diff --git a/docs/diagnostic-artifact-transport.md b/docs/diagnostic-artifact-transport.md new file mode 100644 index 00000000..2119abb7 --- /dev/null +++ b/docs/diagnostic-artifact-transport.md @@ -0,0 +1,53 @@ +# 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. + +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 +restart. Do not retry a GUID with newly generated or changed ZIP bytes. This API +does not validate the archive or its manifest. The host must also obtain consent +and apply its own evidence selection, redaction, storage protection and retention +policy: crash dumps and logs can contain credentials and personal information. + +```csharp +using GeneralUpdate.Core.Diagnostics; +using System.Net.Http; + +// Configure TLS, authentication and timeouts for the deployment. Do not allow +// automatic redirects: a redirect could disclose the ZIP or tenant header. +using var handler = new HttpClientHandler { AllowAutoRedirect = false }; +using var http = new HttpClient(handler); +var upload = new ArtifactUploadClient( + http, new Uri("https://example.com/Fault/UploadArtifact"), + tenantId: tenantId, appKey: appKey); +var result = await upload.UploadAsync(new ArtifactUploadMetadata { + Guid = caseGuid, Kind = "crash", Schema = 2, + Version = version, TargetName = targetName +}, zipBytes, cancellationToken); +``` + +Tenant and app identity must come from trusted host configuration, not the +manifest. The current GeneralSpace anonymous endpoint accepts `X-Tenant-Id` but +does not authenticate `AppKey`; the host must secure access via its deployment +gateway or another authenticated channel. Do not treat either field as proof of +identity. The host owns the `HttpClient` and must restrict redirects, credentials, +proxies and destination appropriately. + +The default ZIP limit is 19 MiB, configurable up to the GeneralSpace 20 MiB +request limit; multipart overhead is included when checking the hard limit. +Servers may impose a lower limit. HTTP and application-level failures throw; +cancellation propagates. The response is accepted only for HTTP success, +`code=200`, `isSuccess=true`, a matching artifact ID, and explicit `duplicate` +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. diff --git a/src/GeneralUpdate.Core/Diagnostics/ArtifactUploadClient.cs b/src/GeneralUpdate.Core/Diagnostics/ArtifactUploadClient.cs new file mode 100644 index 00000000..6b7d5522 --- /dev/null +++ b/src/GeneralUpdate.Core/Diagnostics/ArtifactUploadClient.cs @@ -0,0 +1,166 @@ +using System; +using System.Globalization; +using System.IO; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Security.Cryptography; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; + +namespace GeneralUpdate.Core.Diagnostics; + +/// Uploads an already prepared, immutable diagnostic ZIP to GeneralSpace. +/// +/// This transport does not scan or delete Bowl's outbox. Callers must acquire a +/// coordinated snapshot and retain the same ZIP bytes for every retry. +/// +public sealed class ArtifactUploadClient +{ + private const long RequestLimit = 20_971_520; + private const int ResponseLimit = 64 * 1024; + private readonly HttpClient _client; + private readonly Uri _endpoint; + private readonly string _tenantId; + private readonly string _appKey; + private readonly long _maxZipBytes; + + /// + /// Creates an opt-in transport. The host owns the HTTP client, including its + /// authentication, redirect and TLS policies, and supplies tenant and app identity. + /// + public ArtifactUploadClient(HttpClient client, Uri endpoint, string tenantId, string appKey, + long maxZipBytes = 19 * 1024 * 1024) + { + _client = client ?? throw new ArgumentNullException(nameof(client)); + _endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint)); + if (!endpoint.IsAbsoluteUri || endpoint.Scheme != Uri.UriSchemeHttps || + !string.IsNullOrEmpty(endpoint.UserInfo) || !string.IsNullOrEmpty(endpoint.Fragment)) + throw new ArgumentException("The artifact endpoint must be an absolute HTTPS URI without credentials or a fragment.", nameof(endpoint)); + _tenantId = RequireText(tenantId, nameof(tenantId)); + _appKey = RequireText(appKey, nameof(appKey)); + if (maxZipBytes <= 0 || maxZipBytes > RequestLimit) + throw new ArgumentOutOfRangeException(nameof(maxZipBytes)); + _maxZipBytes = maxZipBytes; + } + + /// + /// Sends one ZIP. Older servers deduplicate by GUID alone and cannot confirm + /// that their stored bytes match this request. + /// + /// Metadata for the snapshot, supplied by the host. + /// ZIP bytes that must remain unchanged while copied and across retries. + /// Cancellation token. + public async Task UploadAsync(ArtifactUploadMetadata artifact, byte[] zip, + CancellationToken cancellationToken = default) + { + if (artifact == null) throw new ArgumentNullException(nameof(artifact)); + if (zip == null) throw new ArgumentNullException(nameof(zip)); + if (zip.Length == 0 || zip.LongLength > _maxZipBytes) + throw new ArgumentException("The ZIP is empty or exceeds the configured size limit.", nameof(zip)); + var guid = artifact.Guid; + var kind = artifact.Kind; + var schema = artifact.Schema; + if (!Guid.TryParseExact(guid, "D", out _) || + !string.Equals(kind, "crash", StringComparison.Ordinal) || schema != 2) + throw new ArgumentException("Only schema 2 crash artifacts with a canonical GUID are supported.", nameof(artifact)); + + var version = RequireText(artifact.Version, nameof(artifact.Version)); + var target = RequireText(artifact.TargetName, nameof(artifact.TargetName)); + var snapshot = (byte[])zip.Clone(); + string hash; + using (var sha256 = SHA256.Create()) + hash = BitConverter.ToString(sha256.ComputeHash(snapshot)).Replace("-", "").ToLowerInvariant(); + using var request = new HttpRequestMessage(HttpMethod.Post, _endpoint); + request.Headers.Add("X-Tenant-Id", _tenantId); + using var form = new MultipartFormDataContent(); + request.Content = form; + form.Add(new StringContent(guid), "Guid"); + form.Add(new StringContent(kind), "Kind"); + form.Add(new StringContent(schema.ToString(CultureInfo.InvariantCulture)), "Schema"); + form.Add(new StringContent(_appKey), "AppKey"); + form.Add(new StringContent(version), "Version"); + form.Add(new StringContent(target), "TargetName"); + var file = new ByteArrayContent(snapshot); + file.Headers.ContentType = new MediaTypeHeaderValue("application/zip"); + form.Add(file, "file", guid + ".zip"); + + var requestLength = form.Headers.ContentLength; + if (!requestLength.HasValue || requestLength.Value > RequestLimit) + throw new InvalidOperationException("The multipart request exceeds the GeneralSpace transport limit."); + + using var response = await _client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken) + .ConfigureAwait(false); + response.EnsureSuccessStatusCode(); + using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); + using var buffer = new MemoryStream(); + var chunk = new byte[4096]; + int read; + while ((read = await stream.ReadAsync(chunk, 0, chunk.Length, cancellationToken).ConfigureAwait(false)) != 0) + { + if (buffer.Length + read > ResponseLimit) + throw new InvalidDataException("The artifact response exceeds the size limit."); + buffer.Write(chunk, 0, read); + } + + using var json = JsonDocument.Parse(buffer.ToArray()); + var root = json.RootElement; + if (root.ValueKind != JsonValueKind.Object || + !root.TryGetProperty("code", out var code) || code.ValueKind != JsonValueKind.Number || + !code.TryGetInt32(out var status) || status != 200 || + !root.TryGetProperty("isSuccess", out var success) || success.ValueKind != JsonValueKind.True || + !root.TryGetProperty("body", out var body) || body.ValueKind != JsonValueKind.Object || + !body.TryGetProperty("artifactId", out var id) || id.ValueKind != JsonValueKind.String || + !string.Equals(id.GetString(), guid, StringComparison.OrdinalIgnoreCase) || + !body.TryGetProperty("duplicate", out var duplicate) || + (duplicate.ValueKind != JsonValueKind.True && duplicate.ValueKind != JsonValueKind.False) || + !body.TryGetProperty("parsed", out var parsed) || + (parsed.ValueKind != JsonValueKind.True && parsed.ValueKind != JsonValueKind.False)) + throw new InvalidDataException("GeneralSpace did not confirm the artifact upload."); + + var hashVerified = false; + if (body.TryGetProperty("contentSha256", out var returnedHash)) + { + if (returnedHash.ValueKind != JsonValueKind.String || + !string.Equals(returnedHash.GetString(), hash, StringComparison.OrdinalIgnoreCase)) + throw new InvalidDataException("GeneralSpace returned a different artifact content hash."); + hashVerified = true; + } + + return new ArtifactUploadResult(duplicate.GetBoolean(), parsed.GetBoolean(), hashVerified); + } + + private static string RequireText(string? value, string name) + { + if (string.IsNullOrWhiteSpace(value) || value!.Length > 256 || + value.IndexOf('\r') >= 0 || value.IndexOf('\n') >= 0) + throw new ArgumentException("The value must be nonempty, at most 256 characters, and contain no line breaks.", name); + return value; + } +} + +/// Metadata for a schema 2 crash snapshot; identity is configured separately. +public sealed class ArtifactUploadMetadata +{ + public string Guid { get; set; } = string.Empty; + public string Kind { get; set; } = string.Empty; + public int Schema { get; set; } + public string Version { get; set; } = string.Empty; + public string TargetName { get; set; } = string.Empty; +} + +/// The server's acknowledgment; it does not authorize source deletion. +public sealed class ArtifactUploadResult +{ + internal ArtifactUploadResult(bool duplicate, bool parsed, bool hashVerified) + { + Duplicate = duplicate; + Parsed = parsed; + HashVerified = hashVerified; + } + + public bool Duplicate { get; } + public bool Parsed { get; } + /// Whether the server returned a matching SHA-256 for the ZIP bytes. + public bool HashVerified { get; } +} diff --git a/tests/CoreTest/Diagnostics/ArtifactUploadClientTests.cs b/tests/CoreTest/Diagnostics/ArtifactUploadClientTests.cs new file mode 100644 index 00000000..aab4f750 --- /dev/null +++ b/tests/CoreTest/Diagnostics/ArtifactUploadClientTests.cs @@ -0,0 +1,162 @@ +using System.Net; +using System.Security.Cryptography; +using System.Text; +using GeneralUpdate.Core.Diagnostics; + +namespace CoreTest.Diagnostics; + +public class ArtifactUploadClientTests +{ + private const string Id = "86c1ae61-89e9-450d-93b0-a7f512c06768"; + private static readonly byte[] Zip = [0x50, 0x4b, 0x03, 0x04]; + + [Fact] + public async Task Upload_UsesExplicitIdentityAndMultipart() + { + var handler = new Handler(async request => + { + Assert.Equal("tenant-a", request.Headers.GetValues("X-Tenant-Id").Single()); + Assert.Equal("multipart/form-data", request.Content!.Headers.ContentType!.MediaType); + Assert.True(request.Content.Headers.ContentLength < 20_971_520); + var payload = await request.Content.ReadAsStringAsync(); + Assert.Contains("name=Guid", payload); + Assert.Contains(Id, payload); + Assert.Contains("name=AppKey", payload); + Assert.Contains("app-a", payload); + Assert.Contains("name=file", payload); + return Response(Success()); + }); + var result = await Client(handler).UploadAsync(Metadata(), Zip); + Assert.False(result.Duplicate); + Assert.True(result.Parsed); + Assert.False(result.HashVerified); + } + + [Theory] + [InlineData("{\"code\":400,\"isSuccess\":false,\"body\":null}")] + [InlineData("{\"code\":500,\"isSuccess\":false,\"body\":null}")] + [InlineData("{\"code\":200,\"isSuccess\":false,\"body\":{}}")] + [InlineData("{\"code\":200,\"body\":{}}")] + [InlineData("{\"code\":200,\"isSuccess\":true,\"body\":{\"artifactId\":\"other\",\"duplicate\":false,\"parsed\":true}}")] + [InlineData("{\"code\":200,\"isSuccess\":true,\"body\":{\"artifactId\":\"86c1ae61-89e9-450d-93b0-a7f512c06768\"}}")] + public async Task Http200WithInvalidBusinessResponse_IsRejected(string body) + { + var client = Client(new Handler(_ => Task.FromResult(Response(body)))); + await Assert.ThrowsAsync(() => client.UploadAsync(Metadata(), Zip)); + } + + [Fact] + public async Task FailedUploadCanBeRetriedWithSameBytes_AndDuplicateIsNotHidden() + { + var attempts = 0; + var payloads = new List(); + var handler = new Handler(async request => + { + var parts = (MultipartFormDataContent)request.Content!; + var file = parts.Single(p => p.Headers.ContentDisposition!.Name == "file"); + payloads.Add(await file.ReadAsByteArrayAsync()); + attempts++; + return attempts == 1 + ? new HttpResponseMessage(HttpStatusCode.ServiceUnavailable) + : Response(Success(duplicate: true, parsed: false)); + }); + var client = Client(handler); + await Assert.ThrowsAsync(() => client.UploadAsync(Metadata(), Zip)); + var result = await client.UploadAsync(Metadata(), Zip); + Assert.True(result.Duplicate); + Assert.False(result.Parsed); + Assert.False(result.HashVerified); + Assert.Equal(payloads[0], payloads[1]); + } + + [Fact] + public async Task ServerHashMustMatchTheZip() + { + var hash = Convert.ToHexString(SHA256.HashData(Zip)).ToLowerInvariant(); + var matching = Client(new Handler(_ => Task.FromResult(Response(Success(duplicate: true, hash: hash))))); + Assert.True((await matching.UploadAsync(Metadata(), Zip)).HashVerified); + var wrong = Client(new Handler(_ => Task.FromResult(Response(Success(hash: new string('0', 64)))))); + await Assert.ThrowsAsync(() => wrong.UploadAsync(Metadata(), Zip)); + } + + [Fact] + public async Task CallerMutationAfterSendDoesNotChangeTheSnapshot() + { + var bytes = (byte[])Zip.Clone(); + var expected = (byte[])bytes.Clone(); + var handler = new Handler(async request => + { + bytes[0] = 0; + var file = ((MultipartFormDataContent)request.Content!).Single(p => p.Headers.ContentDisposition!.Name == "file"); + Assert.Equal(expected, await file.ReadAsByteArrayAsync()); + return Response(Success(hash: Convert.ToHexString(SHA256.HashData(expected)).ToLowerInvariant())); + }); + Assert.True((await Client(handler).UploadAsync(Metadata(), bytes)).HashVerified); + } + + [Fact] + public async Task CancellationIsPropagated() + { + var client = Client(new Handler(_ => throw new OperationCanceledException())); + await Assert.ThrowsAnyAsync(() => client.UploadAsync(Metadata(), Zip)); + } + + [Fact] + public async Task UnknownSchemaAndOversizedInputAreRejectedBeforeSending() + { + var handler = new Handler(_ => throw new Exception("Unexpected network request")); + var client = Client(handler, maxZipBytes: 3); + await Assert.ThrowsAsync(() => client.UploadAsync(Metadata(), Zip)); + var metadata = Metadata(); + metadata.Schema = 3; + await Assert.ThrowsAsync(() => Client(handler).UploadAsync(metadata, Zip)); + } + + [Fact] + public async Task MultipartOverheadCountsTowardServerLimit() + { + var handler = new Handler(_ => throw new Exception("Unexpected network request")); + var client = Client(handler, maxZipBytes: 20_971_520); + await Assert.ThrowsAsync( + () => client.UploadAsync(Metadata(), new byte[20_971_520])); + } + + [Fact] + public async Task OversizedOrMalformedResponseIsRejected() + { + var oversized = Client(new Handler(_ => Task.FromResult(Response(new string('x', 65537))))); + await Assert.ThrowsAsync(() => oversized.UploadAsync(Metadata(), Zip)); + var malformed = Client(new Handler(_ => Task.FromResult(Response("{")))); + await Assert.ThrowsAnyAsync(() => malformed.UploadAsync(Metadata(), Zip)); + } + + [Fact] + public void RequiresHttpsAndExplicitIdentity() + { + using var http = new HttpClient(new Handler(_ => Task.FromResult(Response(Success())))); + Assert.Throws(() => new ArtifactUploadClient(http, new Uri("http://example.test"), "tenant", "app")); + Assert.Throws(() => new ArtifactUploadClient(http, new Uri("https://example.test"), "", "app")); + Assert.Throws(() => new ArtifactUploadClient(http, new Uri("https://example.test"), "tenant", "")); + } + + private static ArtifactUploadClient Client(Handler handler, long maxZipBytes = 1024) => + new(new HttpClient(handler), new Uri("https://example.test/Fault/UploadArtifact"), "tenant-a", "app-a", maxZipBytes); + + private static ArtifactUploadMetadata Metadata() => new() + { + Guid = Id, Kind = "crash", Schema = 2, Version = "1.0", TargetName = "client" + }; + + private static string Success(bool duplicate = false, bool parsed = true, string? hash = null) => + $"{{\"code\":200,\"isSuccess\":true,\"body\":{{\"artifactId\":\"{Id}\",\"duplicate\":{duplicate.ToString().ToLowerInvariant()},\"parsed\":{parsed.ToString().ToLowerInvariant()}{(hash == null ? "" : $",\"contentSha256\":\"{hash}\"")}}}}}"; + + private static HttpResponseMessage Response(string content) => new(HttpStatusCode.OK) + { + Content = new StringContent(content, Encoding.UTF8, "application/json") + }; + + private sealed class Handler(Func> send) : HttpMessageHandler + { + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) => send(request); + } +}