Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 18 additions & 1 deletion .github/workflows/startup-health-aot.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ name: Startup health Native AOT
on:
pull_request:
paths:
- 'src/GeneralUpdate.Core/StartupHealth/**'
- 'src/GeneralUpdate.Core/**'
- 'tests/StartupHealthProbe/**'
- '.github/workflows/startup-health-aot.yml'

Expand All @@ -28,3 +28,20 @@ jobs:
[System.IO.File]::WriteAllText($ready, 'ready')
& (Join-Path $output 'StartupHealthProbe.exe') native-handoff $state $ready
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
$install = Join-Path $env:RUNNER_TEMP 'snapshot-install'
$source = Join-Path $env:RUNNER_TEMP 'snapshot-source'
$snapshot = Join-Path $install ('.backups\backup-aot-' + [Guid]::NewGuid().ToString('N'))
$attempt = [Guid]::NewGuid().ToString('D')
New-Item -ItemType Directory -Force $install, $source | Out-Null
[System.IO.File]::WriteAllText((Join-Path $source 'state.txt'), 'snapshot-content')
$manifestHash = & (Join-Path $output 'StartupHealthProbe.exe') snapshot-create $install $attempt $source $snapshot
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
$manifestHash = ($manifestHash | Select-Object -Last 1).Trim()
if ($manifestHash -notmatch '^[0-9A-F]{64}$') { throw 'Snapshot manifest identity was not emitted.' }
$verified = & (Join-Path $output 'StartupHealthProbe.exe') snapshot-verify $install $attempt $snapshot $manifestHash
if ($LASTEXITCODE -ne 0 -or ($verified | Select-Object -Last 1).Trim() -ne 'verified') { throw 'Persisted snapshot was not verified after restart.' }
Write-Host 'Native AOT snapshot verified after restart.'
[System.IO.File]::WriteAllText((Join-Path $snapshot 'state.txt'), 'SNAPSHOT-CONTENT')
$rejected = & (Join-Path $output 'StartupHealthProbe.exe') snapshot-verify $install $attempt $snapshot $manifestHash
if ($LASTEXITCODE -ne 0 -or ($rejected | Select-Object -Last 1).Trim() -ne 'rejected') { throw 'Tampered snapshot was not rejected.' }
Write-Host 'Native AOT tampered snapshot rejected.'
66 changes: 48 additions & 18 deletions docs/durable-update-attempts.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,32 +57,62 @@ tenant/record/attempt/installation/snapshot binding before treating these
fields as trusted evidence. Adding a snapshot content digest alone cannot
establish that trust.

For the current strict Core consumer, binding now publishes a deterministic
manifest under the attempt journal. It identifies the attempt, normalized
installation and snapshot paths, and an ordinally sorted inventory of files and
directories; each file entry records its length and SHA-256 content digest.
The journal stores the manifest digest, and `SnapshotManifestHash` travels in
the process contract. Core requires the contract value to match the journal
and re-hashes the complete exact snapshot before applying packages. Missing,
extra, renamed, reparse-point, or changed entries and legacy v1 bound records
without a manifest are rejected; there is no latest-backup fallback. Such v1
records remain pinned rather than being upgraded or silently downgraded.
The installation binding is the absolute path returned by `Path.GetFullPath`,
not an OS volume or directory file ID; the manifest covers file bytes and
paths, not ACLs or other metadata.

The attempt journal uses atomic state-file publication and an OS-released
cross-process lock. `CleanBackup` takes the same lock while reading pins and
deleting candidates. Reserved and bound paths are excluded from retention; a
corrupt state file causes cleanup to fail rather than risk deleting an
unreadable pin. The attempt-specific staging/publish path avoids overwriting a
prior attempt snapshot through the opt-in Core path.
prior attempt snapshot through the opt-in Core path. File contents and manifest
bytes are flushed before publication, but directory entries are not explicitly
fsynced: atomic rename and `Flush(true)` are not a guarantee against every
power-loss or filesystem failure. Incomplete publication remains reserved or
is rejected on reopening.

## Reliability boundary
## Reliability and trust boundary

The record binds an attempt to a **path**, not to an immutable snapshot
identity. This layer does not hash or verify a file manifest, prevent a
same-permission external writer from modifying that directory, or coordinate
with older binaries and external cleanup tools that do not use the journal
lock. Consequently it does not claim global snapshot immutability or a
filesystem-wide fence. The installing application should be quiescent during
backup; operators must protect the installation and journal from untrusted
writers.
The journal binds an attempt and installation to an exact **absolute path and
observed content identity**, not to an immutable snapshot. Relative manifest
entries use NFC-normalized segments and `/` separators. The manifest prevents the
current consumer from applying a snapshot that does not match the journal at
verification time, and the strict backup traversal rejects observed reparse
points and non-portable or colliding path names. These path-based checks do not
use OS-specific no-follow handles and cannot exclude a concurrent non-cooperating
writer swapping entries between enumeration, opening, hashing, and use. The
verification-to-apply interval is also not protected by an OS write fence.
On Unix, `FileAttributes` does not prove that a non-directory entry is a
regular file; opening a FIFO or device can block or have side effects. Durable
mode must not be enabled on an installation containing such entries, and a
future platform-specific no-follow, nonblocking regular-file check is required
before this path is safe for untrusted filesystem contents.
Hashes are integrity comparisons, not a fencing mechanism, signature, or
authorization proof; they do not prevent same-permission writers from changing
both files and unauthenticated metadata. The installing application should be
quiescent during backup and apply, and operators must protect the installation,
journal, and IPC temp directory from untrusted writers.

`ClaimRecovery` is a cooperative journal compare-and-swap: simultaneous
claimants using one expected fence cannot both win, and a later claim makes an
earlier claim stale for journal completion. It does not fence writes to the
installation tree and does not establish that a previous owner is dead. A
caller may advance a fence only after independently establishing that the
prior claimant is no longer authorized. No `RecoveryOwner` is designated here.
`Complete` only records a caller-supplied external outcome; it does not inspect
business readiness or restore files.
`ClaimRecovery` is a cooperative journal compare-and-swap that now also
requires the bound manifest to verify: simultaneous claimants using one
expected fence cannot both win, and a later claim makes an earlier claim stale
for journal completion. It does not fence writes to the installation tree and
does not establish that a previous owner is dead. A caller may advance a fence
only after independently establishing that the prior claimant is no longer
authorized. No `RecoveryOwner` is designated here. `Complete` only records a
caller-supplied external outcome; it does not inspect business readiness or
restore files.

For opted-in attempts, Core's legacy `AbstractStrategy.TryRollback` is
suppressed, and success reports from ClientStrategy, AbstractStrategy,
Expand Down
11 changes: 7 additions & 4 deletions src/GeneralUpdate.Core/Bootstrap/GeneralUpdateBootstrap.cs
Original file line number Diff line number Diff line change
Expand Up @@ -435,6 +435,7 @@ private void InitializeFromEnvironment()
ReportType = processInfo.ReportType,
DurableUpdateAttemptId = processInfo.DurableUpdateAttemptId,
AttemptJournalDirectory = processInfo.AttemptJournalDirectory,
SnapshotManifestHash = processInfo.SnapshotManifestHash,
DisableLegacyRollback = processInfo.DisableLegacyRollback,
Files = processInfo.Files ?? BlackDefaults.DefaultFiles,
Formats = processInfo.Formats ?? BlackDefaults.DefaultFormats,
Expand All @@ -447,8 +448,7 @@ private void InitializeFromEnvironment()
throw new InvalidDataException("The update process contract contains an empty durable attempt ID.");
var expectedJournal = DurableUpdateAttemptStore.GetDirectory(processInfo.InstallPath);
if (string.IsNullOrWhiteSpace(processInfo.AttemptJournalDirectory) ||
!string.Equals(Path.GetFullPath(processInfo.AttemptJournalDirectory), expectedJournal,
StringComparison.OrdinalIgnoreCase))
!DurableUpdateAttemptStore.PathsEqual(processInfo.AttemptJournalDirectory, expectedJournal))
throw new InvalidDataException("The update process contract has a mismatched attempt journal directory.");
if (!processInfo.DisableLegacyRollback)
throw new InvalidDataException("A durable update attempt must disable the legacy Core rollback path.");
Expand All @@ -458,10 +458,13 @@ private void InitializeFromEnvironment()
.GetAttempt(processInfo.DurableUpdateAttemptId.Value);
if (attempt.Status != DurableUpdateAttemptStatus.SnapshotBound ||
string.IsNullOrWhiteSpace(attempt.SnapshotPath) ||
!string.Equals(Path.GetFullPath(attempt.SnapshotPath), Path.GetFullPath(processInfo.BackupDirectory),
StringComparison.OrdinalIgnoreCase) ||
!DurableUpdateAttemptStore.PathsEqual(attempt.SnapshotPath, processInfo.BackupDirectory) ||
!Directory.Exists(attempt.SnapshotPath))
throw new InvalidDataException("The update process contract does not match the journal's bound snapshot.");
if (string.IsNullOrWhiteSpace(processInfo.SnapshotManifestHash))
throw new InvalidDataException("The update process contract is missing the bound snapshot content identity.");
new DurableUpdateAttemptStore(processInfo.InstallPath).VerifySnapshotContent(
processInfo.DurableUpdateAttemptId.Value, processInfo.BackupDirectory, processInfo.SnapshotManifestHash);
}

StorageManager.BlackMatcher = BlackMatcher.FromConfigInfo(_configInfo);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,7 @@ public static ProcessContract MapToProcessContract(
processInfo.DurableUpdateAttemptId = source.DurableUpdateAttemptId;
if (source.DurableUpdateAttemptId.HasValue)
{
processInfo.SnapshotManifestHash = source.SnapshotManifestHash;
processInfo.AttemptJournalDirectory = DurableUpdateAttemptStore.GetDirectory(source.InstallPath);
processInfo.DisableLegacyRollback = true;
}
Expand Down
4 changes: 4 additions & 0 deletions src/GeneralUpdate.Core/Configuration/ProcessContract.cs
Original file line number Diff line number Diff line change
Expand Up @@ -408,6 +408,10 @@ public ProcessContract(string appName
[JsonPropertyName("DurableUpdateAttemptId")]
public Guid? DurableUpdateAttemptId { get; set; }

/// <summary>SHA-256 identity of the bound durable snapshot manifest.</summary>
[JsonPropertyName("SnapshotManifestHash")]
public string? SnapshotManifestHash { get; set; }

/// <summary>Stable local journal directory for the durable update attempt.</summary>
[JsonPropertyName("AttemptJournalDirectory")]
public string? AttemptJournalDirectory { get; set; }
Expand Down
3 changes: 3 additions & 0 deletions src/GeneralUpdate.Core/Configuration/UpdateContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,9 @@ public class UpdateContext : UpdateConfiguration
/// </summary>
public string? AttemptJournalDirectory { get; set; }

/// <summary>SHA-256 identity of the bound durable snapshot manifest.</summary>
public string? SnapshotManifestHash { get; set; }

/// <summary>
/// When true, the in-process legacy rollback path must not compete with an external
/// recovery protocol. This does not enable or designate an external recovery owner.
Expand Down
67 changes: 61 additions & 6 deletions src/GeneralUpdate.Core/FileSystem/StorageManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -530,7 +530,18 @@ public static void Backup(string sourcePath, string backupPath, IReadOnlyList<st
=> Backup(sourcePath, backupPath, directoryNames, createOnly: false);

public static void Backup(string sourcePath, string backupPath, IReadOnlyList<string> directoryNames, bool createOnly)
=> Backup(sourcePath, backupPath, directoryNames, createOnly, rejectReparsePoints: false);

/// <summary>
/// Creates a backup with optional rejection of filesystem reparse points.
/// Reparse-point rejection is intended for create-only durable snapshots.
/// </summary>
public static void Backup(string sourcePath, string backupPath, IReadOnlyList<string> directoryNames,
bool createOnly, bool rejectReparsePoints)
{
if (rejectReparsePoints && !createOnly)
throw new ArgumentException("Reparse-point rejection is supported only for create-only backups.", nameof(createOnly));

// Merge default backup-exclusion prefixes with user-configured directories.
// This ensures backup/legacy directories are ALWAYS skipped, preventing
// infinite recursion even when the user passes an empty skip list.
Expand All @@ -539,19 +550,38 @@ public static void Backup(string sourcePath, string backupPath, IReadOnlyList<st

if (createOnly)
{
var backupParent = Path.GetDirectoryName(backupPath)!;
var attemptDirectory = Path.Combine(backupParent, AttemptDirectoryName);
if (rejectReparsePoints)
{
DurableUpdateSnapshotManifest.EnsureNoReparsePointsInPath(sourcePath);
DurableUpdateSnapshotManifest.EnsureNoReparsePointsInExistingPath(backupParent);
Directory.CreateDirectory(attemptDirectory);
DurableUpdateSnapshotManifest.EnsureNoReparsePointsInPath(attemptDirectory);
}
var stagingPath = Path.Combine(
Path.GetDirectoryName(backupPath)!,
backupParent,
AttemptDirectoryName,
".staging-" + Guid.NewGuid().ToString("N"));
try
{
Directory.CreateDirectory(stagingPath);
CopyDirectory(sourcePath, stagingPath, effectiveDirectories);
if (rejectReparsePoints)
DurableUpdateSnapshotManifest.EnsureNoReparsePointsInPath(stagingPath);
CopyDirectory(sourcePath, stagingPath, effectiveDirectories, rejectReparsePoints);
if (rejectReparsePoints)
{
DurableUpdateSnapshotManifest.EnsureNoReparsePointsInPath(sourcePath);
DurableUpdateSnapshotManifest.EnsureNoReparsePointsInPath(stagingPath);
DurableUpdateSnapshotManifest.EnsureNoReparsePointsInExistingPath(backupParent);
}
Directory.Move(stagingPath, backupPath);
if (rejectReparsePoints)
DurableUpdateSnapshotManifest.EnsureNoReparsePointsInPath(backupPath);
}
catch
{
if (Directory.Exists(stagingPath)) DeleteDirectory(stagingPath);
if (!rejectReparsePoints && Directory.Exists(stagingPath)) DeleteDirectory(stagingPath);
throw;
}
return;
Expand All @@ -562,24 +592,49 @@ public static void Backup(string sourcePath, string backupPath, IReadOnlyList<st
CopyDirectory(sourcePath, backupPath, effectiveDirectories);
}

private static void CopyDirectory(string sourceDir, string targetDir, IReadOnlyList<string> directoryNames)
private static void CopyDirectory(string sourceDir, string targetDir, IReadOnlyList<string> directoryNames,
bool rejectReparsePoints = false)
{
if (rejectReparsePoints)
{
DurableUpdateSnapshotManifest.EnsureNoReparsePointsInPath(sourceDir);
DurableUpdateSnapshotManifest.EnsureNoReparsePointsInPath(targetDir);
}

foreach (string dirPath in Directory.GetDirectories(sourceDir, "*", SearchOption.TopDirectoryOnly))
{
if (rejectReparsePoints) DurableUpdateSnapshotManifest.RejectReparsePoint(dirPath);
var dirName = Path.GetFileName(dirPath);
if (!directoryNames.Any(name => dirName.StartsWith(name, StringComparison.OrdinalIgnoreCase)))
{
string newTargetDir = Path.Combine(targetDir, Path.GetFileName(dirPath));
Directory.CreateDirectory(newTargetDir);
CopyDirectory(dirPath, newTargetDir, directoryNames);
CopyDirectory(dirPath, newTargetDir, directoryNames, rejectReparsePoints);
if (rejectReparsePoints) DurableUpdateSnapshotManifest.RejectReparsePoint(dirPath);
}
}

foreach (string filePath in Directory.GetFiles(sourceDir, "*.*", SearchOption.TopDirectoryOnly))
{
if (rejectReparsePoints) DurableUpdateSnapshotManifest.RejectReparsePoint(filePath);
string newFilePath = Path.Combine(targetDir, Path.GetFileName(filePath));
File.Copy(filePath, newFilePath, true);
if (rejectReparsePoints)
{
using var source = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
using var target = new FileStream(newFilePath, FileMode.CreateNew, FileAccess.Write, FileShare.None);
source.CopyTo(target);
target.Flush(true);
DurableUpdateSnapshotManifest.RejectReparsePoint(filePath);
if (new FileInfo(filePath).Length != source.Length)
throw new IOException($"A source file changed while its durable snapshot was being copied: {filePath}");
}
else
{
File.Copy(filePath, newFilePath, true);
}
}

if (rejectReparsePoints) DurableUpdateSnapshotManifest.EnsureNoReparsePointsInPath(sourceDir);
}

/// <summary>
Expand Down
Loading
Loading