diff --git a/.github/workflows/diagnostic-outbox.yml b/.github/workflows/diagnostic-outbox.yml new file mode 100644 index 00000000..beafb65d --- /dev/null +++ b/.github/workflows/diagnostic-outbox.yml @@ -0,0 +1,37 @@ +name: Diagnostic outbox + +on: + pull_request: + push: + branches: [master, main] + +jobs: + outbox: + strategy: + matrix: + include: + - os: windows-latest + rid: win-x64 + - os: ubuntu-latest + rid: linux-x64 + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v6 + - uses: actions/setup-dotnet@v5 + with: + dotnet-version: '10.0.x' + - name: Install Linux native dependencies + if: runner.os == 'Linux' + run: sudo apt-get update && sudo apt-get install -y clang zlib1g-dev + - name: Test cross-process outbox + run: dotnet test tests/CoreTest/CoreTest.csproj -c Release --filter FullyQualifiedName~Diagnostics + - name: Build integration harness + run: dotnet build tests/OutboxConsumerHarness/OutboxConsumerHarness.csproj -c Release + - name: Publish Native AOT smoke + run: dotnet publish tests/OutboxAotSmoke/OutboxAotSmoke.csproj -c Release -r ${{ matrix.rid }} -o outbox-aot + - name: Run Native AOT smoke (Windows) + if: runner.os == 'Windows' + run: ./outbox-aot/OutboxAotSmoke.exe + - name: Run Native AOT smoke (Linux) + if: runner.os == 'Linux' + run: ./outbox-aot/OutboxAotSmoke diff --git a/docs/diagnostic-artifact-transport.md b/docs/diagnostic-artifact-transport.md index 2119abb7..b3f51627 100644 --- a/docs/diagnostic-artifact-transport.md +++ b/docs/diagnostic-artifact-transport.md @@ -1,13 +1,9 @@ # Diagnostic artifact transport `ArtifactUploadClient` is an opt-in transport for an already prepared Bowl schema 2 -crash ZIP. It does **not** scan an outbox, create snapshots, schedule retries, or -delete evidence. It is not integrated into `LaunchAsync`. In particular, do not -read a live outbox using this API: Bowl's original writer, crash hook and GC do -not coordinate with readers. Integration requires the Bowl `outboxProtocol: 1` -shared-lock contract and a separately implemented durable snapshot/consumer. -Unmarked legacy cases must be skipped unless all legacy participants have been -stopped and an explicit migration is performed. +crash ZIP. `DiagnosticOutboxConsumer` separately implements the cooperative Bowl +`outboxProtocol: 1` case lifecycle. Neither component is integrated into +`LaunchAsync`; the host explicitly schedules and retries cases. The host must provide a stable ZIP snapshot, `manifest.json` at its root, and matching metadata. Retain the **same ZIP bytes** for retries, including after a @@ -48,6 +44,78 @@ cancellation propagates. The response is accepted only for HTTP success, and `parsed` flags. A returned `contentSha256` must match the sent bytes. `HashVerified` is false when the server omits it; older servers cannot prove a duplicate contains the same content. `Parsed=false` means the server stored but -did not interpret the artifact. None of these results by itself authorizes -deleting source evidence: safe cleanup also requires the coordinated Bowl -lifecycle and a server that verifies and returns the stored content hash. +did not interpret the artifact. + +## Cooperative outbox consumer + +Only enable this after installing a Bowl writer and GC that both implement +protocol 1. Configure `{install}/fail` as the root, and have the host enumerate +version and D-format GUID directories and call `ProcessCaseAsync` for each one. +Do not pass `.locks` or the consumer's `.generalupdate-uploaded-*` directories +as cases. The host should report exceptions, retry transient failures with +backoff, and separately manage scheduling, retention and consent. + +```csharp +var consumer = new DiagnosticOutboxConsumer( + failDirectory, upload, TimeSpan.FromSeconds(30)); +bool deleted = await consumer.ProcessCaseAsync(version, caseGuid, cancellationToken); +``` + +`false` means busy, incomplete, unmarked, or not confirmed by a server hash; +errors and cancellation propagate. Invalid cases are preserved for investigation. +The consumer validates the manifest and its top-level evidence list, rejects +links and unexpected entries, and bounds the manifest, file count and ZIP size. +It persists a ZIP and SHA-256 inside the case before sending and reuses the same +bytes across retries and restarts. A corrupt or incomplete persisted snapshot +stops automatic processing: preserve the case and investigate; do not delete the +snapshot and retry the same GUID. A hash-confirmed case is first atomically +renamed to `.generalupdate-uploaded-{guid}` before deletion, so interruption +during deletion cannot trigger a regenerated upload. The host must also enumerate +`.generalupdate-uploaded-{guid}` tombstones and call +`CleanupConfirmedCase(version, guid)` to finish an interrupted deletion under +the same stripe lock. Tombstones count against Bowl's admission limits until +removed; a cleanup failure can therefore cause exit-code-only degradation. + +The lock is `{fail}/.locks/{first two lowercase GUID hex characters}.lock`, +opened with `FileShare.None` and never deleted. It remains held through snapshot, +upload and cleanup. The required upload timeout is at most two minutes; the HTTP +handler must honor cancellation. Even with a timeout, a slow upload can prevent +Bowl from acquiring the same stripe. Bowl tries another GUID; exhausted +admission or lock retries can degrade monitoring to exit-code-only, losing +crash evidence. Choose a short timeout appropriate for the deployment and +monitor this failure. + +This contract requires a local filesystem, compatible .NET processes running +with matching permissions, and a private outbox protected by OS permissions. +It does not protect against a malicious local process that can change the +outbox or replace paths while it is being read. It does not provide power-loss +durability guarantees beyond the filesystem's flush and rename guarantees. +Evidence and retained ZIPs may contain secrets; apply host access controls, +redaction and a retention policy. Never remove lock files while any participant +may be running. Do not allow hooks to leave background writers. + +Legacy schema 2 cases without `outboxProtocol` are skipped by default. Set +`allowLegacyAfterQuiescence` only after **all** old watchdogs, uploaders and +collectors are stopped; this is an operational prerequisite, not something the +consumer can verify. GeneralSpace must provide hash-confirmed acknowledgments +before cleanup; older servers without `contentSha256` retain every case. + +## Local integration harness + +`tests/OutboxConsumerHarness` invokes the real consumer once against a loopback +HTTPS service. Supply the server's PEM certificate to pin its exact bytes; +hostname validation remains enabled. It disables proxies and redirects. For +example, with a test certificate valid for `localhost`: + +```powershell +$env:OUTBOX_TEST_TENANT = 'test-tenant' +$env:OUTBOX_TEST_APP_KEY = 'test-app' +dotnet run --project tests\OutboxConsumerHarness -- ` + 'C:\fixture\fail' '1.0.2' '' ` + 'https://localhost:5001/Fault/UploadArtifact' 'C:\fixture\server.pem' +``` + +Exit code 0 means hash-confirmed deletion, 2 means skipped or not confirmed, +and 1 means an error. This test harness does not schedule retries: invoke it +again to exercise persisted snapshots. Never use its certificate pinning to +disable certificate validation in production. diff --git a/src/GeneralUpdate.Core/Diagnostics/DiagnosticOutboxConsumer.cs b/src/GeneralUpdate.Core/Diagnostics/DiagnosticOutboxConsumer.cs new file mode 100644 index 00000000..aec513eb --- /dev/null +++ b/src/GeneralUpdate.Core/Diagnostics/DiagnosticOutboxConsumer.cs @@ -0,0 +1,303 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.IO.Compression; +using System.Linq; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; + +namespace GeneralUpdate.Core.Diagnostics; + +/// Explicit, cooperative consumer for a Bowl diagnostic outbox. +/// The host must protect the outbox against untrusted local writers. +public sealed class DiagnosticOutboxConsumer +{ + private const int MaxManifestBytes = 64 * 1024; + private const int MaxFiles = 128; + private const int MaxZipBytes = 19 * 1024 * 1024; + private const string ZipName = ".generalupdate-outbox.zip"; + private const string HashName = ".generalupdate-outbox.sha256"; + private const string TempZipName = ".generalupdate-outbox.zip.tmp"; + private const string TempHashName = ".generalupdate-outbox.sha256.tmp"; + private readonly string _root; + private readonly ArtifactUploadClient _client; + private readonly TimeSpan _uploadTimeout; + private readonly bool _allowLegacy; + + /// + /// Creates a consumer. Legacy cases may be enabled only after all legacy writers, + /// uploaders and collectors have been stopped. + /// + public DiagnosticOutboxConsumer(string failDirectory, ArtifactUploadClient client, + TimeSpan uploadTimeout, bool allowLegacyAfterQuiescence = false) + { + if (string.IsNullOrWhiteSpace(failDirectory)) throw new ArgumentException("An outbox directory is required.", nameof(failDirectory)); + if (uploadTimeout <= TimeSpan.Zero || uploadTimeout > TimeSpan.FromMinutes(2)) + throw new ArgumentOutOfRangeException(nameof(uploadTimeout)); + _root = Path.GetFullPath(failDirectory); + _client = client ?? throw new ArgumentNullException(nameof(client)); + _uploadTimeout = uploadTimeout; + _allowLegacy = allowLegacyAfterQuiescence; + } + + /// + /// Attempts one case. Returns false when it is busy, incomplete, unmarked, or + /// the server cannot confirm its hash. Invalid data and I/O errors are surfaced. + /// + public async Task ProcessCaseAsync(string version, string caseGuid, CancellationToken cancellationToken = default) + { + RequireSegment(version, nameof(version)); + if (version.Equals(".locks", StringComparison.OrdinalIgnoreCase) || version.Length > 256) + throw new ArgumentException("Invalid outbox version.", nameof(version)); + if (!Guid.TryParseExact(caseGuid, "D", out var guid)) + throw new ArgumentException("A D-format case GUID is required.", nameof(caseGuid)); + cancellationToken.ThrowIfCancellationRequested(); + CheckDirectoryChain(_root); + var stripeLock = TryAcquireLock(guid); + if (stripeLock == null) return false; + using (stripeLock) + { + var versionPath = Path.Combine(_root, version); + var casePath = Path.Combine(versionPath, caseGuid); + if (!Directory.Exists(casePath)) return false; + CheckDirectoryChain(casePath); + var manifestPath = Path.Combine(casePath, "manifest.json"); + if (!File.Exists(manifestPath)) return false; + var manifest = ReadBounded(manifestPath, MaxManifestBytes); + var metadata = ParseManifest(manifest, version, guid, out var files, out var marked); + if (!marked && !_allowLegacy) return false; + ValidateCaseEntries(casePath, files); + var zipPath = Path.Combine(casePath, ZipName); + var hashPath = Path.Combine(casePath, HashName); + RejectLinkIfExists(zipPath); + RejectLinkIfExists(hashPath); + var hasZip = File.Exists(zipPath); + var hasHash = File.Exists(hashPath); + if (hasZip != hasHash) throw new InvalidDataException("Incomplete persisted snapshot; manual recovery is required."); + if (!hasZip) + CreateSnapshot(casePath, manifest, files, cancellationToken); + var expectedHash = Encoding.ASCII.GetString(ReadBounded(hashPath, 64)); + var zip = ReadBounded(zipPath, MaxZipBytes); + if (expectedHash.Length != 64 || !string.Equals(expectedHash, Hash(zip), StringComparison.Ordinal)) + throw new InvalidDataException("Persisted snapshot failed integrity verification."); + using (var archive = new ZipArchive(new MemoryStream(zip, false), ZipArchiveMode.Read)) + { + var entry = archive.GetEntry("manifest.json") ?? throw new InvalidDataException("Snapshot has no manifest."); + using var input = entry.Open(); + using var bytes = new MemoryStream(); + CopyBounded(input, bytes, MaxManifestBytes, cancellationToken); + if (!bytes.ToArray().SequenceEqual(manifest)) + throw new InvalidDataException("The case manifest changed after snapshot creation."); + } + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + timeout.CancelAfter(_uploadTimeout); + var result = await _client.UploadAsync(metadata, zip, timeout.Token).ConfigureAwait(false); + if (!result.HashVerified) return false; + cancellationToken.ThrowIfCancellationRequested(); + CheckDirectoryChain(casePath); + ValidateCaseEntries(casePath, files); + var tombstone = Path.Combine(versionPath, ".generalupdate-uploaded-" + guid.ToString("D")); + Directory.Move(casePath, tombstone); + Directory.Delete(tombstone, true); + return true; + } + } + + /// Removes a previously hash-confirmed tombstone under its original stripe lock. + public bool CleanupConfirmedCase(string version, string caseGuid) + { + RequireSegment(version, nameof(version)); + if (version.Equals(".locks", StringComparison.OrdinalIgnoreCase) || version.Length > 256) + throw new ArgumentException("Invalid outbox version.", nameof(version)); + if (!Guid.TryParseExact(caseGuid, "D", out var guid)) + throw new ArgumentException("A D-format case GUID is required.", nameof(caseGuid)); + CheckDirectoryChain(_root); + using var stripeLock = TryAcquireLock(guid); + if (stripeLock == null) return false; + var path = Path.Combine(_root, version, ".generalupdate-uploaded-" + guid.ToString("D")); + if (!Directory.Exists(path)) return false; + CheckDirectoryChain(path); + Directory.Delete(path, true); + return true; + } + + private FileStream? TryAcquireLock(Guid guid) + { + var locks = Path.Combine(_root, ".locks"); + Directory.CreateDirectory(locks); + CheckDirectoryChain(locks); + var lockPath = Path.Combine(locks, guid.ToString("D").Substring(0, 2) + ".lock"); + RejectLinkIfExists(lockPath); + try { return new FileStream(lockPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None); } + catch (IOException ex) when (IsLockContention(ex)) { return null; } + } + + private static ArtifactUploadMetadata ParseManifest(byte[] bytes, string version, Guid guid, + out List files, out bool marked) + { + using var document = JsonDocument.Parse(bytes); + var root = document.RootElement; + if (root.ValueKind == JsonValueKind.Object) + { + var properties = new HashSet(StringComparer.Ordinal); + foreach (var property in root.EnumerateObject()) + if (!properties.Add(property.Name)) throw new InvalidDataException("Duplicate manifest property."); + } + if (root.ValueKind != JsonValueKind.Object || + !root.TryGetProperty("schema", out var schema) || !schema.TryGetInt32(out var schemaValue) || schemaValue != 2 || + !root.TryGetProperty("guid", out var id) || id.ValueKind != JsonValueKind.String || + !Guid.TryParseExact(id.GetString(), "D", out var parsed) || parsed != guid || + !root.TryGetProperty("kind", out var kind) || kind.ValueKind != JsonValueKind.String || kind.GetString() != "crash" || + !root.TryGetProperty("version", out var v) || v.ValueKind != JsonValueKind.String || v.GetString() != version || + !root.TryGetProperty("targetName", out var target) || target.ValueKind != JsonValueKind.String || + string.IsNullOrWhiteSpace(target.GetString()) || target.GetString()!.Length > 256 || + !root.TryGetProperty("state", out var state) || state.ValueKind != JsonValueKind.String || state.GetString() != "pending" || + !root.TryGetProperty("files", out var list) || list.ValueKind != JsonValueKind.Array) + throw new InvalidDataException("Invalid Bowl manifest."); + marked = false; + if (root.TryGetProperty("outboxProtocol", out var protocol)) + { + if (protocol.ValueKind != JsonValueKind.Number || !protocol.TryGetInt32(out var protocolValue) || protocolValue != 1) + throw new InvalidDataException("Unsupported outbox protocol."); + marked = true; + } + files = new List(); + var names = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (var item in list.EnumerateArray()) + { + if (item.ValueKind != JsonValueKind.String) throw new InvalidDataException("Invalid evidence filename."); + var name = item.GetString()!; + RequireSegment(name, "filename"); + if (name.Length > 255 || name.Equals("manifest.json", StringComparison.OrdinalIgnoreCase) || + name.Equals("manifest.json.tmp", StringComparison.OrdinalIgnoreCase) || + name.StartsWith(".generalupdate-outbox.", StringComparison.OrdinalIgnoreCase) || + !names.Add(name) || files.Count >= MaxFiles) + throw new InvalidDataException("Invalid or duplicate evidence filename."); + files.Add(name); + } + return new ArtifactUploadMetadata { Guid = guid.ToString("D"), Kind = "crash", Schema = 2, Version = version, TargetName = target.GetString()! }; + } + + private static void CreateSnapshot(string casePath, byte[] manifest, List files, CancellationToken token) + { + var tempZip = Path.Combine(casePath, TempZipName); + var tempHash = Path.Combine(casePath, TempHashName); + RejectLinkIfExists(tempZip); + RejectLinkIfExists(tempHash); + if (File.Exists(tempZip)) File.Delete(tempZip); + if (File.Exists(tempHash)) File.Delete(tempHash); + long total = manifest.Length; + using (var output = new FileStream(tempZip, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None)) + { + using (var archive = new ZipArchive(output, ZipArchiveMode.Create, true)) + { + var manifestEntry = archive.CreateEntry("manifest.json", CompressionLevel.NoCompression); + using (var stream = manifestEntry.Open()) stream.Write(manifest, 0, manifest.Length); + foreach (var name in files.OrderBy(x => x, StringComparer.Ordinal)) + { + token.ThrowIfCancellationRequested(); + var path = Path.Combine(casePath, name); + RejectLinkIfExists(path); + using var input = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read); + if (input.Length > MaxZipBytes - total) throw new InvalidDataException("Evidence exceeds the size limit."); + var entry = archive.CreateEntry(name, CompressionLevel.NoCompression); + using var stream = entry.Open(); + total += CopyBounded(input, stream, MaxZipBytes - total, token); + } + } + if (output.Length > MaxZipBytes) throw new InvalidDataException("Snapshot exceeds the size limit."); + output.Flush(true); + } + var hash = Encoding.ASCII.GetBytes(Hash(ReadBounded(tempZip, MaxZipBytes))); + using (var output = new FileStream(tempHash, FileMode.CreateNew, FileAccess.Write, FileShare.None)) + { + output.Write(hash, 0, hash.Length); + output.Flush(true); + } + File.Move(tempHash, Path.Combine(casePath, HashName)); + File.Move(tempZip, Path.Combine(casePath, ZipName)); + } + + private static byte[] ReadBounded(string path, int limit) + { + RejectLinkIfExists(path); + using var input = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read); + using var output = new MemoryStream(); + CopyBounded(input, output, limit, CancellationToken.None); + return output.ToArray(); + } + + private static long CopyBounded(Stream input, Stream output, long limit, CancellationToken token) + { + var buffer = new byte[81920]; + long total = 0; + int read; + while ((read = input.Read(buffer, 0, buffer.Length)) != 0) + { + token.ThrowIfCancellationRequested(); + total += read; + if (total > limit) throw new InvalidDataException("File exceeds the size limit."); + output.Write(buffer, 0, read); + } + return total; + } + + private static string Hash(byte[] bytes) + { + using var sha = SHA256.Create(); + return BitConverter.ToString(sha.ComputeHash(bytes)).Replace("-", "").ToLowerInvariant(); + } + + private static bool IsLockContention(IOException error) + { + var code = error.HResult & 0xffff; + return code == 32 || code == 33 || code == 11; + } + + private static void RequireSegment(string? value, string parameter) + { + if (string.IsNullOrWhiteSpace(value) || value == "." || value == ".." || + value!.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0 || + value.IndexOfAny(new[] { '/', '\\', ':' }) >= 0 || Path.IsPathRooted(value) || + value.EndsWith(".", StringComparison.Ordinal) || value.EndsWith(" ", StringComparison.Ordinal)) + throw new ArgumentException("A single safe path segment is required.", parameter); + } + + private static void ValidateCaseEntries(string casePath, List files) + { + var allowed = new HashSet(files, StringComparer.OrdinalIgnoreCase) + { + "manifest.json", ZipName, HashName, TempZipName, TempHashName + }; + var seen = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (var path in Directory.EnumerateFileSystemEntries(casePath)) + { + var name = Path.GetFileName(path); + if (!allowed.Contains(name) || !seen.Add(name) || + (File.GetAttributes(path) & (FileAttributes.Directory | FileAttributes.ReparsePoint)) != 0) + throw new InvalidDataException("Unexpected or unsafe entry in diagnostic case."); + } + foreach (var name in files) + if (!seen.Contains(name)) throw new InvalidDataException("A manifest evidence file is missing."); + } + + private static void RejectLinkIfExists(string path) + { + if ((File.Exists(path) || Directory.Exists(path)) && (File.GetAttributes(path) & FileAttributes.ReparsePoint) != 0) + throw new InvalidDataException("Outbox links and reparse points are not allowed."); + } + + private static void CheckDirectoryChain(string path) + { + var current = new DirectoryInfo(path); + while (current != null) + { + if (!current.Exists || (current.Attributes & FileAttributes.ReparsePoint) != 0) + throw new InvalidDataException("Outbox directory is missing or is a link."); + current = current.Parent; + } + } +} diff --git a/tests/CoreTest/CoreTest.csproj b/tests/CoreTest/CoreTest.csproj index 99d514db..40bde2fc 100644 --- a/tests/CoreTest/CoreTest.csproj +++ b/tests/CoreTest/CoreTest.csproj @@ -21,6 +21,7 @@ + \ No newline at end of file diff --git a/tests/CoreTest/Diagnostics/DiagnosticOutboxConsumerTests.cs b/tests/CoreTest/Diagnostics/DiagnosticOutboxConsumerTests.cs new file mode 100644 index 00000000..88446f7d --- /dev/null +++ b/tests/CoreTest/Diagnostics/DiagnosticOutboxConsumerTests.cs @@ -0,0 +1,226 @@ +using System.Diagnostics; +using System.Net; +using System.Security.Cryptography; +using System.Text; +using GeneralUpdate.Core.Diagnostics; + +namespace CoreTest.Diagnostics; + +public sealed class DiagnosticOutboxConsumerTests : IDisposable +{ + private const string Id = "86c1ae61-89e9-450d-93b0-a7f512c06768"; + private readonly string _root = Path.Combine(Path.GetTempPath(), "gu-outbox-" + Guid.NewGuid().ToString("N")); + private string CasePath => Path.Combine(_root, "1.0", Id); + + [Fact] + public async Task RetryAfterRestartRetainsIdenticalBytesUntilHashConfirmed() + { + CreateCase(); + var sent = new List(); + var count = 0; + using var http = new HttpClient(new Handler(async (request, _) => + { + var file = ((MultipartFormDataContent)request.Content!).Single(p => p.Headers.ContentDisposition!.Name == "file"); + var bytes = await file.ReadAsByteArrayAsync(); + sent.Add(bytes); + return ++count switch + { + 1 => new HttpResponseMessage(HttpStatusCode.ServiceUnavailable), + 2 => Response(null), + _ => Response(Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant()) + }; + })); + await Assert.ThrowsAsync(() => Consumer(http).ProcessCaseAsync("1.0", Id)); + Assert.True(Directory.Exists(CasePath)); + Assert.False(await Consumer(http).ProcessCaseAsync("1.0", Id)); + Assert.True(Directory.Exists(CasePath)); + Assert.True(await Consumer(http).ProcessCaseAsync("1.0", Id)); + Assert.False(Directory.Exists(CasePath)); + Assert.Equal(3, sent.Count); + Assert.Equal(sent[0], sent[1]); + Assert.Equal(sent[0], sent[2]); + } + + [Fact] + public async Task CorruptOrIncompleteSnapshotNeverRebuilds() + { + CreateCase(); + using var http = Http((_, _) => Task.FromResult(new HttpResponseMessage(HttpStatusCode.ServiceUnavailable))); + await Assert.ThrowsAsync(() => Consumer(http).ProcessCaseAsync("1.0", Id)); + File.WriteAllBytes(Path.Combine(CasePath, ".generalupdate-outbox.zip"), [1, 2]); + await Assert.ThrowsAsync(() => Consumer(http).ProcessCaseAsync("1.0", Id)); + File.Delete(Path.Combine(CasePath, ".generalupdate-outbox.zip")); + await Assert.ThrowsAsync(() => Consumer(http).ProcessCaseAsync("1.0", Id)); + Assert.True(Directory.Exists(CasePath)); + } + + [Fact] + public async Task UnmarkedCasesRequireExplicitMigration() + { + CreateCase(marked: false); + using var http = Http((_, _) => Task.FromResult(Response(null))); + Assert.False(await Consumer(http).ProcessCaseAsync("1.0", Id)); + Assert.False(File.Exists(Path.Combine(CasePath, ".generalupdate-outbox.zip"))); + Assert.False(await Consumer(http, legacy: true).ProcessCaseAsync("1.0", Id)); + Assert.True(File.Exists(Path.Combine(CasePath, ".generalupdate-outbox.zip"))); + } + + [Theory] + [InlineData("../secret")] + [InlineData("manifest.json")] + [InlineData(".generalupdate-outbox.zip")] + public async Task UnsafeEvidenceNamesAreRejected(string name) + { + CreateCase(evidenceName: name); + using var http = Http((_, _) => throw new Exception("Unexpected upload")); + if (name == "../secret") + await Assert.ThrowsAsync(() => Consumer(http).ProcessCaseAsync("1.0", Id)); + else + await Assert.ThrowsAsync(() => Consumer(http).ProcessCaseAsync("1.0", Id)); + Assert.True(Directory.Exists(CasePath)); + } + + [Fact] + public async Task UnexpectedEvidencePreventsUploadAndDeletion() + { + CreateCase(); + File.WriteAllText(Path.Combine(CasePath, "unexpected.txt"), "not in manifest"); + using var http = Http((_, _) => throw new Exception("Unexpected upload")); + await Assert.ThrowsAsync(() => Consumer(http).ProcessCaseAsync("1.0", Id)); + Assert.True(Directory.Exists(CasePath)); + } + + [Fact] + public async Task MissingEvidenceAndUnpublishedCasesAreNotUploaded() + { + CreateCase(); + using var http = Http((_, _) => throw new Exception("Unexpected upload")); + File.Delete(Path.Combine(CasePath, "log.txt")); + await Assert.ThrowsAsync(() => Consumer(http).ProcessCaseAsync("1.0", Id)); + File.Delete(Path.Combine(CasePath, "manifest.json")); + Assert.False(await Consumer(http).ProcessCaseAsync("1.0", Id)); + Assert.True(Directory.Exists(CasePath)); + } + + [Fact] + public async Task WrongServerHashKeepsEvidence() + { + CreateCase(); + using var http = Http((_, _) => Task.FromResult(Response(new string('0', 64)))); + await Assert.ThrowsAsync(() => Consumer(http).ProcessCaseAsync("1.0", Id)); + Assert.True(Directory.Exists(CasePath)); + Assert.True(File.Exists(Path.Combine(CasePath, ".generalupdate-outbox.zip"))); + } + + [Fact] + public async Task OversizedEvidenceIsRejected() + { + CreateCase(); + using (var file = File.OpenWrite(Path.Combine(CasePath, "log.txt"))) file.SetLength(19 * 1024 * 1024); + using var http = Http((_, _) => throw new Exception("Unexpected upload")); + await Assert.ThrowsAsync(() => Consumer(http).ProcessCaseAsync("1.0", Id)); + Assert.True(Directory.Exists(CasePath)); + } + + [Fact] + public async Task TimeoutKeepsSnapshotAndReleasesLock() + { + CreateCase(); + using var http = Http(async (_, token) => + { + await Task.Delay(Timeout.InfiniteTimeSpan, token); + throw new Exception("Unexpected completion"); + }); + await Assert.ThrowsAnyAsync(() => Consumer(http, timeout: TimeSpan.FromMilliseconds(100)).ProcessCaseAsync("1.0", Id)); + Assert.True(Directory.Exists(CasePath)); + using var stripe = new FileStream(Path.Combine(_root, ".locks", "86.lock"), FileMode.Open, FileAccess.ReadWrite, FileShare.None); + } + + [Fact] + public async Task AnotherProcessHoldingStripeMakesConsumerSkip() + { + CreateCase(); + Directory.CreateDirectory(Path.Combine(_root, ".locks")); + var path = Path.Combine(_root, ".locks", "86.lock"); + var start = new ProcessStartInfo + { + FileName = "dotnet", + RedirectStandardInput = true, + RedirectStandardOutput = true, + RedirectStandardError = true, + UseShellExecute = false, + CreateNoWindow = true + }; + start.ArgumentList.Add("exec"); + start.ArgumentList.Add("--runtimeconfig"); + start.ArgumentList.Add(Path.Combine(AppContext.BaseDirectory, "CoreTest.runtimeconfig.json")); + start.ArgumentList.Add(typeof(OutboxLockHelper.Program).Assembly.Location); + start.ArgumentList.Add(path); + using var process = Process.Start(start)!; + try + { + Assert.Equal("ready", await process.StandardOutput.ReadLineAsync().WaitAsync(TimeSpan.FromSeconds(15))); + using var blockedHttp = Http((_, _) => throw new Exception("Unexpected upload")); + Assert.False(await Consumer(blockedHttp).ProcessCaseAsync("1.0", Id)); + Assert.True(Directory.Exists(CasePath)); + } + finally + { + await process.StandardInput.WriteLineAsync(); + await process.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(15)); + } + Assert.Equal(0, process.ExitCode); + using var http = Http(async (request, _) => + { + var file = ((MultipartFormDataContent)request.Content!).Single(p => p.Headers.ContentDisposition!.Name == "file"); + var bytes = await file.ReadAsByteArrayAsync(); + return Response(Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant()); + }); + Assert.True(await Consumer(http).ProcessCaseAsync("1.0", Id)); + Assert.False(Directory.Exists(CasePath)); + } + + [Fact] + public void ConfirmedTombstoneCanBeCleanedWithoutTouchingPendingCase() + { + CreateCase(); + var tombstone = Path.Combine(_root, "1.0", ".generalupdate-uploaded-" + Id); + Directory.CreateDirectory(tombstone); + File.WriteAllText(Path.Combine(tombstone, "remaining.txt"), "already confirmed"); + using var http = Http((_, _) => throw new Exception("Unexpected upload")); + var consumer = Consumer(http); + Assert.True(consumer.CleanupConfirmedCase("1.0", Id)); + Assert.False(Directory.Exists(tombstone)); + Assert.True(Directory.Exists(CasePath)); + Assert.False(consumer.CleanupConfirmedCase("1.0", Id)); + } + + private void CreateCase(bool marked = true, string evidenceName = "log.txt") + { + Directory.CreateDirectory(CasePath); + if (evidenceName == "log.txt") File.WriteAllText(Path.Combine(CasePath, evidenceName), "diagnostic evidence"); + File.WriteAllText(Path.Combine(CasePath, "manifest.json"), + $"{{\"schema\":2,{(marked ? "\"outboxProtocol\":1," : "")}\"guid\":\"{Id}\",\"kind\":\"crash\",\"version\":\"1.0\",\"targetName\":\"TestApp\",\"state\":\"pending\",\"files\":[\"{evidenceName}\"]}}"); + } + + private DiagnosticOutboxConsumer Consumer(HttpClient http, bool legacy = false, TimeSpan? timeout = null) => + new(_root, new ArtifactUploadClient(http, new Uri("https://example.test/upload"), "tenant", "app"), + timeout ?? TimeSpan.FromSeconds(5), legacy); + + private static HttpClient Http(Func> send) => new(new Handler(send)); + + private static HttpResponseMessage Response(string? hash) => new(HttpStatusCode.OK) + { + Content = new StringContent($"{{\"code\":200,\"isSuccess\":true,\"body\":{{\"artifactId\":\"{Id}\",\"duplicate\":true,\"parsed\":true{(hash == null ? "" : $",\"contentSha256\":\"{hash}\"")}}}}}", Encoding.UTF8, "application/json") + }; + + public void Dispose() + { + if (Directory.Exists(_root)) Directory.Delete(_root, true); + } + + private sealed class Handler(Func> send) : HttpMessageHandler + { + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) => send(request, cancellationToken); + } +} diff --git a/tests/OutboxAotSmoke/OutboxAotSmoke.csproj b/tests/OutboxAotSmoke/OutboxAotSmoke.csproj new file mode 100644 index 00000000..9de20b7a --- /dev/null +++ b/tests/OutboxAotSmoke/OutboxAotSmoke.csproj @@ -0,0 +1,12 @@ + + + Exe + net10.0 + enable + enable + true + + + + + diff --git a/tests/OutboxAotSmoke/Program.cs b/tests/OutboxAotSmoke/Program.cs new file mode 100644 index 00000000..25644e10 --- /dev/null +++ b/tests/OutboxAotSmoke/Program.cs @@ -0,0 +1,50 @@ +using System.Net; +using System.Security.Cryptography; +using System.Text; +using GeneralUpdate.Core.Diagnostics; + +const string id = "86c1ae61-89e9-450d-93b0-a7f512c06768"; +var root = Path.Combine(Path.GetTempPath(), "gu-aot-" + Guid.NewGuid().ToString("N")); +var casePath = Path.Combine(root, "1.0", id); +Directory.CreateDirectory(casePath); +try +{ + File.WriteAllText(Path.Combine(casePath, "log.txt"), "evidence"); + File.WriteAllText(Path.Combine(casePath, "manifest.json"), + $"{{\"schema\":2,\"outboxProtocol\":1,\"guid\":\"{id}\",\"kind\":\"crash\",\"version\":\"1.0\",\"targetName\":\"TestApp\",\"state\":\"pending\",\"files\":[\"log.txt\"]}}"); + using var handler = new SmokeHandler(id); + using var http = new HttpClient(handler); + var client = new ArtifactUploadClient(http, new Uri("https://example.test/upload"), "tenant", "app"); + var consumer = new DiagnosticOutboxConsumer(root, client, TimeSpan.FromSeconds(5)); + if (await consumer.ProcessCaseAsync("1.0", id) || !Directory.Exists(casePath)) + throw new InvalidOperationException("Unconfirmed evidence was deleted."); + if (!await consumer.ProcessCaseAsync("1.0", id) || Directory.Exists(casePath) || handler.Attempts != 2) + throw new InvalidOperationException("Confirmed retry did not complete."); + Console.WriteLine("Outbox Native AOT smoke passed."); +} +finally +{ + if (Directory.Exists(root)) Directory.Delete(root, true); +} + +sealed class SmokeHandler(string id) : HttpMessageHandler +{ + private byte[]? _first; + public int Attempts { get; private set; } + + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken token) + { + var content = (MultipartFormDataContent)request.Content!; + var file = content.Single(x => x.Headers.ContentDisposition!.Name == "file"); + var bytes = await file.ReadAsByteArrayAsync(token); + Attempts++; + if (_first != null && !_first.SequenceEqual(bytes)) throw new InvalidOperationException("Retry bytes changed."); + _first = bytes; + var hash = Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant(); + var hashField = Attempts == 1 ? "" : $",\"contentSha256\":\"{hash}\""; + return new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new StringContent($"{{\"code\":200,\"isSuccess\":true,\"body\":{{\"artifactId\":\"{id}\",\"duplicate\":true,\"parsed\":true{hashField}}}}}", Encoding.UTF8, "application/json") + }; + } +} diff --git a/tests/OutboxConsumerHarness/OutboxConsumerHarness.csproj b/tests/OutboxConsumerHarness/OutboxConsumerHarness.csproj new file mode 100644 index 00000000..601478a7 --- /dev/null +++ b/tests/OutboxConsumerHarness/OutboxConsumerHarness.csproj @@ -0,0 +1,11 @@ + + + Exe + net10.0 + enable + enable + + + + + diff --git a/tests/OutboxConsumerHarness/Program.cs b/tests/OutboxConsumerHarness/Program.cs new file mode 100644 index 00000000..1e944f36 --- /dev/null +++ b/tests/OutboxConsumerHarness/Program.cs @@ -0,0 +1,53 @@ +using System.Net; +using System.Net.Security; +using System.Security.Cryptography.X509Certificates; +using GeneralUpdate.Core.Diagnostics; + +if (args.Length != 5) +{ + Console.Error.WriteLine("Usage: OutboxConsumerHarness "); + return 1; +} + +if (!Uri.TryCreate(args[3], UriKind.Absolute, out var endpoint) || + endpoint.Scheme != Uri.UriSchemeHttps || + !(string.Equals(endpoint.Host, "localhost", StringComparison.OrdinalIgnoreCase) || + IPAddress.TryParse(endpoint.Host, out var address) && IPAddress.IsLoopback(address))) +{ + Console.Error.WriteLine("The endpoint must be HTTPS on a loopback address or localhost."); + return 1; +} + +var tenant = Environment.GetEnvironmentVariable("OUTBOX_TEST_TENANT"); +var appKey = Environment.GetEnvironmentVariable("OUTBOX_TEST_APP_KEY"); +if (string.IsNullOrWhiteSpace(tenant) || string.IsNullOrWhiteSpace(appKey)) +{ + Console.Error.WriteLine("Set OUTBOX_TEST_TENANT and OUTBOX_TEST_APP_KEY."); + return 1; +} + +try +{ + using var pinned = X509Certificate2.CreateFromPem(File.ReadAllText(args[4])); + var pinnedBytes = pinned.RawData; + using var handler = new HttpClientHandler + { + AllowAutoRedirect = false, + UseProxy = false, + ServerCertificateCustomValidationCallback = (_, certificate, _, errors) => + certificate != null && + (errors & (SslPolicyErrors.RemoteCertificateNotAvailable | SslPolicyErrors.RemoteCertificateNameMismatch)) == 0 && + certificate.RawData.AsSpan().SequenceEqual(pinnedBytes) + }; + using var http = new HttpClient(handler); + var upload = new ArtifactUploadClient(http, endpoint, tenant, appKey); + var consumer = new DiagnosticOutboxConsumer(args[0], upload, TimeSpan.FromSeconds(30)); + var deleted = await consumer.ProcessCaseAsync(args[1], args[2]); + Console.WriteLine(deleted ? "CONFIRMED_AND_DELETED" : "NOT_CONFIRMED_OR_SKIPPED"); + return deleted ? 0 : 2; +} +catch (Exception error) +{ + Console.Error.WriteLine($"{error.GetType().Name}: {error.Message}"); + return 1; +} diff --git a/tests/OutboxLockHelper/OutboxLockHelper.csproj b/tests/OutboxLockHelper/OutboxLockHelper.csproj new file mode 100644 index 00000000..238f157e --- /dev/null +++ b/tests/OutboxLockHelper/OutboxLockHelper.csproj @@ -0,0 +1,8 @@ + + + Exe + net10.0 + enable + enable + + diff --git a/tests/OutboxLockHelper/Program.cs b/tests/OutboxLockHelper/Program.cs new file mode 100644 index 00000000..c341536c --- /dev/null +++ b/tests/OutboxLockHelper/Program.cs @@ -0,0 +1,11 @@ +namespace OutboxLockHelper; + +public static class Program +{ + public static void Main(string[] args) + { + using var file = new FileStream(args[0], FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None); + Console.WriteLine("ready"); + Console.ReadLine(); + } +}