diff --git a/.github/workflows/startup-health-aot.yml b/.github/workflows/startup-health-aot.yml
index 0b467c1d..63fa017d 100644
--- a/.github/workflows/startup-health-aot.yml
+++ b/.github/workflows/startup-health-aot.yml
@@ -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'
@@ -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.'
diff --git a/docs/durable-update-attempts.md b/docs/durable-update-attempts.md
index 091f0422..1664e6df 100644
--- a/docs/durable-update-attempts.md
+++ b/docs/durable-update-attempts.md
@@ -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,
diff --git a/src/GeneralUpdate.Core/Bootstrap/GeneralUpdateBootstrap.cs b/src/GeneralUpdate.Core/Bootstrap/GeneralUpdateBootstrap.cs
index 532f2dc5..fb2da645 100644
--- a/src/GeneralUpdate.Core/Bootstrap/GeneralUpdateBootstrap.cs
+++ b/src/GeneralUpdate.Core/Bootstrap/GeneralUpdateBootstrap.cs
@@ -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,
@@ -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.");
@@ -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);
diff --git a/src/GeneralUpdate.Core/Configuration/ConfigurationMapper.cs b/src/GeneralUpdate.Core/Configuration/ConfigurationMapper.cs
index 25513093..4b6468b1 100644
--- a/src/GeneralUpdate.Core/Configuration/ConfigurationMapper.cs
+++ b/src/GeneralUpdate.Core/Configuration/ConfigurationMapper.cs
@@ -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;
}
diff --git a/src/GeneralUpdate.Core/Configuration/ProcessContract.cs b/src/GeneralUpdate.Core/Configuration/ProcessContract.cs
index 036e690b..e95c042a 100644
--- a/src/GeneralUpdate.Core/Configuration/ProcessContract.cs
+++ b/src/GeneralUpdate.Core/Configuration/ProcessContract.cs
@@ -408,6 +408,10 @@ public ProcessContract(string appName
[JsonPropertyName("DurableUpdateAttemptId")]
public Guid? DurableUpdateAttemptId { get; set; }
+ /// SHA-256 identity of the bound durable snapshot manifest.
+ [JsonPropertyName("SnapshotManifestHash")]
+ public string? SnapshotManifestHash { get; set; }
+
/// Stable local journal directory for the durable update attempt.
[JsonPropertyName("AttemptJournalDirectory")]
public string? AttemptJournalDirectory { get; set; }
diff --git a/src/GeneralUpdate.Core/Configuration/UpdateContext.cs b/src/GeneralUpdate.Core/Configuration/UpdateContext.cs
index f27f9af1..448bce80 100644
--- a/src/GeneralUpdate.Core/Configuration/UpdateContext.cs
+++ b/src/GeneralUpdate.Core/Configuration/UpdateContext.cs
@@ -136,6 +136,9 @@ public class UpdateContext : UpdateConfiguration
///
public string? AttemptJournalDirectory { get; set; }
+ /// SHA-256 identity of the bound durable snapshot manifest.
+ public string? SnapshotManifestHash { get; set; }
+
///
/// 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.
diff --git a/src/GeneralUpdate.Core/FileSystem/StorageManager.cs b/src/GeneralUpdate.Core/FileSystem/StorageManager.cs
index 0d5d7cdc..ab7ca9e3 100644
--- a/src/GeneralUpdate.Core/FileSystem/StorageManager.cs
+++ b/src/GeneralUpdate.Core/FileSystem/StorageManager.cs
@@ -530,7 +530,18 @@ public static void Backup(string sourcePath, string backupPath, IReadOnlyList Backup(sourcePath, backupPath, directoryNames, createOnly: false);
public static void Backup(string sourcePath, string backupPath, IReadOnlyList directoryNames, bool createOnly)
+ => Backup(sourcePath, backupPath, directoryNames, createOnly, rejectReparsePoints: false);
+
+ ///
+ /// Creates a backup with optional rejection of filesystem reparse points.
+ /// Reparse-point rejection is intended for create-only durable snapshots.
+ ///
+ public static void Backup(string sourcePath, string backupPath, IReadOnlyList 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.
@@ -539,19 +550,38 @@ public static void Backup(string sourcePath, string backupPath, IReadOnlyList directoryNames)
+ private static void CopyDirectory(string sourceDir, string targetDir, IReadOnlyList 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);
}
///
diff --git a/src/GeneralUpdate.Core/StartupHealth/DurableUpdateAttemptStore.cs b/src/GeneralUpdate.Core/StartupHealth/DurableUpdateAttemptStore.cs
index 4eaa68a5..27f61d6d 100644
--- a/src/GeneralUpdate.Core/StartupHealth/DurableUpdateAttemptStore.cs
+++ b/src/GeneralUpdate.Core/StartupHealth/DurableUpdateAttemptStore.cs
@@ -13,7 +13,8 @@ namespace GeneralUpdate.Core.StartupHealth;
///
public sealed class DurableUpdateAttemptStore
{
- private const int FormatVersion = 1;
+ private const int LegacyFormatVersion = 1;
+ private const int FormatVersion = 2;
public const string RequiredAttemptIdEnvironmentVariable = "GENERALUPDATE_REQUIRED_DURABLE_ATTEMPT_ID";
private readonly string _installPath;
private readonly string _directory;
@@ -35,6 +36,12 @@ public static string GetDirectory(string installPath)
GeneralUpdate.Core.FileSystem.StorageManager.AttemptDirectoryName);
}
+ internal static string GetSnapshotManifestPath(string installPath, Guid attemptId)
+ {
+ ValidateId(attemptId);
+ return DurableUpdateSnapshotManifest.ManifestPath(installPath, attemptId);
+ }
+
///
/// Creates a new attempt. IDs are caller-selected and must never be reused, including
/// after an interrupted creation.
@@ -73,8 +80,8 @@ public void ReserveSnapshot(Guid attemptId, string snapshotPath)
}
///
- /// Binds the exact reserved path after the real backup operation has completed.
- /// Missing or mismatched paths fail explicitly; no latest-backup fallback is used.
+ /// Publishes a content manifest and binds it to the exact reserved path after
+ /// the real backup operation has completed. No latest-backup fallback is used.
///
public void BindSnapshot(Guid attemptId, string snapshotPath)
{
@@ -88,11 +95,36 @@ public void BindSnapshot(Guid attemptId, string snapshotPath)
throw new InvalidOperationException("The completed backup does not match the reserved snapshot path.");
if (!Directory.Exists(fullPath))
throw new DirectoryNotFoundException($"The reserved update snapshot was not created: {fullPath}");
+ if (state.JournalVersion == LegacyFormatVersion)
+ throw new InvalidOperationException("A legacy reserved snapshot cannot be promoted without a content identity.");
+ state.SnapshotManifestHash = DurableUpdateSnapshotManifest.CreateAndPublish(_installPath, attemptId, fullPath);
state.Status = DurableUpdateAttemptStatus.SnapshotBound;
WriteState(StatePath(attemptId), state);
});
}
+ ///
+ /// Verifies the bound manifest identity and every file and directory in the exact snapshot.
+ /// This detects changed content but does not prevent writes after verification.
+ ///
+ public void VerifySnapshotContent(Guid attemptId, string snapshotPath, string expectedManifestHash)
+ {
+ ValidateId(attemptId);
+ var fullPath = ValidateSnapshotPath(snapshotPath);
+ WithLock(() =>
+ {
+ var state = ReadState(attemptId);
+ RequireStatus(state, DurableUpdateAttemptStatus.SnapshotBound);
+ if (state.SnapshotPath == null || !PathEquals(state.SnapshotPath, fullPath))
+ throw new InvalidDataException("The process contract does not match the journal's bound snapshot.");
+ if (string.IsNullOrEmpty(state.SnapshotManifestHash))
+ throw new InvalidDataException("The bound snapshot has no verifiable content identity.");
+ if (!string.Equals(state.SnapshotManifestHash, expectedManifestHash, StringComparison.Ordinal))
+ throw new InvalidDataException("The process contract does not match the journal's snapshot content identity.");
+ DurableUpdateSnapshotManifest.Verify(_installPath, attemptId, fullPath, state.SnapshotManifestHash);
+ });
+ }
+
/// Reopens the durable attempt after a process restart.
public DurableUpdateAttemptRecord GetAttempt(Guid attemptId)
{
@@ -116,6 +148,9 @@ public DurableUpdateAttemptClaim ClaimRecovery(Guid attemptId, long expectedFenc
throw new InvalidOperationException("Recovery requires an active attempt with a bound snapshot.");
if (state.SnapshotPath == null || !Directory.Exists(state.SnapshotPath))
throw new DirectoryNotFoundException($"The bound update snapshot is missing: {state.SnapshotPath}");
+ if (string.IsNullOrEmpty(state.SnapshotManifestHash))
+ throw new InvalidDataException("The bound update snapshot has no verifiable content identity.");
+ DurableUpdateSnapshotManifest.Verify(_installPath, attemptId, state.SnapshotPath, state.SnapshotManifestHash);
if (state.Fence != expectedFence)
throw new InvalidOperationException($"Stale recovery fence {expectedFence}; current fence is {state.Fence}.");
state.Fence = checked(state.Fence + 1);
@@ -193,9 +228,13 @@ private string ValidateSnapshotPath(string path)
if (string.IsNullOrWhiteSpace(path)) throw new ArgumentException("A snapshot path is required.", nameof(path));
var fullPath = Path.GetFullPath(path);
var backupRoot = Path.GetFullPath(Path.Combine(_installPath, GeneralUpdate.Core.FileSystem.StorageManager.BackupRootDirectory));
+ var pathComparison = Path.DirectorySeparatorChar == '\\'
+ ? StringComparison.OrdinalIgnoreCase
+ : StringComparison.Ordinal;
if (!PathEquals(Path.GetDirectoryName(fullPath)!, backupRoot) ||
- !Path.GetFileName(fullPath).StartsWith("backup-", StringComparison.OrdinalIgnoreCase))
+ !Path.GetFileName(fullPath).StartsWith("backup-", pathComparison))
throw new ArgumentException("The snapshot must be a direct backup-{name} child of the installation backup directory.", nameof(path));
+ DurableUpdateSnapshotManifest.EnsureNoReparsePointsInExistingPath(Path.GetDirectoryName(fullPath)!);
return fullPath;
}
@@ -203,7 +242,10 @@ private string ValidateSnapshotPath(string path)
private TResult WithLock(Func action)
{
+ DurableUpdateSnapshotManifest.EnsureNoReparsePointsInExistingPath(_installPath);
+ DurableUpdateSnapshotManifest.EnsureNoReparsePointsInExistingPath(_directory);
Directory.CreateDirectory(_directory);
+ DurableUpdateSnapshotManifest.EnsureNoReparsePointsInPath(_directory);
using (AcquireLock(_installPath))
return action();
}
@@ -259,7 +301,9 @@ private static AttemptState ReadStateFile(string path, Guid? expectedId = null)
if (!File.Exists(path)) throw new FileNotFoundException("Durable update attempt was not found.", path);
try
{
+ DurableUpdateSnapshotManifest.RejectReparsePointIfPresent(path);
var fileBytes = File.ReadAllBytes(path);
+ DurableUpdateSnapshotManifest.RejectReparsePoint(path);
if (fileBytes.Length < 36) throw new InvalidDataException("Truncated update attempt journal.");
var payloadLength = fileBytes.Length - 32;
var payload = new byte[payloadLength];
@@ -273,7 +317,9 @@ private static AttemptState ReadStateFile(string path, Guid? expectedId = null)
using var stream = new MemoryStream(payload, writable: false);
using var reader = new BinaryReader(stream);
- if (reader.ReadInt32() != FormatVersion) throw new InvalidDataException("Unsupported update attempt journal format.");
+ var journalVersion = reader.ReadInt32();
+ if (journalVersion != LegacyFormatVersion && journalVersion != FormatVersion)
+ throw new InvalidDataException("Unsupported update attempt journal format.");
var idBytes = reader.ReadBytes(16);
if (idBytes.Length != 16) throw new InvalidDataException("Truncated update attempt identifier.");
var id = new Guid(idBytes);
@@ -294,6 +340,15 @@ private static AttemptState ReadStateFile(string path, Guid? expectedId = null)
}
var hasSnapshot = reader.ReadBoolean();
var snapshotPath = hasSnapshot ? reader.ReadString() : null;
+ string? snapshotManifestHash = null;
+ if (journalVersion >= FormatVersion && reader.ReadBoolean())
+ {
+ snapshotManifestHash = reader.ReadString();
+ if (snapshotManifestHash.Length != 64 ||
+ snapshotManifestHash.Any(character => !((character >= '0' && character <= '9') ||
+ (character >= 'A' && character <= 'F'))))
+ throw new InvalidDataException("Invalid update snapshot manifest identity.");
+ }
if (stream.Position != stream.Length) throw new InvalidDataException("Unexpected trailing update attempt data.");
if ((status == DurableUpdateAttemptStatus.Pending) != (snapshotPath == null))
throw new InvalidDataException("Update attempt snapshot state is inconsistent.");
@@ -304,7 +359,9 @@ private static AttemptState ReadStateFile(string path, Guid? expectedId = null)
Status = status,
Fence = fence,
ClaimId = claimId,
- SnapshotPath = snapshotPath
+ SnapshotPath = snapshotPath,
+ SnapshotManifestHash = snapshotManifestHash,
+ JournalVersion = journalVersion
};
}
catch (EndOfStreamException ex)
@@ -323,7 +380,7 @@ private static void WriteState(string path, AttemptState state)
{
using (var writer = new BinaryWriter(memory, System.Text.Encoding.UTF8, true))
{
- writer.Write(FormatVersion);
+ writer.Write(state.JournalVersion);
writer.Write(state.AttemptId.ToByteArray());
writer.Write((int)state.Status);
writer.Write(state.Fence);
@@ -331,6 +388,11 @@ private static void WriteState(string path, AttemptState state)
if (state.ClaimId.HasValue) writer.Write(state.ClaimId.Value.ToByteArray());
writer.Write(state.SnapshotPath != null);
if (state.SnapshotPath != null) writer.Write(state.SnapshotPath);
+ if (state.JournalVersion >= FormatVersion)
+ {
+ writer.Write(state.SnapshotManifestHash != null);
+ if (state.SnapshotManifestHash != null) writer.Write(state.SnapshotManifestHash);
+ }
writer.Flush();
}
payload = memory.ToArray();
@@ -344,6 +406,7 @@ private static void WriteState(string path, AttemptState state)
stream.Write(hash, 0, hash.Length);
stream.Flush(true);
}
+ DurableUpdateSnapshotManifest.RejectReparsePointIfPresent(path);
if (File.Exists(path)) File.Replace(temporary, path, null);
else File.Move(temporary, path);
}
@@ -360,10 +423,13 @@ private static void RequireStatus(AttemptState state, DurableUpdateAttemptStatus
}
private static DurableUpdateAttemptRecord ToRecord(AttemptState state) =>
- new(state.AttemptId, state.Status, state.SnapshotPath, state.Fence, state.ClaimId);
+ new(state.AttemptId, state.Status, state.SnapshotPath, state.Fence, state.ClaimId, state.SnapshotManifestHash);
+
+ internal static bool PathsEqual(string left, string right) =>
+ string.Equals(Path.GetFullPath(left), Path.GetFullPath(right),
+ Path.DirectorySeparatorChar == '\\' ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
- private static bool PathEquals(string left, string right) =>
- string.Equals(Path.GetFullPath(left), Path.GetFullPath(right), StringComparison.OrdinalIgnoreCase);
+ private static bool PathEquals(string left, string right) => PathsEqual(left, right);
private static void ValidateId(Guid id)
{
@@ -376,8 +442,10 @@ private sealed class AttemptState
public Guid AttemptId { get; }
public DurableUpdateAttemptStatus Status { get; set; } = DurableUpdateAttemptStatus.Pending;
public string? SnapshotPath { get; set; }
+ public string? SnapshotManifestHash { get; set; }
public long Fence { get; set; }
public Guid? ClaimId { get; set; }
+ public int JournalVersion { get; set; } = FormatVersion;
}
}
@@ -398,13 +466,15 @@ public enum DurableUpdateAttemptCompletion
public sealed class DurableUpdateAttemptRecord
{
- internal DurableUpdateAttemptRecord(Guid attemptId, DurableUpdateAttemptStatus status, string? snapshotPath, long fence, Guid? claimId)
+ internal DurableUpdateAttemptRecord(Guid attemptId, DurableUpdateAttemptStatus status, string? snapshotPath, long fence,
+ Guid? claimId, string? snapshotManifestHash)
{
AttemptId = attemptId;
Status = status;
SnapshotPath = snapshotPath;
Fence = fence;
ClaimId = claimId;
+ SnapshotManifestHash = snapshotManifestHash;
}
public Guid AttemptId { get; }
@@ -412,6 +482,7 @@ internal DurableUpdateAttemptRecord(Guid attemptId, DurableUpdateAttemptStatus s
public string? SnapshotPath { get; }
public long Fence { get; }
public Guid? ClaimId { get; }
+ public string? SnapshotManifestHash { get; }
}
public sealed class DurableUpdateAttemptClaim
diff --git a/src/GeneralUpdate.Core/StartupHealth/DurableUpdateSnapshotManifest.cs b/src/GeneralUpdate.Core/StartupHealth/DurableUpdateSnapshotManifest.cs
new file mode 100644
index 00000000..c0edd84b
--- /dev/null
+++ b/src/GeneralUpdate.Core/StartupHealth/DurableUpdateSnapshotManifest.cs
@@ -0,0 +1,395 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Security.Cryptography;
+using System.Text;
+
+namespace GeneralUpdate.Core.StartupHealth;
+
+internal static class DurableUpdateSnapshotManifest
+{
+ private const int FormatVersion = 1;
+ private const int MaximumManifestBytes = 64 * 1024 * 1024;
+ private const int MaximumEntries = 500_000;
+
+ internal static string ManifestPath(string installPath, Guid attemptId) =>
+ Path.Combine(DurableUpdateAttemptStore.GetDirectory(installPath), attemptId.ToString("N") + ".manifest");
+
+ internal static string CreateAndPublish(string installPath, Guid attemptId, string snapshotPath)
+ {
+ var fullInstallPath = Path.GetFullPath(installPath);
+ var fullSnapshotPath = Path.GetFullPath(snapshotPath);
+ EnsureNoReparsePointsInPath(fullInstallPath);
+ EnsureNoReparsePointsInPath(fullSnapshotPath);
+
+ var entries = CaptureEntries(fullSnapshotPath);
+ var bytes = Serialize(attemptId, fullInstallPath, fullSnapshotPath, entries);
+ if (bytes.Length > MaximumManifestBytes)
+ throw new InvalidDataException("The update snapshot manifest exceeds the supported size.");
+
+ var path = ManifestPath(fullInstallPath, attemptId);
+ var directory = Path.GetDirectoryName(path)!;
+ EnsureNoReparsePointsInPath(directory);
+ RejectReparsePointIfPresent(path);
+ var temporary = path + "." + Guid.NewGuid().ToString("N") + ".tmp";
+ try
+ {
+ using (var stream = new FileStream(temporary, FileMode.CreateNew, FileAccess.Write, FileShare.None))
+ {
+ stream.Write(bytes, 0, bytes.Length);
+ stream.Flush(true);
+ }
+ File.Move(temporary, path);
+ }
+ finally
+ {
+ if (File.Exists(temporary)) File.Delete(temporary);
+ }
+
+ return ToHex(Hash(bytes));
+ }
+
+ internal static void Verify(
+ string installPath,
+ Guid attemptId,
+ string snapshotPath,
+ string expectedManifestHash)
+ {
+ if (!IsSha256(expectedManifestHash))
+ throw new InvalidDataException("The update snapshot manifest identity is missing or malformed.");
+
+ var fullInstallPath = Path.GetFullPath(installPath);
+ var fullSnapshotPath = Path.GetFullPath(snapshotPath);
+ EnsureNoReparsePointsInPath(fullInstallPath);
+ EnsureNoReparsePointsInPath(fullSnapshotPath);
+
+ var path = ManifestPath(fullInstallPath, attemptId);
+ EnsureNoReparsePointsInExistingPath(Path.GetDirectoryName(path)!);
+ RejectReparsePoint(path);
+ var info = new FileInfo(path);
+ if (!info.Exists) throw new FileNotFoundException("The update snapshot manifest is missing.", path);
+ if (info.Length <= 0 || info.Length > MaximumManifestBytes)
+ throw new InvalidDataException("The update snapshot manifest has an unsupported size.");
+
+ var bytes = File.ReadAllBytes(path);
+ RejectReparsePoint(path);
+ if (!string.Equals(ToHex(Hash(bytes)), expectedManifestHash, StringComparison.Ordinal))
+ throw new InvalidDataException("The update snapshot manifest identity does not match the attempt journal.");
+
+ var manifest = Deserialize(bytes);
+ if (manifest.AttemptId != attemptId ||
+ !PathEquals(manifest.InstallPath, fullInstallPath) ||
+ !PathEquals(manifest.SnapshotPath, fullSnapshotPath))
+ throw new InvalidDataException("The update snapshot manifest is bound to another attempt, installation, or snapshot.");
+
+ VerifyEntries(fullSnapshotPath, manifest.Entries);
+ }
+
+ internal static void EnsureNoReparsePointsInExistingPath(string path)
+ {
+ var fullPath = Path.GetFullPath(path);
+ var root = Path.GetPathRoot(fullPath);
+ if (string.IsNullOrEmpty(root)) throw new InvalidDataException("A filesystem-rooted path is required.");
+ var current = root;
+ if (File.Exists(root) || Directory.Exists(root)) RejectReparsePoint(root);
+ var remainder = fullPath.Substring(root.Length);
+ foreach (var segment in remainder.Split(new[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar },
+ StringSplitOptions.RemoveEmptyEntries))
+ {
+ current = Path.Combine(current, segment);
+ try
+ {
+ RejectReparsePoint(current);
+ }
+ catch (FileNotFoundException)
+ {
+ return;
+ }
+ catch (DirectoryNotFoundException)
+ {
+ return;
+ }
+ }
+ }
+
+ internal static void EnsureNoReparsePointsInPath(string path)
+ {
+ var fullPath = Path.GetFullPath(path);
+ EnsureNoReparsePointsInExistingPath(fullPath);
+ if (!Directory.Exists(fullPath))
+ throw new DirectoryNotFoundException($"The required directory does not exist: {fullPath}");
+
+ var root = Path.GetPathRoot(fullPath)!;
+ var current = root;
+ var remainder = fullPath.Substring(root.Length);
+ foreach (var segment in remainder.Split(new[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar },
+ StringSplitOptions.RemoveEmptyEntries))
+ {
+ current = Path.Combine(current, segment);
+ var attributes = File.GetAttributes(current);
+ if ((attributes & FileAttributes.Directory) == 0)
+ throw new InvalidDataException($"A directory was expected in the path: {current}");
+ }
+ }
+
+ internal static void RejectReparsePoint(string path)
+ {
+ var attributes = File.GetAttributes(path);
+ if ((attributes & FileAttributes.ReparsePoint) != 0)
+ throw new InvalidDataException($"Reparse points are not permitted in durable update snapshots: {path}");
+ }
+
+ internal static void RejectReparsePointIfPresent(string path)
+ {
+ try
+ {
+ RejectReparsePoint(path);
+ }
+ catch (FileNotFoundException)
+ {
+ return;
+ }
+ catch (DirectoryNotFoundException)
+ {
+ return;
+ }
+ }
+
+ private static List CaptureEntries(string root)
+ {
+ var entries = new List();
+ CaptureDirectory(root, string.Empty, entries);
+ var ordered = entries.OrderBy(entry => entry.Path, StringComparer.Ordinal).ToList();
+ var portablePaths = new HashSet(StringComparer.OrdinalIgnoreCase);
+ foreach (var entry in ordered)
+ {
+ if (!portablePaths.Add(entry.Path))
+ throw new InvalidDataException($"Snapshot paths collide on a case-insensitive filesystem: {entry.Path}");
+ }
+ return ordered;
+ }
+
+ private static void CaptureDirectory(string directory, string relativeDirectory, List entries)
+ {
+ EnsureNoReparsePointsInPath(directory);
+ foreach (var path in Directory.GetFileSystemEntries(directory)
+ .OrderBy(entry => Path.GetFileName(entry), StringComparer.Ordinal))
+ {
+ RejectReparsePoint(path);
+ var name = Path.GetFileName(path);
+ ValidateSegment(name);
+ var relativePath = relativeDirectory.Length == 0 ? name : relativeDirectory + "/" + name;
+ var attributes = File.GetAttributes(path);
+ if ((attributes & FileAttributes.Directory) != 0)
+ {
+ EnsureEntryLimit(entries);
+ entries.Add(new Entry(relativePath, true, 0, Array.Empty()));
+ CaptureDirectory(path, relativePath, entries);
+ RejectReparsePoint(path);
+ }
+ else
+ {
+ using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
+ var length = stream.Length;
+ byte[] hash;
+ using (var sha = SHA256.Create()) hash = sha.ComputeHash(stream);
+ RejectReparsePoint(path);
+ if (new FileInfo(path).Length != length)
+ throw new IOException($"A snapshot file changed while its manifest was being created: {path}");
+ EnsureEntryLimit(entries);
+ entries.Add(new Entry(relativePath, false, length, hash));
+ }
+ }
+ EnsureNoReparsePointsInPath(directory);
+ }
+
+ private static byte[] Serialize(Guid attemptId, string installPath, string snapshotPath, IReadOnlyList entries)
+ {
+ using var memory = new MemoryStream();
+ using (var writer = new BinaryWriter(memory, Encoding.UTF8, true))
+ {
+ writer.Write(FormatVersion);
+ writer.Write(attemptId.ToByteArray());
+ writer.Write(installPath);
+ writer.Write(snapshotPath);
+ writer.Write(entries.Count);
+ foreach (var entry in entries)
+ {
+ writer.Write(entry.Path);
+ writer.Write(entry.IsDirectory);
+ if (entry.IsDirectory) continue;
+ writer.Write(entry.Length);
+ writer.Write(entry.Hash);
+ }
+ }
+ return memory.ToArray();
+ }
+
+ private static Manifest Deserialize(byte[] bytes)
+ {
+ try
+ {
+ using var memory = new MemoryStream(bytes, writable: false);
+ using var reader = new BinaryReader(memory, Encoding.UTF8);
+ if (reader.ReadInt32() != FormatVersion)
+ throw new InvalidDataException("Unsupported update snapshot manifest format.");
+ var idBytes = reader.ReadBytes(16);
+ if (idBytes.Length != 16) throw new InvalidDataException("Truncated update snapshot manifest attempt ID.");
+ var attemptId = new Guid(idBytes);
+ var installPath = reader.ReadString();
+ var snapshotPath = reader.ReadString();
+ var count = reader.ReadInt32();
+ if (count < 0 || count > MaximumEntries)
+ throw new InvalidDataException("The update snapshot manifest has an unsupported entry count.");
+
+ var entries = new List(count);
+ var portablePaths = new HashSet(StringComparer.OrdinalIgnoreCase);
+ string? previousPath = null;
+ for (var index = 0; index < count; index++)
+ {
+ var relativePath = reader.ReadString();
+ ValidateRelativePath(relativePath);
+ if (!portablePaths.Add(relativePath))
+ throw new InvalidDataException("Update snapshot manifest paths collide on a case-insensitive filesystem.");
+ if (previousPath != null && string.Compare(previousPath, relativePath, StringComparison.Ordinal) >= 0)
+ throw new InvalidDataException("Update snapshot manifest entries are not uniquely sorted.");
+ previousPath = relativePath;
+ var isDirectory = reader.ReadBoolean();
+ if (isDirectory)
+ {
+ entries.Add(new Entry(relativePath, true, 0, Array.Empty()));
+ continue;
+ }
+
+ var length = reader.ReadInt64();
+ var hash = reader.ReadBytes(32);
+ if (length < 0 || hash.Length != 32)
+ throw new InvalidDataException("Invalid update snapshot manifest file entry.");
+ entries.Add(new Entry(relativePath, false, length, hash));
+ }
+ if (memory.Position != memory.Length)
+ throw new InvalidDataException("Unexpected trailing update snapshot manifest data.");
+ return new Manifest(attemptId, installPath, snapshotPath, entries);
+ }
+ catch (EndOfStreamException ex)
+ {
+ throw new InvalidDataException("Truncated update snapshot manifest.", ex);
+ }
+ }
+
+ private static void VerifyEntries(string root, IReadOnlyList expectedEntries)
+ {
+ var actualEntries = CaptureEntries(root);
+ if (actualEntries.Count != expectedEntries.Count)
+ throw new InvalidDataException("The update snapshot contents do not match the bound manifest.");
+
+ for (var index = 0; index < expectedEntries.Count; index++)
+ {
+ var expected = expectedEntries[index];
+ var actual = actualEntries[index];
+ if (!string.Equals(expected.Path, actual.Path, StringComparison.Ordinal) ||
+ expected.IsDirectory != actual.IsDirectory ||
+ expected.Length != actual.Length ||
+ !FixedTimeEquals(expected.Hash, actual.Hash))
+ throw new InvalidDataException($"The update snapshot entry does not match its manifest: {expected.Path}");
+ }
+ }
+
+ private static void ValidateRelativePath(string path)
+ {
+ if (string.IsNullOrEmpty(path) || path.StartsWith("/", StringComparison.Ordinal))
+ throw new InvalidDataException("An update snapshot manifest path is not relative.");
+ foreach (var segment in path.Split('/'))
+ ValidateSegment(segment);
+ }
+
+ private static void ValidateSegment(string segment)
+ {
+ if (string.IsNullOrEmpty(segment) || segment == "." || segment == ".." ||
+ segment.IndexOfAny(new[] { '<', '>', ':', '"', '/', '\\', '|', '?', '*', '\0' }) >= 0 ||
+ segment.Any(character => character < 32) ||
+ segment.EndsWith(".", StringComparison.Ordinal) || segment.EndsWith(" ", StringComparison.Ordinal) ||
+ !string.Equals(segment, segment.Normalize(NormalizationForm.FormC), StringComparison.Ordinal))
+ throw new InvalidDataException("A snapshot path is not in the supported canonical form.");
+ var baseName = segment.Split('.')[0];
+ if (baseName.Equals("CON", StringComparison.OrdinalIgnoreCase) ||
+ baseName.Equals("PRN", StringComparison.OrdinalIgnoreCase) ||
+ baseName.Equals("AUX", StringComparison.OrdinalIgnoreCase) ||
+ baseName.Equals("NUL", StringComparison.OrdinalIgnoreCase) ||
+ IsNumberedDeviceName(baseName, "COM") || IsNumberedDeviceName(baseName, "LPT"))
+ throw new InvalidDataException("A snapshot path uses a reserved cross-platform device name.");
+ }
+
+ private static bool IsNumberedDeviceName(string name, string prefix) =>
+ name.Length == prefix.Length + 1 &&
+ name.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) &&
+ name[prefix.Length] >= '1' && name[prefix.Length] <= '9';
+
+ private static void EnsureEntryLimit(IReadOnlyCollection entries)
+ {
+ if (entries.Count >= MaximumEntries)
+ throw new InvalidDataException("The update snapshot has too many manifest entries.");
+ }
+
+ private static bool IsSha256(string value)
+ {
+ if (value == null || value.Length != 64) return false;
+ foreach (var character in value)
+ if (!((character >= '0' && character <= '9') || (character >= 'A' && character <= 'F')))
+ return false;
+ return true;
+ }
+
+ private static byte[] Hash(byte[] bytes)
+ {
+ using var sha = SHA256.Create();
+ return sha.ComputeHash(bytes);
+ }
+
+ private static string ToHex(byte[] bytes) => BitConverter.ToString(bytes).Replace("-", string.Empty);
+
+ private static bool FixedTimeEquals(byte[] left, byte[] right)
+ {
+ if (left.Length != right.Length) return false;
+ var difference = 0;
+ for (var index = 0; index < left.Length; index++) difference |= left[index] ^ right[index];
+ return difference == 0;
+ }
+
+ private static bool PathEquals(string left, string right) =>
+ string.Equals(Path.GetFullPath(left), Path.GetFullPath(right),
+ Path.DirectorySeparatorChar == '\\' ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
+
+ private sealed class Entry
+ {
+ internal Entry(string path, bool isDirectory, long length, byte[] hash)
+ {
+ Path = path;
+ IsDirectory = isDirectory;
+ Length = length;
+ Hash = hash;
+ }
+
+ internal string Path { get; }
+ internal bool IsDirectory { get; }
+ internal long Length { get; }
+ internal byte[] Hash { get; }
+ }
+
+ private sealed class Manifest
+ {
+ internal Manifest(Guid attemptId, string installPath, string snapshotPath, List entries)
+ {
+ AttemptId = attemptId;
+ InstallPath = installPath;
+ SnapshotPath = snapshotPath;
+ Entries = entries;
+ }
+
+ internal Guid AttemptId { get; }
+ internal string InstallPath { get; }
+ internal string SnapshotPath { get; }
+ internal List Entries { get; }
+ }
+}
diff --git a/src/GeneralUpdate.Core/Strategy/ClientStrategy.cs b/src/GeneralUpdate.Core/Strategy/ClientStrategy.cs
index 688ae2ae..1bc8383c 100644
--- a/src/GeneralUpdate.Core/Strategy/ClientStrategy.cs
+++ b/src/GeneralUpdate.Core/Strategy/ClientStrategy.cs
@@ -584,7 +584,11 @@ private async Task ExecuteStandardWorkflowAsync()
{
Backup();
if (attemptStore != null)
+ {
attemptStore.BindSnapshot(_configInfo.DurableUpdateAttemptId!.Value, _configInfo.BackupDirectory);
+ _configInfo.SnapshotManifestHash = attemptStore.GetAttempt(_configInfo.DurableUpdateAttemptId.Value)
+ .SnapshotManifestHash ?? throw new InvalidDataException("The durable backup has no content identity.");
+ }
StorageManager.CleanBackup(_configInfo.InstallPath, keepVersions: 3);
}
else
@@ -938,7 +942,8 @@ private void Backup()
$"ClientStrategy: backing up {_configInfo!.InstallPath} -> {_configInfo.BackupDirectory}");
StorageManager.Backup(_configInfo.InstallPath, _configInfo.BackupDirectory,
_configInfo.Directories ?? BlackDefaults.DefaultDirectories,
- createOnly: _configInfo.DurableUpdateAttemptId.HasValue);
+ createOnly: _configInfo.DurableUpdateAttemptId.HasValue,
+ rejectReparsePoints: _configInfo.DurableUpdateAttemptId.HasValue);
}
///
diff --git a/tests/CoreTest/StartupHealth/DurableUpdateAttemptStoreTests.cs b/tests/CoreTest/StartupHealth/DurableUpdateAttemptStoreTests.cs
index b67456b9..aea33403 100644
--- a/tests/CoreTest/StartupHealth/DurableUpdateAttemptStoreTests.cs
+++ b/tests/CoreTest/StartupHealth/DurableUpdateAttemptStoreTests.cs
@@ -29,6 +29,7 @@ public void Attempt_metadata_is_opt_in_and_round_trips_through_the_process_contr
Assert.Null(legacyRequest.DurableUpdateAttemptId);
var legacyContract = new ProcessContract();
Assert.Null(legacyContract.DurableUpdateAttemptId);
+ Assert.Null(legacyContract.SnapshotManifestHash);
Assert.Null(legacyContract.AttemptJournalDirectory);
Assert.False(legacyContract.DisableLegacyRollback);
@@ -45,7 +46,8 @@ public void Attempt_metadata_is_opt_in_and_round_trips_through_the_process_contr
TempPath = _root,
Encoding = Encoding.UTF8,
Format = Format.Zip,
- DurableUpdateAttemptId = attemptId
+ DurableUpdateAttemptId = attemptId,
+ SnapshotManifestHash = new string('A', 64)
};
var contract = ConfigurationMapper.MapToProcessContract(
@@ -55,6 +57,7 @@ public void Attempt_metadata_is_opt_in_and_round_trips_through_the_process_contr
var reopened = JsonSerializer.Deserialize(json, ProcessContractJsonContext.Default.ProcessContract)!;
Assert.Equal(attemptId, reopened.DurableUpdateAttemptId);
+ Assert.Equal(source.SnapshotManifestHash, reopened.SnapshotManifestHash);
Assert.Equal(DurableUpdateAttemptStore.GetDirectory(_root), reopened.AttemptJournalDirectory);
Assert.True(reopened.DisableLegacyRollback);
Assert.Equal(attemptId, ConfigurationMapper.MapToUpdateContext(new UpdateRequest
@@ -88,7 +91,8 @@ public void Real_backup_is_bound_to_its_reserved_path_and_retention_keeps_the_pi
var store = new DurableUpdateAttemptStore(installPath);
store.Begin(attemptId);
store.ReserveSnapshot(attemptId, snapshotPath);
- StorageManager.Backup(sourcePath, snapshotPath, Array.Empty(), createOnly: true);
+ StorageManager.Backup(sourcePath, snapshotPath, Array.Empty(), createOnly: true,
+ rejectReparsePoints: true);
store.BindSnapshot(attemptId, snapshotPath);
for (var index = 0; index < 3; index++)
@@ -121,6 +125,47 @@ public void Attempt_specific_backup_never_deletes_an_existing_destination()
Assert.Equal("existing", File.ReadAllText(Path.Combine(snapshotPath, "file.txt")));
}
+ [Fact]
+ public void Strict_backup_and_bound_snapshot_reject_directory_links()
+ {
+ var installPath = Path.Combine(_root, "link-install");
+ var sourcePath = Path.Combine(_root, "link-source");
+ var externalPath = Path.Combine(_root, "outside");
+ Directory.CreateDirectory(installPath);
+ Directory.CreateDirectory(sourcePath);
+ Directory.CreateDirectory(externalPath);
+ File.WriteAllText(Path.Combine(externalPath, "outside.txt"), "outside");
+ var link = Path.Combine(sourcePath, "linked");
+ CreateDirectoryLink(link, externalPath);
+ try
+ {
+ var snapshotPath = Path.Combine(installPath, StorageManager.BackupRootDirectory, "backup-link");
+ Assert.Throws(() =>
+ StorageManager.Backup(sourcePath, snapshotPath, Array.Empty(), createOnly: true,
+ rejectReparsePoints: true));
+ Assert.False(Directory.Exists(snapshotPath));
+ }
+ finally
+ {
+ Directory.Delete(link);
+ }
+
+ File.WriteAllText(Path.Combine(sourcePath, "data.txt"), "data");
+ var store = CreateBoundAttempt(installPath, sourcePath, out var attemptId);
+ var record = store.GetAttempt(attemptId);
+ var snapshotLink = Path.Combine(record.SnapshotPath!, "linked");
+ CreateDirectoryLink(snapshotLink, externalPath);
+ try
+ {
+ Assert.Throws(() =>
+ store.VerifySnapshotContent(attemptId, record.SnapshotPath!, record.SnapshotManifestHash!));
+ }
+ finally
+ {
+ Directory.Delete(snapshotLink);
+ }
+ }
+
[Fact]
public async Task Client_strategy_creates_and_binds_the_backup_used_by_its_update_workflow()
{
@@ -128,16 +173,30 @@ public async Task Client_strategy_creates_and_binds_the_backup_used_by_its_updat
Directory.CreateDirectory(installPath);
File.WriteAllText(Path.Combine(installPath, "app-state.txt"), "before-update");
var attemptId = Guid.NewGuid();
- var asset = new DownloadAsset("client.zip", "https://example.test/client.zip", 10, null, "2.0.0",
- AppType: (int)AppType.Client);
+ var packageFixture = Path.Combine(_root, "client-package.zip");
+ using (var archive = ZipFile.Open(packageFixture, ZipArchiveMode.Create))
+ using (var writer = new StreamWriter(archive.CreateEntry("updated.txt").Open()))
+ writer.Write("child-applied");
+ byte[] packageHash;
+ using (var sha = System.Security.Cryptography.SHA256.Create())
+ packageHash = sha.ComputeHash(File.ReadAllBytes(packageFixture));
+ var asset = new DownloadAsset("client", "https://example.test/client.zip",
+ new FileInfo(packageFixture).Length, Convert.ToHexString(packageHash), "2.0.0",
+ AppType: (int)AppType.Client, PackageType: (int)PackageType.Full);
+ var chain = new DownloadAsset("chain", "https://example.test/chain.zip",
+ asset.Size, null, "2.0.0", AppType: (int)AppType.Client, PackageType: (int)PackageType.Chain);
var source = new Mock();
source.Setup(s => s.ListAsync(It.IsAny()))
- .ReturnsAsync(new DownloadSourceResult { Assets = new[] { asset }, HasMainUpdate = true });
+ .ReturnsAsync(new DownloadSourceResult { Assets = new[] { chain, asset }, HasMainUpdate = true });
var executor = new Mock();
executor.Setup(e => e.ExecuteAsync(It.IsAny(), It.IsAny(),
It.IsAny>(), It.IsAny()))
.Returns((DownloadAsset download, string path, IProgress? _, CancellationToken _) =>
- Task.FromResult(new DownloadResult(download, path, 10, TimeSpan.Zero, 0, true, null)));
+ {
+ File.Copy(packageFixture, path, overwrite: true);
+ return Task.FromResult(new DownloadResult(download, path,
+ new FileInfo(path).Length, TimeSpan.Zero, 0, true, null));
+ });
var reports = new List();
var reporter = new Mock();
reporter.Setup(r => r.ReportAsync(It.IsAny(), It.IsAny()))
@@ -149,7 +208,8 @@ public async Task Client_strategy_creates_and_binds_the_backup_used_by_its_updat
DownloadSource = source.Object,
LaunchAfterPrepare = false,
Reporter = reporter.Object,
- ProcessContractProvider = new EncryptedFileProcessContractProvider(Path.Combine(_root, "client-ipc"))
+ ProcessContractProvider = new EncryptedFileProcessContractProvider(
+ Path.Combine(_root, "GeneralUpdate", "ipc"))
};
strategy.SetDownloadExecutor(executor.Object);
strategy.Create(new UpdateContext
@@ -166,13 +226,28 @@ public async Task Client_strategy_creates_and_binds_the_backup_used_by_its_updat
try
{
await strategy.ExecuteAsync();
- Assert.True(strategy.HasPreparedClientUpdate);
+ Assert.True(strategy.HasPreparedClientUpdate,
+ $"Client update was not prepared. Reports: {string.Join(",", reports.Select(report => report.Status))}");
var attempt = new DurableUpdateAttemptStore(installPath).GetAttempt(attemptId);
Assert.Equal(DurableUpdateAttemptStatus.SnapshotBound, attempt.Status);
Assert.NotNull(attempt.SnapshotPath);
Assert.Contains(attemptId.ToString("N"), Path.GetFileName(attempt.SnapshotPath));
+ Assert.NotNull(attempt.SnapshotManifestHash);
Assert.Equal("before-update", File.ReadAllText(Path.Combine(attempt.SnapshotPath, "app-state.txt")));
Assert.DoesNotContain(reports, report => report.Status == (int)UpdateStatus.Success);
+
+ var childStart = CreateProbeStart("attempt-apply");
+ ConfigureProbeTemp(childStart, _root);
+ childStart.EnvironmentVariables[DurableUpdateAttemptStore.RequiredAttemptIdEnvironmentVariable] =
+ attemptId.ToString("D");
+ using var child = Process.Start(childStart) ?? throw new InvalidOperationException("Failed to start update child.");
+ var appliedOutput = Finish(child).Split('|');
+ Assert.Equal(attemptId.ToString("D"), appliedOutput[0]);
+ Assert.DoesNotContain((int)UpdateStatus.Success, appliedOutput[1]
+ .Split(',', StringSplitOptions.RemoveEmptyEntries).Select(int.Parse));
+ var appliedFile = Path.Combine(installPath, "updated.txt");
+ Assert.True(File.Exists(appliedFile), $"Child output: {string.Join("|", appliedOutput)}");
+ Assert.Equal("child-applied", File.ReadAllText(appliedFile));
}
finally
{
@@ -364,6 +439,36 @@ public void Child_process_requires_the_matching_attempt_contract_and_rejects_mis
File.WriteAllBytes(ipcPath, new byte[] { 1, 2, 3, 4 });
Assert.Equal("rejected", RunRequiredAttemptProbe(tempRoot, attemptId));
+ provider.Send(contract);
+ var snapshotPath = store.GetAttempt(attemptId).SnapshotPath!;
+ var snapshotFile = Path.Combine(snapshotPath, "file.txt");
+ File.WriteAllText(snapshotFile, "SNAPSHOT");
+ Assert.Equal("rejected", RunRequiredAttemptProbe(tempRoot, attemptId));
+ File.WriteAllText(snapshotFile, "snapshot");
+ File.Delete(snapshotFile);
+ provider.Send(contract);
+ Assert.Equal("rejected", RunRequiredAttemptProbe(tempRoot, attemptId));
+ File.WriteAllText(snapshotFile, "snapshot");
+ File.WriteAllText(Path.Combine(snapshotPath, "unexpected.txt"), "extra");
+ provider.Send(contract);
+ Assert.Equal("rejected", RunRequiredAttemptProbe(tempRoot, attemptId));
+ File.Delete(Path.Combine(snapshotPath, "unexpected.txt"));
+
+ var manifestPath = DurableUpdateAttemptStore.GetSnapshotManifestPath(installPath, attemptId);
+ var manifest = File.ReadAllBytes(manifestPath);
+ File.WriteAllBytes(manifestPath, new byte[] { 0, 1, 2, 3 });
+ provider.Send(contract);
+ Assert.Equal("rejected", RunRequiredAttemptProbe(tempRoot, attemptId));
+ File.WriteAllBytes(manifestPath, manifest);
+
+ contract.SnapshotManifestHash = new string('0', 64);
+ provider.Send(contract);
+ Assert.Equal("rejected", RunRequiredAttemptProbe(tempRoot, attemptId));
+ contract.SnapshotManifestHash = null;
+ provider.Send(contract);
+ Assert.Equal("rejected", RunRequiredAttemptProbe(tempRoot, attemptId));
+ contract.SnapshotManifestHash = store.GetAttempt(attemptId).SnapshotManifestHash;
+
contract.DurableUpdateAttemptId = Guid.NewGuid();
provider.Send(contract);
Assert.Equal("rejected", RunRequiredAttemptProbe(tempRoot, attemptId));
@@ -457,9 +562,44 @@ public void Missing_or_corrupt_snapshot_state_fails_closed_without_latest_backup
Assert.Throws(() => StorageManager.CleanBackup(installPath, keepVersions: 0));
}
+ [Fact]
+ public void Legacy_v1_bound_snapshot_is_still_pinned_but_cannot_be_promoted_or_verified()
+ {
+ var installPath = Path.Combine(_root, "legacy-install");
+ var snapshotPath = Path.Combine(installPath, StorageManager.BackupRootDirectory, "backup-legacy-attempt");
+ var tempRoot = Path.Combine(_root, "legacy-ipc");
+ Directory.CreateDirectory(snapshotPath);
+ Directory.CreateDirectory(tempRoot);
+ File.WriteAllText(Path.Combine(snapshotPath, "file.txt"), "legacy");
+ using (var archive = ZipFile.Open(Path.Combine(_root, "package.zip"), ZipArchiveMode.Create))
+ using (var writer = new StreamWriter(archive.CreateEntry("updated.txt").Open()))
+ writer.Write("must-not-apply");
+ var attemptId = Guid.NewGuid();
+ WriteLegacyBoundAttempt(installPath, attemptId, snapshotPath);
+ var store = new DurableUpdateAttemptStore(installPath);
+
+ var record = store.GetAttempt(attemptId);
+ Assert.Equal(DurableUpdateAttemptStatus.SnapshotBound, record.Status);
+ Assert.Null(record.SnapshotManifestHash);
+ Assert.Throws(() =>
+ store.VerifySnapshotContent(attemptId, snapshotPath, new string('A', 64)));
+ Assert.Throws(() => store.ClaimRecovery(attemptId, 0));
+ var contract = CreateAttemptContract(installPath, attemptId, snapshotPath);
+ contract.SnapshotManifestHash = new string('A', 64);
+ var provider = new EncryptedFileProcessContractProvider(Path.Combine(tempRoot, "GeneralUpdate", "ipc"));
+ provider.Send(contract);
+ Assert.Equal("rejected", RunRequiredAttemptProbe(tempRoot, attemptId));
+ Assert.False(File.Exists(Path.Combine(installPath, "updated.txt")));
+
+ StorageManager.CleanBackup(installPath, keepVersions: 0);
+
+ Assert.True(Directory.Exists(snapshotPath));
+ Assert.Null(store.GetAttempt(attemptId).SnapshotManifestHash);
+ }
+
private ProcessContract CreateAttemptContract(string installPath, Guid attemptId, string snapshotPath, string bowl = "")
{
- return ConfigurationMapper.MapToProcessContract(new UpdateContext
+ var contract = ConfigurationMapper.MapToProcessContract(new UpdateContext
{
MainAppName = "App.exe",
InstallPath = installPath,
@@ -486,6 +626,9 @@ private ProcessContract CreateAttemptContract(string installPath, Guid attemptId
}
},
BlackDefaults.DefaultFormats, BlackDefaults.DefaultFiles, BlackDefaults.DefaultDirectories);
+ contract.SnapshotManifestHash = new DurableUpdateAttemptStore(installPath).GetAttempt(attemptId)
+ .SnapshotManifestHash;
+ return contract;
}
private static string RunRequiredAttemptProbe(string tempRoot, Guid attemptId)
@@ -511,11 +654,67 @@ private DurableUpdateAttemptStore CreateBoundAttempt(string installPath, string
var store = new DurableUpdateAttemptStore(installPath);
store.Begin(attemptId);
store.ReserveSnapshot(attemptId, snapshotPath);
- StorageManager.Backup(sourcePath, snapshotPath, Array.Empty(), createOnly: true);
+ StorageManager.Backup(sourcePath, snapshotPath, Array.Empty(), createOnly: true,
+ rejectReparsePoints: true);
store.BindSnapshot(attemptId, snapshotPath);
return store;
}
+ private static void WriteLegacyBoundAttempt(string installPath, Guid attemptId, string snapshotPath)
+ {
+ var journalDirectory = DurableUpdateAttemptStore.GetDirectory(installPath);
+ Directory.CreateDirectory(journalDirectory);
+ byte[] payload;
+ using (var memory = new MemoryStream())
+ {
+ using (var writer = new BinaryWriter(memory, Encoding.UTF8, true))
+ {
+ writer.Write(1);
+ writer.Write(attemptId.ToByteArray());
+ writer.Write((int)DurableUpdateAttemptStatus.SnapshotBound);
+ writer.Write(0L);
+ writer.Write(false);
+ writer.Write(true);
+ writer.Write(snapshotPath);
+ }
+ payload = memory.ToArray();
+ }
+
+ byte[] hash;
+ using (var sha = System.Security.Cryptography.SHA256.Create())
+ hash = sha.ComputeHash(payload);
+ var bytes = new byte[payload.Length + hash.Length];
+ Buffer.BlockCopy(payload, 0, bytes, 0, payload.Length);
+ Buffer.BlockCopy(hash, 0, bytes, payload.Length, hash.Length);
+ File.WriteAllBytes(Path.Combine(journalDirectory, attemptId.ToString("N") + ".state"), bytes);
+ }
+
+ private static void CreateDirectoryLink(string link, string target)
+ {
+ if (!OperatingSystem.IsWindows())
+ {
+ Directory.CreateSymbolicLink(link, target);
+ return;
+ }
+
+ var start = new ProcessStartInfo(Environment.GetEnvironmentVariable("ComSpec") ?? "cmd.exe")
+ {
+ UseShellExecute = false,
+ RedirectStandardError = true,
+ RedirectStandardOutput = true
+ };
+ start.ArgumentList.Add("/c");
+ start.ArgumentList.Add("mklink");
+ start.ArgumentList.Add("/J");
+ start.ArgumentList.Add(link);
+ start.ArgumentList.Add(target);
+ using var process = Process.Start(start) ?? throw new InvalidOperationException("Failed to create junction.");
+ var stdout = process.StandardOutput.ReadToEnd();
+ var stderr = process.StandardError.ReadToEnd();
+ process.WaitForExit();
+ Assert.True(process.ExitCode == 0, $"Failed to create junction: {stdout} {stderr}");
+ }
+
private static Process StartProbe(params string[] args)
{
var start = CreateProbeStart(args);
@@ -547,11 +746,20 @@ private static string RunProbe(params string[] args)
private static string Finish(Process process)
{
- Assert.True(process.WaitForExit(15000), "The durable-attempt probe did not exit.");
- var stderr = process.StandardError.ReadToEnd();
+ var standardOutput = process.StandardOutput.ReadToEndAsync();
+ var standardError = process.StandardError.ReadToEndAsync();
+ if (!process.WaitForExit(30000))
+ {
+ process.Kill();
+ process.WaitForExit();
+ throw new Xunit.Sdk.XunitException(
+ $"The durable-attempt probe did not exit. stdout: {standardOutput.GetAwaiter().GetResult()} " +
+ $"stderr: {standardError.GetAwaiter().GetResult()}");
+ }
+ var stderr = standardError.GetAwaiter().GetResult();
Assert.Equal(0, process.ExitCode);
Assert.Empty(stderr);
- return process.StandardOutput.ReadToEnd()
+ return standardOutput.GetAwaiter().GetResult()
.Split(new[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries)
.LastOrDefault()?.Trim() ?? string.Empty;
}
diff --git a/tests/StartupHealthProbe/Program.cs b/tests/StartupHealthProbe/Program.cs
index a8741e92..9dd29f8d 100644
--- a/tests/StartupHealthProbe/Program.cs
+++ b/tests/StartupHealthProbe/Program.cs
@@ -49,7 +49,38 @@
if (args.Length == 3 && args[0] == "attempt-read")
{
var record = new DurableUpdateAttemptStore(args[1]).GetAttempt(Guid.Parse(args[2]));
- Console.WriteLine($"{record.Status}|{record.SnapshotPath}|{record.Fence}");
+ Console.WriteLine($"{record.Status}|{record.SnapshotPath}|{record.Fence}|{record.SnapshotManifestHash}");
+ return;
+}
+
+if (args.Length == 5 && args[0] == "snapshot-create")
+{
+ var installPath = args[1];
+ var attemptId = Guid.Parse(args[2]);
+ var sourcePath = args[3];
+ var snapshotPath = args[4];
+ var store = new DurableUpdateAttemptStore(installPath);
+ store.Begin(attemptId);
+ store.ReserveSnapshot(attemptId, snapshotPath);
+ StorageManager.Backup(sourcePath, snapshotPath, Array.Empty(), createOnly: true,
+ rejectReparsePoints: true);
+ store.BindSnapshot(attemptId, snapshotPath);
+ Console.WriteLine(store.GetAttempt(attemptId).SnapshotManifestHash);
+ return;
+}
+
+if (args.Length == 5 && args[0] == "snapshot-verify")
+{
+ try
+ {
+ new DurableUpdateAttemptStore(args[1])
+ .VerifySnapshotContent(Guid.Parse(args[2]), args[3], args[4]);
+ Console.WriteLine("verified");
+ }
+ catch (InvalidDataException)
+ {
+ Console.WriteLine("rejected");
+ }
return;
}