diff --git a/.gitignore b/.gitignore index e50034a2..e332ee6a 100644 --- a/.gitignore +++ b/.gitignore @@ -194,3 +194,6 @@ FakesAssemblies/ src/.vs src/.idea src/global.json + +# Mimosa security scan local state +.mimosa/ diff --git a/docs/bowl-integration-v1.md b/docs/bowl-integration-v1.md index 27f4f0a3..7263692f 100644 --- a/docs/bowl-integration-v1.md +++ b/docs/bowl-integration-v1.md @@ -24,6 +24,47 @@ after starting the application. ## Configuration +For crash collection during an update, enable the independent option on the +Client bootstrap: + +```csharp +bootstrap.SetOption(Option.BowlCrashCollectionEnabled, true); +``` + +It defaults off. When enabled it requests v1 monitoring and crash capture, +using `C:\Bowl\Bowl.Host.exe` unless `Monitoring.ExecutablePath` is already +set. Deploy a compatible Bowl host first; an unavailable host stops the update +before application files are changed. This option does not change +`LaunchClientAfterUpdate`: without application relaunch, Bowl supervises the +updater but has no relaunched application to observe. Capture is Windows-only +and limited to the v1 update/health-observation window, not a long-running +watchdog. A valid target version is required. + +The current standalone Bowl.Host does not implement that crash capture request +or produce `crash-outbox` cases. The separate `bowl.exe watch` diagnostic +program produces legacy `\fail` cases, but is not launched by this +option and must be deployed and configured separately. Do not rely on this +option alone to collect crashes with the current Bowl.Host. + +The Client uploads Bowl's completed crash cases from +`\crash-outbox\\`; the legacy +`\fail` outbox remains supported. Use the same durable state root +for updater, Bowl and subsequent Client runs. Configure `ReportUrl` (whose +origin determines `/Fault/UploadArtifact`) or `Option.DiagnosticsReportUrl`, +and set `X-Tenant-Id` through `UpdateRequest.CustomHeaders` as required by +GeneralSpace. Outbox failures remain on disk for retry on a subsequent Client +run; no retry limit applies to this option. Evidence is removed only after the +server returns HTTP success, JSON `code` 200 and a matching `body.artifactId`. +Oversized or excluded dumps remain on disk. Existing separately enabled +self-check/rollback diagnostics are unchanged. + +Ordinary update failures with a server record ID also publish a minimal, +credential-free case under `\update-outbox\\`. +It contains only an allowlisted failure phase and record identifiers, not a +stack trace or dump. A subsequent Client run with diagnostics enabled and the +same installation identity uploads it; failed delivery remains pending without +a retry limit. No case is created if the server record ID is unavailable. + Configure `UpdateRequest.Monitoring` and `UpdateRequest.DiagnosticsDirectory` through `SetConfig`, JSON configuration, or `UpdateRequestBuilder`: @@ -38,11 +79,26 @@ builder.SetDiagnosticsDirectory(@"C:\ProgramData\MyProduct\UpdateState") HealthTimeoutSeconds = 5, UpdateTimeoutSeconds = 600, AutoRollback = false, - CredentialEnvironmentVariable = "MYPRODUCT_REPORT_TOKEN" + CredentialEnvironmentVariable = "MYPRODUCT_REPORT_TOKEN", + AppKeyEnvironmentVariable = "MYPRODUCT_APP_KEY" }); ``` Only enable this after deploying a separately validated compatible production host. +`AppKeyEnvironmentVariable` names a separately provisioned environment variable +whose value must equal the verification `AppSecretKey`; it must be available to +both the initial host and every `--retry` process. Only the name is persisted. +App-key reporting requires HTTPS (or HTTP to a literal loopback IP for local +testing). Missing credentials leave Bowl delivery pending. + +**Automatic monitored rollback is currently unavailable.** Setting `AutoRollback` +to true aborts before application files are modified: the producer cannot yet +provide Bowl's complete write-ahead rollback plan. In particular, do not use +older mirror-rollback hosts against real installations: backup-excluded +directories and newly created user data could otherwise be deleted. +The Client rejects all update preparation when monitored automatic rollback +is requested: backup and updater packages otherwise run before the monitor +can hold a trusted installation lease. Timeouts must be positive and the update timeout must exceed the readiness timeout. Missing executables, malformed/mismatched ready records, host exit, or readiness timeout abort the update before application file operations. @@ -61,6 +117,11 @@ including attempts launched by different users or schedulers. Bowl's persistent installation-owner lock is scoped to that root; choosing a fresh root per attempt would bypass cross-attempt coordination. Configure an explicit shared root when the default per-user directory does not provide this guarantee. +The Client stores a random installation UUID under that root and sends it as +`deviceId` in both version-verification calls; keep the root and installation +path stable across upgrades and restarts. Clearing the root, relocating the +installation, or using different roots creates a new identity. Custom download +sources must provide their own stable identity when calling GeneralSpace. Client creates `UpdateAttemptId` once per workflow; standard/silent IPC carries it, the root and monitor options to Update. OSS transfers these through child @@ -103,11 +164,13 @@ replaceable files must permit `FileShare.Delete` as well as reading. "healthTimeoutSeconds": 5, "updateTimeoutSeconds": 600, "autoRollback": false, + "crashCollectionEnabled": false, "report": { "url": "https://updates.example.test/report", "recordId": 42, "type": 1, - "credentialEnvironmentVariable": "MYPRODUCT_REPORT_TOKEN" + "credentialEnvironmentVariable": "MYPRODUCT_REPORT_TOKEN", + "appKeyEnvironmentVariable": "MYPRODUCT_APP_KEY" } } ``` @@ -219,7 +282,8 @@ Bowl.Host --retry 100 --state-root ``` The retry limit is 1 through 100. Failed HTTP delivery stays pending and follows -the host's retry backoff; only 2xx acknowledges it. Provision reporting credentials +the host's retry backoff; app-key reports require HTTP success and JSON +`code=200`, `isSuccess=true`, `body=true`. Provision reporting credentials for that scheduled process as well as the initially launched host. The optional Bearer environment credential is only sent over HTTPS. @@ -270,7 +334,13 @@ depend on a successful network call. Default HTTP serialization is deliberately still exactly `{"recordId":42,"status":2,"type":1}` (1 Updating / 2 Success / 3 Failure). -The richer local shape is **not uploaded** and no server API is changed. +When configured by the bootstrap, the in-memory app key is also sent in the +HTTP body and never persisted in pending reports. A scheduler replaying pending +reports must configure the reporter with the same app key and endpoint used by +the original verification; a business rejection keeps the report pending. +Credentialed reports require HTTPS or a literal loopback HTTP address and a +confirmed GeneralSpace business response. Legacy uncredentialed endpoints may +still acknowledge with an empty 2xx response. The richer local shape is **not uploaded**. Non-2xx responses now throw from `HttpUpdateReporter`; role-level wrappers log/isolate them so application/rollback work can proceed. Direct reporter callers must handle those exceptions. `monitorUnavailable` has no honest @@ -309,6 +379,12 @@ $env:GENERALUPDATE_REAL_BOWL_HOST = 'C:\External\Bowl.Host.exe' dotnet test tests\CoreTest\CoreTest.csproj --filter FullyQualifiedName~RealBowlIntegrationTests ``` +On Windows, setting `GENERALUPDATE_CRASH_TEST_PEER` to the independently built +`Bowl.TestPeer.dll` also enables a real unhandled-exception capture test. It +checks the resulting nonempty dump and schema-2 outbox, then exercises the +Client scanner against a simulated HTTP server that first rejects the upload +at the business layer and then acknowledges the same GUID. + Six scenarios have been verified against the independently built net8.0 host: files-only success, the complete application-survival window, launch failure, application exit during that window (`healthCheckFailure`), real updater diff --git a/docs/controlled-full-zip-apply-internal.md b/docs/controlled-full-zip-apply-internal.md new file mode 100644 index 00000000..eebb1856 --- /dev/null +++ b/docs/controlled-full-zip-apply-internal.md @@ -0,0 +1,77 @@ +# Internal controlled full ZIP apply foundation + +This Windows-only component is **not wired into production**, is not an +authorization entrypoint, and does not perform rollback or recovery. It assumes +a trusted caller with externally enforced exclusive access to the target tree, +staging files, snapshots, and state directory for the whole operation and any +subsequent recovery. Path and hash checks do not provide fencing or establish +ACL authorization. Do not call it against a live, concurrently writable tree. + +`GeneralUpdate.ControlledWorker` is a separate executable placeholder for a +future production controller. It currently rejects every invocation with exit +code 2 without reading requests, preparing snapshots, or writing to disk. The +test-only READY/GO protocol below must not be used to enable it. A production +implementation requires an independently verified Host protocol and full +recovery/reporting lifecycle before this guard can be removed. + +`ControlledFullZipPlan` copies the supplied entries and protected relative paths. +Each `ControlledFullZipEntry` describes a relative destination, staged payload and +SHA-256, and either a snapshot plus original SHA-256, or two nulls indicating a +destination that must not exist. Paths use canonical Windows spelling and `\` +separators. The caller must provide existing destination parent directories, +existing stage and snapshot files, and an existing trusted state directory. +State and inputs must be outside the target tree; state is also separate from +inputs. Only fixed local NTFS volumes are supported. Reparse points, hard-linked +files, alternate streams, sparse, encrypted, offline, read-only and device files, +short-name-style components, reserved names, overlapping entries and protected +paths are rejected. `.backups` is always protected. There is no directory +creation, file deletion, metadata preservation contract, or support for +arbitrary package executors. + +`ControlledFullZipPrepare.Prepare` builds this write set from one staged full ZIP. +It requires disjoint existing target, state, stage and empty backup directories, +checks the complete set of target paths and opens existing originals before +copying and flushing snapshots under `backup\`. The target parent +directories must already exist. Preparation retains any partial snapshots after +failure and does not create an intent or modify the installation. Like apply, +it requires an independently authenticated controller and exclusive access; +its checks cannot establish either. It does not preserve file metadata. +Once an intent is published, the owner must retain the stage as well as the +snapshots until a trusted recovery or completion decision. Calling +`StagedZip.RetainForRecovery` in the intent callback prevents normal disposal +from removing files referenced by the intent; this transfers cleanup ownership +to the controller and is not itself a cleanup or recovery protocol. + +`ControlledFullZipApply.Apply(plan)` validates every entry and verifies the +original, snapshot and payload hashes before writing targets. It flushes supplied +snapshots, publishes a complete versioned JSON intent in the state directory +using create-new and `Flush(true)`, then copies each payload to a create-new +temporary file in the destination directory, flushes and verifies it, checks the +target again, replaces or moves without overwrite, and verifies the result. The +intent includes entries with `path`, `originalSha256` (null for new files), and +`updatedSha256`, plus paths required to inspect the operation. Snapshots remain +at the caller-provided paths and must remain protected and available. On failure, +intent, snapshots, and any temporary files are retained; exceptions report +conflicts. Nothing automatically removes unknown content. + +There is no cross-file transaction, external fencing, progress journal, resume, +or automatic recovery. A process interruption can leave some files applied and +temporary files or incomplete `.writing` state files. Even after `Flush(true)` +and rename, power-loss durability of directory entries and replace operations is +not proven; neither the intent nor targets are guaranteed to be in only an old +or new state after power loss. A future Host must independently validate and +interpret the persisted intent and snapshots, maintain its own recovery journal, +and decide how to handle conflicts and retained artifacts. + +The opt-in cross-repository tests can set `GENERALUPDATE_BOWL_SUPERVISOR` to a +separately built `Bowl.TestPeer.exe`. Its **test-only** supervisor starts the +`MonitoringTestHost` fixture in a Windows Job and exchanges READY/GO/DONE over +a PID-checked pipe. Only after GO does the fixture download a loopback ZIP, +prepare the write set and apply it. Failure cases exercise Bowl's test recovery; +another test kills the supervisor and checks worker termination and rejection of +attempt reuse. This is not the production Bowl.Host entrypoint, service +authentication, an authorization protocol, or proof of safe crash restart. +An additional test enables the supervisor's test-only durable delivery and +verifies a 503 leaves a pending outbox, then a separate retry process sends the +same event and receives a business acknowledgment. No credential is stored in +the outbox. This exercises the test supervisor, not production reporting. diff --git a/src/GeneralUpdate.ControlledWorker/GeneralUpdate.ControlledWorker.csproj b/src/GeneralUpdate.ControlledWorker/GeneralUpdate.ControlledWorker.csproj new file mode 100644 index 00000000..b388a40c --- /dev/null +++ b/src/GeneralUpdate.ControlledWorker/GeneralUpdate.ControlledWorker.csproj @@ -0,0 +1,9 @@ + + + Exe + net8.0 + enable + enable + false + + diff --git a/src/GeneralUpdate.ControlledWorker/Program.cs b/src/GeneralUpdate.ControlledWorker/Program.cs new file mode 100644 index 00000000..d9a60afc --- /dev/null +++ b/src/GeneralUpdate.ControlledWorker/Program.cs @@ -0,0 +1,4 @@ +// This entrypoint deliberately accepts no authorization until the production +// Host protocol and its process/lease binding have been implemented. +Console.Error.WriteLine("Controlled worker unavailable: production Host authorization is not implemented."); +return 2; diff --git a/src/GeneralUpdate.Core/Bootstrap/GeneralUpdateBootstrap.cs b/src/GeneralUpdate.Core/Bootstrap/GeneralUpdateBootstrap.cs index 2f15bb26..ca736351 100644 --- a/src/GeneralUpdate.Core/Bootstrap/GeneralUpdateBootstrap.cs +++ b/src/GeneralUpdate.Core/Bootstrap/GeneralUpdateBootstrap.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.IO; using System.Linq; +using System.Runtime.InteropServices; using System.Threading; using System.Text; using System.Text.Json; @@ -136,11 +137,14 @@ public override async Task LaunchAsync() return appType switch { - AppType.Client => await LaunchWithStrategy(new ClientStrategy()), - AppType.Upgrade => await LaunchWithStrategy(new UpdateStrategy()), - AppType.OssClient => await LaunchWithStrategy(new OssStrategy(AppType.OssClient)), - AppType.OssUpgrade => await LaunchWithStrategy(new OssStrategy(AppType.OssUpgrade)), - _ => await LaunchWithStrategy(new ClientStrategy()) + // Library entry points must not hop back to a host SynchronizationContext + // (a UI host blocking with .Result would deadlock) — ConfigureAwait(false) + // consistently on the library side. + AppType.Client => await LaunchWithStrategy(new ClientStrategy()).ConfigureAwait(false), + AppType.Upgrade => await LaunchWithStrategy(new UpdateStrategy()).ConfigureAwait(false), + AppType.OssClient => await LaunchWithStrategy(new OssStrategy(AppType.OssClient)).ConfigureAwait(false), + AppType.OssUpgrade => await LaunchWithStrategy(new OssStrategy(AppType.OssUpgrade)).ConfigureAwait(false), + _ => await LaunchWithStrategy(new ClientStrategy()).ConfigureAwait(false) }; } @@ -166,7 +170,7 @@ private async Task LaunchWithStrategy(IStrategy roleStra roleStrategy.Create(_configInfo); - await roleStrategy.ExecuteAsync(); + await roleStrategy.ExecuteAsync().ConfigureAwait(false); } catch (Exception ex) { @@ -474,6 +478,15 @@ private void ApplyRuntimeOptions() _configInfo.RetryInterval = GetOption(Option.RetryInterval); _configInfo.VerifyChecksum = GetOption(Option.VerifyChecksum); _configInfo.DiffMode = GetOption(Option.DiffMode); + + if (GetOption(Option.BowlCrashCollectionEnabled)) + { + _configInfo.Monitoring ??= new Configuration.BowlOptions(); + _configInfo.Monitoring.Enabled = true; + _configInfo.Monitoring.CrashCollectionEnabled = true; + if (string.IsNullOrWhiteSpace(_configInfo.Monitoring.ExecutablePath)) + _configInfo.Monitoring.ExecutablePath = @"C:\Bowl\Bowl.Host.exe"; + } } /// @@ -530,7 +543,10 @@ private void ConfigureStrategy(IStrategy roleStrategy) var reporter = ResolveExtension() ?? new Download.Reporting.HttpUpdateReporter(); if (reporter is Download.Reporting.HttpUpdateReporter httpReporter) + { httpReporter.ReportUrl = _configInfo.ReportUrl; + httpReporter.AppKey = _configInfo.AppSecretKey; + } roleStrategy.Reporter = reporter; var diffPipeline = BuildDiffPipeline(); @@ -545,7 +561,7 @@ private void ConfigureStrategy(IStrategy roleStrategy) if (downloadPipeline != null) downloadPipelineFactory = _ => downloadPipeline; - var diagnostics = BuildDiagnosticsChannel(); + var diagnostics = BuildDiagnosticsChannel(roleStrategy is ClientStrategy); switch (roleStrategy) { case ClientStrategy cs: @@ -564,7 +580,7 @@ private void ConfigureStrategy(IStrategy roleStrategy) us.SetReportType(_configInfo.ReportType); us.SetSelfCheckRules(ResolveSelfCheckRules()); us.LaunchBowl = GetOption(Option.LaunchBowl); - us.SetDiagnosticsUploader(diagnostics?.Uploader); + us.SetDiagnosticsChannel(diagnostics); break; } @@ -595,26 +611,69 @@ private DiffPipeline BuildDiffPipeline() } /// - /// Builds the client diagnostics channel when the upload switch is on and a report URL - /// is configured; null otherwise, keeping every diagnostics path inert. + /// Builds the client diagnostics channel when the upload switch is on; null + /// otherwise, keeping every diagnostics path inert. /// - private Diagnostics.DiagnosticsChannel? BuildDiagnosticsChannel() + /// + /// Endpoint resolution: an explicit wins; when it + /// is empty the GeneralSpace artifact endpoint is derived from the status report URL's + /// origin ({origin}/Fault/UploadArtifact) — the reporter and the diagnostics + /// channel always target the same server in a GeneralSpace deployment. + /// + private Diagnostics.DiagnosticsChannel? BuildDiagnosticsChannel(bool clientRole) { - if (!GetOption(Option.DiagnosticsUploadEnabled)) + var crashCollection = clientRole && GetOption(Option.BowlCrashCollectionEnabled); + if (!GetOption(Option.DiagnosticsUploadEnabled) && !crashCollection) return null; var url = GetOption(Option.DiagnosticsReportUrl); if (string.IsNullOrWhiteSpace(url)) { - GeneralTracer.Warn("GeneralUpdateBootstrap: DiagnosticsUploadEnabled without DiagnosticsReportUrl — diagnostics channel disabled."); - return null; + url = DeriveDiagnosticsReportUrl(_configInfo.ReportUrl); + if (string.IsNullOrWhiteSpace(url)) + { + GeneralTracer.Warn( + "GeneralUpdateBootstrap: DiagnosticsUploadEnabled without DiagnosticsReportUrl (and no ReportUrl origin to derive it from) — diagnostics channel disabled."); + return null; + } + + GeneralTracer.Info($"GeneralUpdateBootstrap: DiagnosticsReportUrl derived from the report origin: {url}"); } return new Diagnostics.DiagnosticsChannel(_configInfo.InstallPath, new Diagnostics.DiagnosticsOptions { Enabled = true, - Url = url - }, FileSystem.StorageManager.BlackMatcher); + Url = url, + AppKey = _configInfo.AppSecretKey, + ProductId = _configInfo.ProductId, + Platform = ResolveDiagnosticsPlatform(), + TargetName = _configInfo.MainAppName, + MaxRetry = crashCollection ? 0 : 5, + MaxSizeBytes = 19 * 1024 * 1024, + }, FileSystem.StorageManager.BlackMatcher, + _configInfo.DiagnosticsDirectory ?? Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "GeneralUpdate", "state"), + clientRole ? Configuration.InstallationIdentity.GetOrCreate(_configInfo) : null); + } + + /// Composes the GeneralSpace artifact endpoint from the report URL's origin. + private static string? DeriveDiagnosticsReportUrl(string? reportUrl) + { + if (string.IsNullOrWhiteSpace(reportUrl) || + !Uri.TryCreate(reportUrl, UriKind.Absolute, out var uri) || + (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps)) + return null; + + return $"{uri.Scheme}://{uri.Authority}/Fault/UploadArtifact"; + } + + /// Platform code per the GeneralSpace convention (1 = Windows, 2 = Linux, 3 = macOS). + private static int ResolveDiagnosticsPlatform() + { + // netstandard2.0 target: OperatingSystem.Is* guards are .NET 5+ only. + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) return 1; + if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) return 2; + return 3; } private static Format ParseFormat(string? compressFormat) diff --git a/src/GeneralUpdate.Core/Bowl/BowlLauncher.cs b/src/GeneralUpdate.Core/Bowl/BowlLauncher.cs index 456800ed..d251c352 100644 --- a/src/GeneralUpdate.Core/Bowl/BowlLauncher.cs +++ b/src/GeneralUpdate.Core/Bowl/BowlLauncher.cs @@ -100,7 +100,7 @@ private static bool EnsureRunning(BowlLaunchOptions options, CancellationToken c CreateNoWindow = true }; - using var process = Process.Start(startInfo); + using var process = ProcessLauncher.Start(startInfo); if (process == null) { GeneralTracer.Warn("BowlLauncher: process start returned null — watchdog not started."); @@ -145,13 +145,15 @@ private static string Quote(string value) => /// wrong "not running" verdict is harmless because the watchdog itself exits with /// code 2 on a duplicate start. /// - private static bool IsAlreadyRunning(string instanceKey) + internal static bool IsAlreadyRunning(string instanceKey) { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { try { - using var probe = Mutex.OpenExisting(instanceKey); + // The watchdog creates the mutex under its documented full name + // (SingleInstanceLock.Acquire) — probing the bare key would never match it. + using var probe = Mutex.OpenExisting(BuildMutexName(instanceKey)); return true; } catch (WaitHandleCannotBeOpenedException) @@ -213,4 +215,13 @@ public static string BuildInstanceKey(string targetProcessName, string installPa /// Well-known Unix lock file location (mirrored by the watchdog; temp dir = same user session). public static string GetUnixLockPath(string instanceKey) => Path.Combine(Path.GetTempPath(), "GeneralUpdate", "bowl-locks", $"{instanceKey}.lock"); + + /// + /// Full mutex name the watchdog registers for a target + /// (Global\GeneralUpdate.Bowl.{key}) — byte-identical to the watchdog console's + /// SingleInstanceLock.Acquire. One half of the probe contract: the launcher only + /// ever OPENS this name; the watchdog is its creator. + /// + internal static string BuildMutexName(string instanceKey) => + $"Global\\GeneralUpdate.Bowl.{instanceKey}"; } diff --git a/src/GeneralUpdate.Core/Compress/ControlledFullZipApply.cs b/src/GeneralUpdate.Core/Compress/ControlledFullZipApply.cs new file mode 100644 index 00000000..fcf06171 --- /dev/null +++ b/src/GeneralUpdate.Core/Compress/ControlledFullZipApply.cs @@ -0,0 +1,354 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.IO; +using System.Runtime.InteropServices; +using System.Security.Cryptography; +using System.Text.Json; +using System.Text.Json.Serialization; +using Microsoft.Win32.SafeHandles; + +namespace GeneralUpdate.Core.Compress +{ + // Internal foundation only: the caller must enforce exclusive access to all paths + // and protect the state, stage and snapshot directories against other writers. + // This is neither an authorization boundary nor a recovery implementation. + internal sealed class ControlledFullZipPlan + { + internal ControlledFullZipPlan(string targetRoot, string stateDirectory, + IEnumerable entries, IEnumerable protectedPaths) + { + TargetRoot = targetRoot; + StateDirectory = stateDirectory; + Entries = new ReadOnlyCollection(new List(entries)); + ProtectedPaths = new ReadOnlyCollection(new List(protectedPaths)); + } + + internal string TargetRoot { get; } + internal string StateDirectory { get; } + internal IReadOnlyList Entries { get; } + // Relative paths; a protected directory protects its descendants. + internal IReadOnlyList ProtectedPaths { get; } + } + + internal sealed class ControlledFullZipEntry + { + internal ControlledFullZipEntry(string relativePath, string stagedPath, string payloadSha256, + string? snapshotPath, string? preStateSha256) + { + RelativePath = relativePath; + StagedPath = stagedPath; + PayloadSha256 = payloadSha256; + SnapshotPath = snapshotPath; + PreStateSha256 = preStateSha256; + } + + internal string RelativePath { get; } + internal string StagedPath { get; } + internal string PayloadSha256 { get; } + // Both null means the target must not exist; otherwise both are required. + internal string? SnapshotPath { get; } + internal string? PreStateSha256 { get; } + } + + internal static class ControlledFullZipApply + { + // Callbacks are for internal fault-injection tests; never use them as fencing. + internal static string Apply(ControlledFullZipPlan plan, Action? afterIntent = null, + Action? afterWrite = null) + { + if (plan == null) throw new ArgumentNullException(nameof(plan)); + if (Path.DirectorySeparatorChar != '\\') throw new PlatformNotSupportedException("Windows only."); + string root = Absolute(plan.TargetRoot); + string state = Absolute(plan.StateDirectory); + if (Overlaps(root, state)) throw new InvalidDataException("State and target directories overlap."); + CheckDirectories(root); + CheckDirectories(state); + var protectedPaths = new List(); + foreach (string value in plan.ProtectedPaths) + protectedPaths.Add(Relative(value)); + // Backup data must never become an apply target even if the caller omits it. + protectedPaths.Add(".backups"); + var names = new List(); + var records = new List(); + var inputs = new List(); + try + { + foreach (var entry in plan.Entries) + { + if (entry == null) throw new InvalidDataException("Null entry."); + string relative = Relative(entry.RelativePath); + foreach (string previous in names) + if (Overlaps(previous, relative)) throw new InvalidDataException("Conflicting target paths."); + foreach (string protect in protectedPaths) + if (Overlaps(protect, relative)) throw new InvalidDataException("Protected target path."); + names.Add(relative); + string target = Path.Combine(root, relative); + CheckDirectories(Path.GetDirectoryName(target)!); + string stage = Absolute(entry.StagedPath); + if (Overlaps(root, stage) || Overlaps(state, stage)) + throw new InvalidDataException("Staged file overlaps target or state."); + CheckDirectories(Path.GetDirectoryName(stage)!); + CheckHash(entry.PayloadSha256); + var staged = OpenRegular(stage, false); + inputs.Add(staged); + Verify(staged, entry.PayloadSha256); + bool existing = entry.SnapshotPath != null || entry.PreStateSha256 != null; + string? snapshot = null; + if (existing) + { + if (entry.SnapshotPath == null || entry.PreStateSha256 == null) + throw new InvalidDataException("Snapshot and pre-state hash are both required."); + CheckHash(entry.PreStateSha256); + snapshot = Absolute(entry.SnapshotPath); + if (Overlaps(root, snapshot) || Overlaps(state, snapshot)) + throw new InvalidDataException("Snapshot overlaps target or state."); + CheckDirectories(Path.GetDirectoryName(snapshot)!); + var snap = OpenRegular(snapshot, true); + inputs.Add(snap); + Verify(snap, entry.PreStateSha256); + snap.Flush(true); + } + VerifyTarget(target, entry.PreStateSha256); + string temp = Path.Combine(Path.GetDirectoryName(target)!, ".gu-apply-" + Guid.NewGuid().ToString("N")); + records.Add(new IntentEntry + { + RelativePath = relative, TargetPath = target, StagedPath = stage, + PayloadSha256 = entry.PayloadSha256, SnapshotPath = snapshot, + PreStateSha256 = entry.PreStateSha256, TemporaryPath = temp + }); + } + if (records.Count == 0) throw new InvalidDataException("Empty plan."); + var intent = new Intent { Version = 1, TargetRoot = root, StateDirectory = state, + ProtectedPaths = protectedPaths.ToArray(), Entries = records.ToArray() }; + string intentPath = Path.Combine(state, "apply-" + Guid.NewGuid().ToString("N") + ".json"); + string intentTemp = intentPath + ".writing"; + byte[] json = JsonSerializer.SerializeToUtf8Bytes(intent, ControlledFullZipIntentJsonContext.Default.Intent); + using (var file = new FileStream(intentTemp, FileMode.CreateNew, FileAccess.Write, FileShare.None)) + { + file.Write(json, 0, json.Length); + file.Flush(true); + } + File.Move(intentTemp, intentPath); + afterIntent?.Invoke(); + for (int i = 0; i < records.Count; i++) + { + var record = records[i]; + CheckDirectories(Path.GetDirectoryName(record.TargetPath)!); + VerifyTarget(record.TargetPath, record.PreStateSha256); + using (var output = new FileStream(record.TemporaryPath, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None)) + { + var source = inputs[InputIndex(records, i)]; + source.Position = 0; + source.CopyTo(output); + output.Flush(true); + Verify(output, record.PayloadSha256); + } + // This is a conflict check, not an atomic compare-and-swap. + VerifyTarget(record.TargetPath, record.PreStateSha256); + if (record.PreStateSha256 == null) + File.Move(record.TemporaryPath, record.TargetPath); + else + File.Replace(record.TemporaryPath, record.TargetPath, null); + using (var result = OpenRegular(record.TargetPath, false)) Verify(result, record.PayloadSha256); + afterWrite?.Invoke(i); + } + return intentPath; + } + finally + { + foreach (var input in inputs) input.Dispose(); + } + } + + private static int InputIndex(List records, int index) + { + int result = 0; + for (int i = 0; i < index; i++) result += records[i].PreStateSha256 == null ? 1 : 2; + return result; + } + + private static void VerifyTarget(string path, string? hash) + { + if (hash == null) + { + // GetAttributes detects directories and dangling reparse points as conflicts too. + try { File.GetAttributes(path); } + catch (FileNotFoundException) { return; } + throw new IOException("Target already exists: " + path); + } + using (var stream = OpenRegular(path, false)) Verify(stream, hash); + } + + internal static FileStream OpenRegular(string path, bool writable) + { + var attributes = File.GetAttributes(path); + if ((attributes & (FileAttributes.Directory | FileAttributes.ReparsePoint | FileAttributes.Device | + FileAttributes.Encrypted | FileAttributes.Offline | + FileAttributes.SparseFile | FileAttributes.ReadOnly)) != 0) + throw new InvalidDataException("Unsupported file: " + path); + var stream = new FileStream(path, FileMode.Open, writable ? FileAccess.ReadWrite : FileAccess.Read, FileShare.Read); + try + { + if (!GetFileInformationByHandle(stream.SafeFileHandle, out var info) || + info.NumberOfLinks != 1 || (info.FileAttributes & 0x400) != 0) + throw new IOException("Cannot verify regular unlinked file: " + path); + CheckStreams(path); + return stream; + } + catch { stream.Dispose(); throw; } + } + + private static void CheckStreams(string path) + { + IntPtr find = FindFirstStreamW(path, 0, out var data, 0); + if (find == new IntPtr(-1)) throw new IOException("Cannot enumerate file streams: " + path); + try + { + if (!string.Equals(data.Name, "::$DATA", StringComparison.OrdinalIgnoreCase)) + throw new InvalidDataException("Unsupported file stream: " + path); + if (FindNextStreamW(find, out data)) + throw new InvalidDataException("Alternate streams are unsupported: " + path); + if (Marshal.GetLastWin32Error() != 38) + throw new IOException("Cannot enumerate file streams: " + path); + } + finally { FindClose(find); } + } + + private static void Verify(FileStream file, string expected) + { + file.Position = 0; + using (var sha = SHA256.Create()) + { + var actual = BitConverter.ToString(sha.ComputeHash(file)).Replace("-", ""); + if (!string.Equals(actual, expected, StringComparison.OrdinalIgnoreCase)) + throw new IOException("SHA-256 conflict: " + file.Name); + } + } + + private static void CheckHash(string value) + { + if (value == null || value.Length != 64) throw new InvalidDataException("Invalid SHA-256."); + foreach (char c in value) + if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'))) + throw new InvalidDataException("Invalid SHA-256."); + } + + internal static string Relative(string path) + { + if (string.IsNullOrEmpty(path) || Path.IsPathRooted(path) || path.IndexOf('/') >= 0) + throw new InvalidDataException("Invalid relative path."); + foreach (string segment in path.Split('\\')) CheckSegment(segment); + return path; + } + + internal static string Absolute(string path) + { + if (string.IsNullOrEmpty(path) || path.Length < 3 || !char.IsLetter(path[0]) || + path[1] != ':' || path[2] != '\\' || path.IndexOf('/') >= 0) + throw new InvalidDataException("A local absolute path is required."); + string trimmed = path.TrimEnd('\\'); + if (trimmed.Length == 2) trimmed += "\\"; + if (!string.Equals(Path.GetFullPath(trimmed), trimmed, StringComparison.OrdinalIgnoreCase)) + throw new InvalidDataException("Non-canonical path."); + var drive = new DriveInfo(trimmed.Substring(0, 3)); + if (drive.DriveType != DriveType.Fixed || + !string.Equals(drive.DriveFormat, "NTFS", StringComparison.OrdinalIgnoreCase)) + throw new InvalidDataException("Only local fixed NTFS volumes are supported."); + foreach (string segment in trimmed.Substring(3).Split('\\')) + if (segment.Length != 0) CheckSegment(segment); + return trimmed; + } + + private static void CheckSegment(string segment) + { + if (segment.Length == 0 || segment == "." || segment == ".." || + segment.EndsWith(".", StringComparison.Ordinal) || segment.EndsWith(" ", StringComparison.Ordinal) || + segment.IndexOf('~') >= 0) + throw new InvalidDataException("Invalid path component."); + foreach (char c in segment) + if (c < 32 || "<>:\"|?*".IndexOf(c) >= 0) throw new InvalidDataException("Invalid path component."); + string stem = segment.Split('.')[0].TrimEnd(' ').ToUpperInvariant(); + if (stem == "CON" || stem == "PRN" || stem == "AUX" || stem == "NUL" || + stem == "CONIN$" || stem == "CONOUT$" || + (stem.Length == 4 && (stem.StartsWith("COM", StringComparison.Ordinal) || stem.StartsWith("LPT", StringComparison.Ordinal)) && + ("123456789¹²³".IndexOf(stem[3]) >= 0))) + throw new InvalidDataException("Reserved path component."); + } + + internal static bool Overlaps(string a, string b) + { + return string.Equals(a, b, StringComparison.OrdinalIgnoreCase) || + a.StartsWith(b.TrimEnd('\\') + "\\", StringComparison.OrdinalIgnoreCase) || + b.StartsWith(a.TrimEnd('\\') + "\\", StringComparison.OrdinalIgnoreCase); + } + + internal static void CheckDirectories(string path) + { + string? current = path; + while (current != null) + { + var attributes = File.GetAttributes(current); + if ((attributes & FileAttributes.Directory) == 0 || + (attributes & (FileAttributes.ReparsePoint | FileAttributes.Device)) != 0) + throw new InvalidDataException("Unsafe directory: " + current); + current = Path.GetDirectoryName(current); + } + } + + [DllImport("kernel32.dll", SetLastError = true)] + private static extern bool GetFileInformationByHandle(SafeFileHandle file, out FileInformation information); + + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + private static extern IntPtr FindFirstStreamW(string name, int level, out StreamData data, int flags); + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + private static extern bool FindNextStreamW(IntPtr find, out StreamData data); + [DllImport("kernel32.dll")] + private static extern bool FindClose(IntPtr find); + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + private struct StreamData + { + public long Size; + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 296)] + public string Name; + } + + [StructLayout(LayoutKind.Sequential)] + private struct FileInformation + { + public uint FileAttributes; + public System.Runtime.InteropServices.ComTypes.FILETIME CreationTime, LastAccessTime, LastWriteTime; + public uint VolumeSerialNumber, FileSizeHigh, FileSizeLow, NumberOfLinks, FileIndexHigh, FileIndexLow; + } + + internal sealed class Intent + { + public int Version { get; set; } + public string TargetRoot { get; set; } = ""; + public string StateDirectory { get; set; } = ""; + public string[] ProtectedPaths { get; set; } = Array.Empty(); + public IntentEntry[] Entries { get; set; } = Array.Empty(); + } + + internal sealed class IntentEntry + { + [JsonPropertyName("path")] + public string RelativePath { get; set; } = ""; + public string TargetPath { get; set; } = ""; + public string StagedPath { get; set; } = ""; + [JsonPropertyName("updatedSha256")] + public string PayloadSha256 { get; set; } = ""; + public string? SnapshotPath { get; set; } + [JsonPropertyName("originalSha256")] + public string? PreStateSha256 { get; set; } + public string TemporaryPath { get; set; } = ""; + } + } + + [JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)] + [JsonSerializable(typeof(ControlledFullZipApply.Intent))] + internal partial class ControlledFullZipIntentJsonContext : JsonSerializerContext + { + } +} diff --git a/src/GeneralUpdate.Core/Compress/ControlledFullZipPrepare.cs b/src/GeneralUpdate.Core/Compress/ControlledFullZipPrepare.cs new file mode 100644 index 00000000..9cc21d41 --- /dev/null +++ b/src/GeneralUpdate.Core/Compress/ControlledFullZipPrepare.cs @@ -0,0 +1,97 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Security.Cryptography; + +namespace GeneralUpdate.Core.Compress +{ + // The caller must hold externally enforced exclusive access and protect all roots. + // Preparing a plan does not authenticate a controller or authorize installation writes. + internal static class ControlledFullZipPrepare + { + internal static ControlledFullZipPlan Prepare(StagedZip staged, string targetRoot, + string stateDirectory, string backupRoot, IEnumerable protectedPaths) + { + if (staged == null) throw new ArgumentNullException(nameof(staged)); + if (protectedPaths == null) throw new ArgumentNullException(nameof(protectedPaths)); + if (Path.DirectorySeparatorChar != '\\') throw new PlatformNotSupportedException("Windows only."); + string target = ControlledFullZipApply.Absolute(targetRoot); + string state = ControlledFullZipApply.Absolute(stateDirectory); + string backup = ControlledFullZipApply.Absolute(backupRoot); + string stage = ControlledFullZipApply.Absolute(staged.DirectoryPath); + var roots = new[] { target, state, backup, stage }; + for (int i = 0; i < roots.Length; i++) + { + ControlledFullZipApply.CheckDirectories(roots[i]); + for (int j = 0; j < i; j++) + if (ControlledFullZipApply.Overlaps(roots[i], roots[j])) + throw new InvalidDataException("Controlled roots overlap."); + } + if (Directory.GetFileSystemEntries(backup).Length != 0) + throw new IOException("Backup directory must be empty."); + + var protectedNames = new List(); + foreach (string value in protectedPaths) + protectedNames.Add(ControlledFullZipApply.Relative(value)); + var names = new List(); + var originals = new List(); + try + { + foreach (var entry in staged.Entries) + { + string relative = ControlledFullZipApply.Relative(entry.RelativePath.Replace('/', '\\')); + foreach (string name in names) + if (ControlledFullZipApply.Overlaps(name, relative)) + throw new InvalidDataException("Conflicting target paths."); + foreach (string name in protectedNames) + if (ControlledFullZipApply.Overlaps(name, relative)) + throw new InvalidDataException("Protected target path."); + if (ControlledFullZipApply.Overlaps(".backups", relative)) + throw new InvalidDataException("Protected target path."); + string stagedPath = ControlledFullZipApply.Absolute(entry.StagedPath); + if (!stagedPath.StartsWith(stage.TrimEnd('\\') + "\\", StringComparison.OrdinalIgnoreCase)) + throw new InvalidDataException("Staged file is outside the stage directory."); + ControlledFullZipApply.CheckDirectories(Path.GetDirectoryName(stagedPath)!); + using (ControlledFullZipApply.OpenRegular(stagedPath, false)) { } + string destination = Path.Combine(target, relative); + ControlledFullZipApply.CheckDirectories(Path.GetDirectoryName(destination)!); + FileStream? original; + try { original = ControlledFullZipApply.OpenRegular(destination, false); } + catch (FileNotFoundException) { original = null; } + originals.Add(original); + names.Add(relative); + } + if (names.Count == 0) throw new InvalidDataException("Empty plan."); + + var entries = new List(); + for (int i = 0; i < names.Count; i++) + { + string? snapshot = null; + string? hash = null; + if (originals[i] != null) + { + snapshot = Path.Combine(backup, names[i]); + string parent = Path.GetDirectoryName(snapshot)!; + Directory.CreateDirectory(parent); + ControlledFullZipApply.CheckDirectories(parent); + using (var output = new FileStream(snapshot, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None)) + { + originals[i]!.CopyTo(output); + output.Flush(true); + output.Position = 0; + using (var sha = SHA256.Create()) + hash = BitConverter.ToString(sha.ComputeHash(output)).Replace("-", "").ToLowerInvariant(); + } + } + entries.Add(new ControlledFullZipEntry(names[i], staged.Entries[i].StagedPath, + staged.Entries[i].Sha256, snapshot, hash)); + } + return new ControlledFullZipPlan(target, state, entries, protectedNames); + } + finally + { + foreach (var stream in originals) stream?.Dispose(); + } + } + } +} diff --git a/src/GeneralUpdate.Core/Compress/FullZipStager.cs b/src/GeneralUpdate.Core/Compress/FullZipStager.cs new file mode 100644 index 00000000..62a6af91 --- /dev/null +++ b/src/GeneralUpdate.Core/Compress/FullZipStager.cs @@ -0,0 +1,427 @@ +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.IO; +using System.IO.Compression; +using System.Runtime.InteropServices; +using System.Security.Cryptography; + +namespace GeneralUpdate.Core.Compress +{ + /// + /// Preflights and stages a complete ZIP without writing to its eventual destination. + /// The caller must supply a trusted, access-controlled staging parent and keep it + /// protected from concurrent modification until the returned result is disposed. + /// ZIP64 and multi-volume archives are not supported. On netstandard2.0, the + /// runtime must expose ZipArchiveEntry.ExternalAttributes or staging fails closed. + /// + internal static class FullZipStager + { + internal static StagedZip Stage(string zipPath, string stagingParent, string expectedSha256, + int maxEntries, long maxFileBytes, long maxTotalBytes) + { + if (string.IsNullOrWhiteSpace(zipPath)) throw new ArgumentException("ZIP path is required.", nameof(zipPath)); + if (string.IsNullOrWhiteSpace(stagingParent)) throw new ArgumentException("Staging parent is required.", nameof(stagingParent)); + if (maxEntries <= 0) throw new ArgumentOutOfRangeException(nameof(maxEntries)); + if (maxFileBytes < 0) throw new ArgumentOutOfRangeException(nameof(maxFileBytes)); + if (maxTotalBytes < 0) throw new ArgumentOutOfRangeException(nameof(maxTotalBytes)); + if (!IsSha256(expectedSha256)) throw new ArgumentException("A SHA-256 hex digest is required.", nameof(expectedSha256)); + + using (var zip = new FileStream(zipPath, FileMode.Open, FileAccess.Read, FileShare.Read)) + using (var sha = SHA256.Create()) + { + var actual = ToHex(sha.ComputeHash(zip)); + if (!string.Equals(actual, expectedSha256, StringComparison.OrdinalIgnoreCase)) + throw new InvalidDataException("ZIP SHA-256 mismatch."); + zip.Position = 0; + using (var archive = new ZipArchive(zip, ZipArchiveMode.Read, true)) + { + if (archive.Entries.Count > maxEntries) throw new InvalidDataException("ZIP entry limit exceeded."); + var records = ReadRecords(zip, archive); + var paths = new Dictionary(StringComparer.OrdinalIgnoreCase); + long declaredTotal = 0; + for (int i = 0; i < archive.Entries.Count; i++) + { + var entry = archive.Entries[i]; + bool directory = ValidateEntry(entry, paths); + if (entry.Length > maxFileBytes || entry.Length > maxTotalBytes - declaredTotal) + throw new InvalidDataException("ZIP expanded size limit exceeded."); + if (directory && (entry.Length != 0 || records[i].Crc != 0)) + throw new InvalidDataException("Directory has content."); + declaredTotal += entry.Length; + } + + string stageDirectory = CreatePrivateDirectory(stagingParent); + var createdFiles = new List(); + try + { + var staged = new List(); + long total = 0; + for (int i = 0; i < archive.Entries.Count; i++) + { + var entry = archive.Entries[i]; + if (entry.FullName.EndsWith("/", StringComparison.Ordinal)) continue; + string stagedPath = Path.Combine(stageDirectory, Guid.NewGuid().ToString("N")); + using (var output = new FileStream(stagedPath, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None)) + { + createdFiles.Add(stagedPath); + long size = 0; + uint crc = 0xffffffff; + zip.Position = records[i].DataOffset; + using (var bounded = new BoundedReadStream(zip, records[i].CompressedSize)) + using (var input = records[i].Method == 8 + ? (Stream)new DeflateStream(bounded, CompressionMode.Decompress, true) + : bounded) + { + var buffer = new byte[81920]; + int read; + while ((read = input.Read(buffer, 0, buffer.Length)) != 0) + { + if (read > maxFileBytes - size || read > maxTotalBytes - total || read > entry.Length - size) + throw new InvalidDataException("ZIP expanded size limit exceeded."); + output.Write(buffer, 0, read); + for (int j = 0; j < read; j++) + crc = CrcTable[(crc ^ buffer[j]) & 0xff] ^ (crc >> 8); + size += read; + total += read; + } + } + if (size != entry.Length || (crc ^ 0xffffffff) != records[i].Crc) + throw new InvalidDataException("ZIP entry length or checksum mismatch."); + output.Flush(); + output.Position = 0; + staged.Add(new StagedZipEntry(entry.FullName, stagedPath, ToHex(sha.ComputeHash(output)))); + } + } + return new StagedZip(stageDirectory, staged, createdFiles); + } + catch (Exception error) + { + try { Cleanup(stageDirectory, createdFiles); } + catch (Exception cleanupError) { throw new AggregateException(error, cleanupError); } + throw; + } + } + } + } + + private enum PathKind { ImplicitDirectory, Directory, File } + + private static readonly uint[] CrcTable = CreateCrcTable(); + + private static uint[] CreateCrcTable() + { + var table = new uint[256]; + for (uint i = 0; i < table.Length; i++) + { + uint value = i; + for (int bit = 0; bit < 8; bit++) + value = (value & 1) != 0 ? 0xedb88320 ^ (value >> 1) : value >> 1; + table[i] = value; + } + return table; + } + + // ZipArchive may stop at a forged uncompressed length without verifying CRC. + // Use the central directory to bound the compressed input instead. + // ZIP64 and multi-volume archives are deliberately rejected. + private static List ReadRecords(Stream zip, ZipArchive archive) + { + int tailLength = (int)Math.Min(zip.Length, 65557); + var tail = new byte[tailLength]; + zip.Position = zip.Length - tailLength; + using (var reader = new BinaryReader(zip, System.Text.Encoding.UTF8, true)) + { + int read = 0; + while (read < tail.Length) + { + int count = zip.Read(tail, read, tail.Length - read); + if (count == 0) throw new InvalidDataException("Truncated ZIP."); + read += count; + } + int end = -1; + for (int i = tail.Length - 22; i >= 0; i--) + if (BitConverter.ToUInt32(tail, i) == 0x06054b50 && + i + 22 + BitConverter.ToUInt16(tail, i + 20) == tail.Length) + { end = i; break; } + if (end < 0) throw new InvalidDataException("ZIP end record not found."); + ushort disk = BitConverter.ToUInt16(tail, end + 4); + ushort centralDisk = BitConverter.ToUInt16(tail, end + 6); + ushort diskEntries = BitConverter.ToUInt16(tail, end + 8); + ushort entries = BitConverter.ToUInt16(tail, end + 10); + uint centralSize = BitConverter.ToUInt32(tail, end + 12); + uint centralOffset = BitConverter.ToUInt32(tail, end + 16); + long endOffset = zip.Length - tailLength + end; + if (disk != 0 || centralDisk != 0 || diskEntries != entries || entries == 0xffff || + centralSize == uint.MaxValue || centralOffset == uint.MaxValue || + entries != archive.Entries.Count || (long)centralOffset + centralSize != endOffset) + throw new InvalidDataException("Unsupported or invalid ZIP directory."); + zip.Position = centralOffset; + var records = new List(entries); + for (int i = 0; i < entries; i++) + { + if (zip.Position > endOffset - 46 || reader.ReadUInt32() != 0x02014b50) + throw new InvalidDataException("Invalid ZIP directory entry."); + zip.Position += 4; + ushort flags = reader.ReadUInt16(); + ushort method = reader.ReadUInt16(); + zip.Position += 4; + uint crc = reader.ReadUInt32(); + uint compressed = reader.ReadUInt32(); + uint expanded = reader.ReadUInt32(); + ushort nameLength = reader.ReadUInt16(); + ushort extraLength = reader.ReadUInt16(); + ushort commentLength = reader.ReadUInt16(); + ushort entryDisk = reader.ReadUInt16(); + zip.Position += 6; + uint localOffset = reader.ReadUInt32(); + long next = zip.Position + nameLength + extraLength + commentLength; + if (next > endOffset || entryDisk != 0 || localOffset == uint.MaxValue || + compressed == uint.MaxValue || expanded == uint.MaxValue || + (flags & 0x2061) != 0 || (method != 0 && method != 8) || + compressed != archive.Entries[i].CompressedLength || expanded != archive.Entries[i].Length) + throw new InvalidDataException("Unsupported or invalid ZIP entry."); + byte[] name = reader.ReadBytes(nameLength); + if (name.Length != nameLength) throw new InvalidDataException("Truncated ZIP entry name."); + records.Add(new ZipRecord(localOffset, compressed, expanded, crc, flags, method, name)); + zip.Position = next; + } + if (zip.Position != endOffset) throw new InvalidDataException("Invalid ZIP directory size."); + foreach (var record in records) + { + if ((long)record.LocalOffset + 30 > centralOffset) + throw new InvalidDataException("Invalid ZIP local header."); + zip.Position = record.LocalOffset; + if (reader.ReadUInt32() != 0x04034b50) throw new InvalidDataException("Invalid ZIP local header."); + zip.Position += 2; + ushort flags = reader.ReadUInt16(); + ushort method = reader.ReadUInt16(); + zip.Position += 4; + uint crc = reader.ReadUInt32(); + uint compressed = reader.ReadUInt32(); + uint expanded = reader.ReadUInt32(); + ushort nameLength = reader.ReadUInt16(); + ushort extraLength = reader.ReadUInt16(); + long dataOffset = zip.Position + nameLength + extraLength; + if (flags != record.Flags || method != record.Method || + ((flags & 8) == 0 && (crc != record.Crc || compressed != record.CompressedSize || expanded != record.ExpandedSize)) || + nameLength != record.Name.Length || dataOffset + record.CompressedSize > centralOffset) + throw new InvalidDataException("Inconsistent ZIP local header."); + byte[] name = reader.ReadBytes(nameLength); + if (name.Length != record.Name.Length) throw new InvalidDataException("Truncated ZIP entry name."); + for (int i = 0; i < name.Length; i++) + if (name[i] != record.Name[i]) throw new InvalidDataException("Inconsistent ZIP entry name."); + record.DataOffset = dataOffset; + } + return records; + } + } + + private sealed class ZipRecord + { + internal ZipRecord(uint localOffset, uint compressedSize, uint expandedSize, uint crc, + ushort flags, ushort method, byte[] name) + { + LocalOffset = localOffset; + CompressedSize = compressedSize; + ExpandedSize = expandedSize; + Crc = crc; + Flags = flags; + Method = method; + Name = name; + } + internal uint LocalOffset { get; } + internal uint CompressedSize { get; } + internal uint ExpandedSize { get; } + internal uint Crc { get; } + internal ushort Flags { get; } + internal ushort Method { get; } + internal byte[] Name { get; } + internal long DataOffset { get; set; } + } + + private sealed class BoundedReadStream : Stream + { + private readonly Stream _source; + private long _remaining; + internal BoundedReadStream(Stream source, long length) { _source = source; _remaining = length; } + public override bool CanRead => true; + public override bool CanSeek => false; + public override bool CanWrite => false; + public override long Length => throw new NotSupportedException(); + public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } + public override int Read(byte[] buffer, int offset, int count) + { + if (_remaining == 0) return 0; + int read = _source.Read(buffer, offset, (int)Math.Min(count, _remaining)); + if (read == 0 && count != 0) throw new InvalidDataException("Truncated ZIP entry."); + _remaining -= read; + return read; + } + public override void Flush() { } + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + public override void SetLength(long value) => throw new NotSupportedException(); + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + } + + private static bool ValidateEntry(ZipArchiveEntry entry, Dictionary paths) + { + string name = entry.FullName; + bool directory = name.EndsWith("/", StringComparison.Ordinal); + string path = directory ? name.Substring(0, name.Length - 1) : name; + if (path.Length == 0 || path.IndexOf('\\') >= 0) throw new InvalidDataException("Invalid ZIP path."); + string[] parts = path.Split('/'); + string prefix = ""; + for (int i = 0; i < parts.Length; i++) + { + string part = parts[i]; + ValidatePart(part); + prefix = i == 0 ? part : prefix + "/" + part; + bool last = i == parts.Length - 1; + if (paths.TryGetValue(prefix, out var existing)) + { + if (!last) + { + if (existing == PathKind.File) throw new InvalidDataException("ZIP file/directory conflict."); + } + else if (directory && existing == PathKind.ImplicitDirectory) + paths[prefix] = PathKind.Directory; + else + throw new InvalidDataException("Duplicate or conflicting ZIP path."); + } + else + paths.Add(prefix, last ? (directory ? PathKind.Directory : PathKind.File) : PathKind.ImplicitDirectory); + } + + int attributes = GetExternalAttributes(entry); + int unixType = (attributes >> 16) & 0xF000; + int upperAttributes = (int)((uint)attributes >> 16); + if ((attributes & 0x400) != 0 || (attributes & 0x40) != 0 || + (upperAttributes & 0x400) != 0 || (unixType == 0 && (upperAttributes & 0x40) != 0) || + (unixType != 0 && unixType != 0x8000 && unixType != 0x4000) || + (unixType == 0x4000 && !directory) || (unixType == 0x8000 && directory) || + ((attributes & 0x10) != 0 && !directory)) + throw new InvalidDataException("Unsupported ZIP entry type."); + return directory; + } + + private static int GetExternalAttributes(ZipArchiveEntry entry) + { +#if NETSTANDARD2_0 + // ExternalAttributes is not in the netstandard2.0 reference contract. + // Never assume an entry is safe on runtimes that cannot expose it. + var property = typeof(ZipArchiveEntry).GetProperty("ExternalAttributes"); + if (property == null || property.PropertyType != typeof(int)) + throw new PlatformNotSupportedException("ZIP external attributes are unavailable."); + return (int)property.GetValue(entry)!; +#else + return entry.ExternalAttributes; +#endif + } + + private static void ValidatePart(string part) + { + if (part.Length == 0 || part == "." || part == ".." || + part[part.Length - 1] == '.' || part[part.Length - 1] == ' ' || + string.Equals(part, ".backups", StringComparison.OrdinalIgnoreCase)) + throw new InvalidDataException("Invalid ZIP path component."); + foreach (char c in part) + if (char.IsControl(c) || c == '<' || c == '>' || c == ':' || c == '"' || + c == '|' || c == '?' || c == '*') + throw new InvalidDataException("Invalid ZIP path character."); + + string stem = part.Split('.')[0].TrimEnd(' '); + if (string.Equals(stem, "CON", StringComparison.OrdinalIgnoreCase) || + string.Equals(stem, "PRN", StringComparison.OrdinalIgnoreCase) || + string.Equals(stem, "AUX", StringComparison.OrdinalIgnoreCase) || + string.Equals(stem, "NUL", StringComparison.OrdinalIgnoreCase) || + string.Equals(stem, "CONIN$", StringComparison.OrdinalIgnoreCase) || + string.Equals(stem, "CONOUT$", StringComparison.OrdinalIgnoreCase) || + (stem.Length == 4 && + (stem.StartsWith("COM", StringComparison.OrdinalIgnoreCase) || stem.StartsWith("LPT", StringComparison.OrdinalIgnoreCase)) && + ("123456789\u00b9\u00b2\u00b3".IndexOf(stem[3]) >= 0))) + throw new InvalidDataException("Reserved Windows name."); + } + + private static bool IsSha256(string value) + { + if (value == null || value.Length != 64) return false; + foreach (char c in value) + if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'))) return false; + return true; + } + + private static string ToHex(byte[] bytes) => BitConverter.ToString(bytes).Replace("-", "").ToLowerInvariant(); + + private static string CreatePrivateDirectory(string parent) + { + if (!Directory.Exists(parent)) throw new DirectoryNotFoundException("Staging parent does not exist."); + for (int i = 0; i < 10; i++) + { + string path = Path.Combine(parent, "zip-stage-" + Guid.NewGuid().ToString("N")); + bool created; + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + created = CreateDirectoryWindows(path, IntPtr.Zero); + else + created = MkdirUnix(path, 448) == 0; // 0700 + if (created) return path; + int error = Marshal.GetLastWin32Error(); + if (error != (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? 183 : 17)) + throw new IOException("Unable to create staging directory.", new Win32Exception(error)); + } + throw new IOException("Unable to allocate a unique staging directory."); + } + + [DllImport("kernel32.dll", EntryPoint = "CreateDirectoryW", CharSet = CharSet.Unicode, SetLastError = true)] + private static extern bool CreateDirectoryWindows(string path, IntPtr securityAttributes); + + [DllImport("libc", EntryPoint = "mkdir", SetLastError = true)] + private static extern int MkdirUnix(string path, int mode); + + internal static void Cleanup(string directory, List files) + { + var errors = new List(); + foreach (string file in files) + try { File.Delete(file); } catch (Exception error) { errors.Add(error); } + try { Directory.Delete(directory, false); } + catch (DirectoryNotFoundException) { } + catch (Exception error) { errors.Add(error); } + if (errors.Count != 0) throw new AggregateException("Unable to clean up ZIP staging.", errors); + } + } + + internal sealed class StagedZipEntry + { + internal StagedZipEntry(string relativePath, string stagedPath, string sha256) + { + RelativePath = relativePath; + StagedPath = stagedPath; + Sha256 = sha256; + } + + internal string RelativePath { get; } + internal string StagedPath { get; } + internal string Sha256 { get; } + } + + internal sealed class StagedZip : IDisposable + { + private readonly List _files; + private bool _retainForRecovery; + internal StagedZip(string directory, List entries, List files) + { + DirectoryPath = directory; + Entries = new ReadOnlyCollection(entries); + _files = files; + } + + internal string DirectoryPath { get; } + internal IReadOnlyList Entries { get; } + internal void RetainForRecovery() => _retainForRecovery = true; + public void Dispose() + { + if (!_retainForRecovery) FullZipStager.Cleanup(DirectoryPath, _files); + } + } +} diff --git a/src/GeneralUpdate.Core/Compress/ZipCompressionStrategy.cs b/src/GeneralUpdate.Core/Compress/ZipCompressionStrategy.cs index 08d2772c..2ee1c4a4 100644 --- a/src/GeneralUpdate.Core/Compress/ZipCompressionStrategy.cs +++ b/src/GeneralUpdate.Core/Compress/ZipCompressionStrategy.cs @@ -139,7 +139,10 @@ public void Decompress(string zipFilePath, string unZipDir, Encoding encoding) var extractionRoot = Path.GetFullPath(unZipDir); - using var zipToOpen = new FileStream(zipFilePath, FileMode.Open, FileAccess.ReadWrite, FileShare.Read); + // Read-only access: ReadWrite made read-only files on disk fail to open (the + // archive is only ever read here), and required unnecessary write permissions + // on the source package. + using var zipToOpen = new FileStream(zipFilePath, FileMode.Open, FileAccess.Read, FileShare.Read); using var archive = new ZipArchive(zipToOpen, ZipArchiveMode.Read, false, encoding); for (int i = 0; i < archive.Entries.Count; i++) { @@ -199,8 +202,10 @@ private Dictionary GetAllDirList(string strBaseDir var directoryInfo = new DirectoryInfo(strBaseDir); var directories = directoryInfo.GetDirectories(); var fileInfos = directoryInfo.GetFiles(); + // Zip entry names always use "/" (PKZIP spec); a platform-specific separator here + // produced malformed entries ("a\\b.txt") when compressing on Linux/macOS. if (includeBaseDirectory) - namePrefix += directoryInfo.Name + "\\"; + namePrefix += directoryInfo.Name + "/"; foreach (var directory in directories) resultDictionary = resultDictionary.Concat(GetAllDirList(directory.FullName, true, namePrefix)) .ToDictionary(k => k.Key, k => k.Value); diff --git a/src/GeneralUpdate.Core/Configuration/BowlOptions.cs b/src/GeneralUpdate.Core/Configuration/BowlOptions.cs index 06dcb732..87d9d983 100644 --- a/src/GeneralUpdate.Core/Configuration/BowlOptions.cs +++ b/src/GeneralUpdate.Core/Configuration/BowlOptions.cs @@ -5,6 +5,8 @@ public sealed class BowlOptions { /// False preserves operation without a Bowl deployment; true requires a successful readiness handshake. public bool Enabled { get; set; } + /// Collect crash evidence for the supervised application. Defaults to false. + public bool CrashCollectionEnabled { get; set; } /// Absolute path to the actual host executable, outside every update/backup tree; not a launcher or library. public string ExecutablePath { get; set; } = string.Empty; /// Maximum seconds to wait for a matching, live host before aborting without applying application files. @@ -19,4 +21,6 @@ public sealed class BowlOptions public bool AutoRollback { get; set; } /// Name of a host-provisioned environment variable; never the credential itself. public string? CredentialEnvironmentVariable { get; set; } + /// Name of the environment variable containing the GeneralSpace app key, available to Host and retry processes. + public string? AppKeyEnvironmentVariable { get; set; } } diff --git a/src/GeneralUpdate.Core/Configuration/InstallationIdentity.cs b/src/GeneralUpdate.Core/Configuration/InstallationIdentity.cs new file mode 100644 index 00000000..d6cbbc71 --- /dev/null +++ b/src/GeneralUpdate.Core/Configuration/InstallationIdentity.cs @@ -0,0 +1,53 @@ +using System; +using System.IO; +using System.Security.Cryptography; +using System.Text; +using GeneralUpdate.Core.Download.Reporting; + +namespace GeneralUpdate.Core.Configuration; + +/// Stable random identity stored outside the installation and backup trees. +internal static class InstallationIdentity +{ + internal static string GetOrCreate(UpdateContext config) + { + var root = Path.GetFullPath(config.DiagnosticsDirectory ?? Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "GeneralUpdate", "state")); + UpdateAttempt.ValidateExternalPath(root, config); + var install = Path.GetFullPath(config.InstallPath).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); + if (Path.DirectorySeparatorChar == '\\') install = install.ToUpperInvariant(); + using var sha = SHA256.Create(); + var hash = BitConverter.ToString(sha.ComputeHash(Encoding.UTF8.GetBytes(install))).Replace("-", "").ToLowerInvariant(); + var directory = Path.Combine(root, "installations"); + UpdateAttempt.ValidateExternalPath(directory, config); + Directory.CreateDirectory(directory); + var path = Path.Combine(directory, hash + ".id"); + if (File.Exists(path) && (File.GetAttributes(path) & FileAttributes.ReparsePoint) != 0) + throw new InvalidDataException("The installation identity cannot be a symbolic link."); + if (!File.Exists(path)) + { + var temp = Path.Combine(directory, Guid.NewGuid().ToString("N") + ".tmp"); + try + { + var bytes = Encoding.UTF8.GetBytes(Guid.NewGuid().ToString("D")); + using (var stream = new FileStream(temp, FileMode.CreateNew, FileAccess.Write, FileShare.None)) + { + stream.Write(bytes, 0, bytes.Length); + stream.Flush(true); + } + try { File.Move(temp, path); } + catch (IOException) when (File.Exists(path)) { } + } + finally + { + if (File.Exists(temp)) File.Delete(temp); + } + } + if ((File.GetAttributes(path) & FileAttributes.ReparsePoint) != 0) + throw new InvalidDataException("The installation identity cannot be a symbolic link."); + var value = File.ReadAllText(path); + if (!Guid.TryParseExact(value, "D", out var id) || id == Guid.Empty) + throw new InvalidDataException("The installation identity is invalid."); + return id.ToString("D"); + } +} diff --git a/src/GeneralUpdate.Core/Configuration/ManifestInfo.cs b/src/GeneralUpdate.Core/Configuration/ManifestInfo.cs index 8ecc77fd..24354564 100644 --- a/src/GeneralUpdate.Core/Configuration/ManifestInfo.cs +++ b/src/GeneralUpdate.Core/Configuration/ManifestInfo.cs @@ -105,7 +105,24 @@ public void Save(string? path = null) { var filePath = path ?? Path.Combine(AppDomain.CurrentDomain.BaseDirectory, FileName); var json = JsonSerializer.Serialize(this, HttpParameterJsonContext.Default.ManifestInfo); - File.WriteAllText(filePath, json); + // Atomic replace: the manifest drives the next update cycle's version decision, + // so neither a torn half-written file nor a missing one (crash between delete and + // move) may ever be observable. File.Replace swaps in one OS operation when the + // destination exists; File.Move covers initial creation (same pattern as + // UpdateAttempt.WriteAtomic — File.Move(src, dst, overwrite) is unavailable on + // netstandard2.0). + var tempPath = filePath + ".tmp-" + Guid.NewGuid().ToString("N"); + try + { + File.WriteAllText(tempPath, json); + if (File.Exists(filePath)) File.Replace(tempPath, filePath, null); + else File.Move(tempPath, filePath); + } + catch + { + try { File.Delete(tempPath); } catch { /* best-effort cleanup */ } + throw; + } } /// diff --git a/src/GeneralUpdate.Core/Configuration/Option.cs b/src/GeneralUpdate.Core/Configuration/Option.cs index 9597b796..efd35b23 100644 --- a/src/GeneralUpdate.Core/Configuration/Option.cs +++ b/src/GeneralUpdate.Core/Configuration/Option.cs @@ -160,6 +160,13 @@ public override bool Equals(object? obj) /// public static Option LaunchBowl { get; } = ValueOf("LAUNCHBOWL", false); + /// + /// Enables the external Bowl.Host update monitor and crash collection. The host + /// defaults to C:\Bowl\Bowl.Host.exe; this is independent of application relaunch. + /// Existing Monitoring settings can override the host path and timeouts. + /// + public static Option BowlCrashCollectionEnabled { get; } = ValueOf("BOWLCRASHCOLLECTIONENABLED", false); + /// /// 诊断上报总开关。默认 false。开启后 Core 在主程序启动时后台扫描 /// fail 目录 outbox 补传崩溃采证,并在自检失败/回滚时实时上传诊断包。 @@ -168,8 +175,8 @@ public override bool Equals(object? obj) public static Option DiagnosticsUploadEnabled { get; } = ValueOf("DIAGNOSTICSUPLOADENABLED", false); /// - /// 诊断上报服务端地址。独立于状态上报地址(UpdateRequest.ReportUrl 只承载 - /// UpdateStatus 状态上报,二者互不影响),为空时视为未配置诊断通道。 + /// 诊断上报服务端地址。为空时从状态上报地址的 origin 推导 GeneralSpace 地址; + /// 两者都不可用时不启动诊断通道。 /// public static Option DiagnosticsReportUrl { get; } = ValueOf("DIAGNOSTICSREPORTURL", string.Empty); diff --git a/src/GeneralUpdate.Core/Diagnostics/DiagnosticsChannel.cs b/src/GeneralUpdate.Core/Diagnostics/DiagnosticsChannel.cs index e51acf0b..c3b30fa1 100644 --- a/src/GeneralUpdate.Core/Diagnostics/DiagnosticsChannel.cs +++ b/src/GeneralUpdate.Core/Diagnostics/DiagnosticsChannel.cs @@ -25,16 +25,24 @@ public sealed class DiagnosticsChannel /// Scanner delivering the Bowl crash-evidence outbox. public PendingDiagnosticsScanner Scanner { get; } + /// + /// Blacklist filter applied when packaging evidence. Exposed so real-time collectors + /// (rollback / self-check) pack under the same privacy gate as the outbox scanner. + /// + public IBlackMatcher? PrivacyFilter { get; } + /// Application install root (locates the fail/ outbox). /// Runtime options. Must be enabled and carry a URL — see . /// Optional blacklist filter applied when packaging evidence. - public DiagnosticsChannel(string installPath, DiagnosticsOptions options, IBlackMatcher? privacyFilter = null) + public DiagnosticsChannel(string installPath, DiagnosticsOptions options, IBlackMatcher? privacyFilter = null, + string? stateRoot = null, string? installationId = null) { if (string.IsNullOrWhiteSpace(installPath)) throw new ArgumentNullException(nameof(installPath)); Options = options ?? throw new ArgumentNullException(nameof(options)); + PrivacyFilter = privacyFilter; Uploader = new DiagnosticsUploader(options); - Scanner = new PendingDiagnosticsScanner(installPath, options, Uploader, privacyFilter); + Scanner = new PendingDiagnosticsScanner(installPath, options, Uploader, privacyFilter, stateRoot, installationId); } /// true when the channel has a usable endpoint. diff --git a/src/GeneralUpdate.Core/Diagnostics/DiagnosticsManifest.cs b/src/GeneralUpdate.Core/Diagnostics/DiagnosticsManifest.cs index 88667b55..4e7ef0db 100644 --- a/src/GeneralUpdate.Core/Diagnostics/DiagnosticsManifest.cs +++ b/src/GeneralUpdate.Core/Diagnostics/DiagnosticsManifest.cs @@ -12,6 +12,11 @@ namespace GeneralUpdate.Core.Diagnostics; /// One of . /// Version the diagnostics are about (failed target / rolled-back target). /// Free-form reason (first self-check failure, exception message...). +/// +/// Server update record this bundle belongs to (0 = none). Written to the upload so the +/// server can link the artifact back to the failing upgrade/push record. +/// +/// Server record type matching (1 = poll, 2 = push). /// Serialized SelfCheckReport, when available. /// Serialized RollbackResult, when available. public sealed record DiagnosticsCollectRequest( @@ -19,30 +24,66 @@ public sealed record DiagnosticsCollectRequest( string Kind, string? TargetVersion, string? Reason, + int RecordId = 0, + int RecordType = 0, string? SelfCheckReportJson = null, string? RollbackResultJson = null); /// -/// Metadata declared alongside an uploaded bundle. Sent with every upload so the server can -/// audit what the package contains without unpacking it (privacy/audit requirement). +/// Metadata declared alongside an uploaded bundle. It travels BOTH ways of the server +/// contract (GeneralSpace /Fault/UploadArtifact): as multipart form fields on the +/// wire — guid doubles as the server-side idempotency key — and as the +/// manifest.json entry inside the archive, so the server can audit what the +/// package contains without trusting the form (privacy/audit requirement). /// public sealed class DiagnosticsManifest { - /// Manifest contract version. + /// Manifest contract version. Aligned with the Bowl outbox disk contract (schema 2). [System.Text.Json.Serialization.JsonPropertyName("schema")] public int Schema { get; set; } = CurrentSchema; - /// Current manifest contract version. - public const int CurrentSchema = 1; + /// Current manifest contract version (matches ). + public const int CurrentSchema = OutboxManifest.SupportedSchema; + + /// + /// Canonical bundle id (GUID "D" form). Required — the server deduplicates uploads on it; + /// callers generate it once at collection time and reuse it across retries. + /// + [System.Text.Json.Serialization.JsonPropertyName("guid")] + public string Guid { get; set; } = string.Empty; /// One of . [System.Text.Json.Serialization.JsonPropertyName("kind")] public string Kind { get; set; } = DiagnosticsKinds.Manual; + /// Monitored process name (diagnostic metadata; crash outboxes carry Bowl's target). + [System.Text.Json.Serialization.JsonPropertyName("targetName")] + public string? TargetName { get; set; } + /// Version the diagnostics are about. [System.Text.Json.Serialization.JsonPropertyName("version")] public string? Version { get; set; } + /// Client identity used for verification (server attribute column); empty when unknown. + [System.Text.Json.Serialization.JsonPropertyName("appKey")] + public string? AppKey { get; set; } + + /// Product the diagnostics belong to (server attribution); empty when unknown. + [System.Text.Json.Serialization.JsonPropertyName("productId")] + public string? ProductId { get; set; } + + /// Target platform per the GeneralSpace convention (1 = Windows, 2 = Linux); null when unknown. + [System.Text.Json.Serialization.JsonPropertyName("platform")] + public int? Platform { get; set; } + + /// Server update record id this bundle belongs to; 0/absent = not linked to a record. + [System.Text.Json.Serialization.JsonPropertyName("recordId")] + public int? RecordId { get; set; } + + /// Server record type matching (1 = upgrade/poll, 2 = push). + [System.Text.Json.Serialization.JsonPropertyName("recordType")] + public int? RecordType { get; set; } + /// Free-form reason collected from the caller. [System.Text.Json.Serialization.JsonPropertyName("reason")] public string? Reason { get; set; } diff --git a/src/GeneralUpdate.Core/Diagnostics/DiagnosticsOptions.cs b/src/GeneralUpdate.Core/Diagnostics/DiagnosticsOptions.cs index 58001b3c..4b1619ca 100644 --- a/src/GeneralUpdate.Core/Diagnostics/DiagnosticsOptions.cs +++ b/src/GeneralUpdate.Core/Diagnostics/DiagnosticsOptions.cs @@ -4,13 +4,29 @@ namespace GeneralUpdate.Core.Diagnostics; /// Well-known values for and /// . /// +/// +/// The vocabulary is the server contract of GeneralSpace /Fault/UploadArtifact +/// (docs/自检与Bowl诊断联动服务端适配方案 §3.2): crash / update / selfcheck. +/// The server stores any non-empty kind verbatim (only crash opens a StartupFail +/// fault ticket), so stays a distinct, honest value instead of +/// masquerading as an update-failure diagnostic. +/// public static class DiagnosticsKinds { - /// Real-time bundle produced by after a rollback. - public const string Rollback = "rollback"; + /// + /// Real-time bundle produced by after a rollback. + /// Per the server adaptation design the rollback evidence is a self-check failure + /// diagnostic (kind=selfcheck + recordId), so it shares the self-check bucket. + /// + public const string Rollback = SelfCheck; + + /// + /// Real-time bundle produced after a failed self-check session (with or without rollback). + /// + public const string SelfCheck = "selfcheck"; - /// Real-time bundle produced after a failed self-check session (without rollback). - public const string SelfCheck = "self-check"; + /// Update-failure diagnostic (pipeline failure evidence); also the crash-outbox sibling bucket. + public const string Update = "update"; /// Crash evidence outbox written by the Bowl watchdog (schema 2 disk contract). public const string Crash = "crash"; @@ -59,6 +75,22 @@ public sealed class DiagnosticsOptions /// public int RetainDays { get; set; } = 14; - /// Upload attempts per outbox directory before it is marked giveup. Default 5. + /// Upload attempts before giveup; zero means unlimited retries. Default 5. public int MaxRetry { get; set; } = 5; + + // ---- Server attribution identity (GeneralSpace /Fault/UploadArtifact form fields) ---- + // Populated by the bootstrap from the verification configuration so every bundle — + // real-time and outbox — carries the same client identity without call-site plumbing. + + /// Client identity used for verification (AppSecretKey); empty when unknown. + public string? AppKey { get; set; } + + /// Product the diagnostics belong to; empty when unknown. + public string? ProductId { get; set; } + + /// Target platform per the GeneralSpace convention (1 = Windows, 2 = Linux); null when unknown. + public int? Platform { get; set; } + + /// Monitored / verified process name (manifest targetName); empty when unknown. + public string? TargetName { get; set; } } diff --git a/src/GeneralUpdate.Core/Diagnostics/DiagnosticsPackager.cs b/src/GeneralUpdate.Core/Diagnostics/DiagnosticsPackager.cs index 3e23e969..e3367840 100644 --- a/src/GeneralUpdate.Core/Diagnostics/DiagnosticsPackager.cs +++ b/src/GeneralUpdate.Core/Diagnostics/DiagnosticsPackager.cs @@ -3,7 +3,10 @@ using System.IO; using System.IO.Compression; using System.Linq; +using System.Text; +using System.Text.Json; using GeneralUpdate.Core.FileSystem; +using GeneralUpdate.Core.JsonContext; namespace GeneralUpdate.Core.Diagnostics; @@ -32,6 +35,7 @@ namespace GeneralUpdate.Core.Diagnostics; internal static class DiagnosticsPackager { private const string DumpExtension = ".dmp"; + private const string ManifestEntryName = "manifest.json"; private const long LogTailBytes = 64 * 1024; /// Packs a directory. Returns the archive path and the list of included file names. @@ -71,16 +75,73 @@ public static (string ZipPath, List Entries)? PackDirectory( return null; } + // Size-cap processing has settled: sync the in-archive schema-2 manifest.json with the + // entries ACTUALLY retained (after privacy filtering and dump stripping) so the server's + // audit list declares the real archive contents. + UpdateEmbeddedManifest(zipPath, sourceDirectory, included); + + if (new FileInfo(zipPath).Length > options.MaxSizeBytes) + { + File.Delete(zipPath); + GeneralTracer.Warn("DiagnosticsPackager: final bundle exceeds the size cap — not delivered."); + return null; + } + return (zipPath, included); } + /// + /// Rewrites the manifest.json entry inside a finished archive with the retained + /// entry list. Only schema-2 manifests (our own disk contract) are touched; an unknown + /// dialect is left as written. Best-effort: a failure here must not lose the bundle. + /// + private static void UpdateEmbeddedManifest(string zipPath, string sourceDirectory, List included) + { + try + { + var manifestPath = Path.Combine(sourceDirectory, ManifestEntryName); + if (!File.Exists(manifestPath)) return; + + OutboxManifest? manifest; + try + { + manifest = JsonSerializer.Deserialize( + File.ReadAllText(manifestPath), DiagnosticsJsonContext.Default.OutboxManifest); + } + catch + { + return; // Unknown manifest dialect — leave the embedded copy untouched. + } + if (manifest == null || manifest.Schema != OutboxManifest.SupportedSchema) return; + + manifest.Files = included; + using var archive = ZipFile.Open(zipPath, ZipArchiveMode.Update); + var entry = archive.GetEntry(ManifestEntryName); + if (entry == null) return; + entry.Delete(); + var updated = archive.CreateEntry(ManifestEntryName); + using (var writer = new StreamWriter(updated.Open(), new UTF8Encoding(false))) + { + writer.Write(JsonSerializer.Serialize(manifest, DiagnosticsJsonContext.Default.OutboxManifest)); + } + } + catch (Exception ex) + { + GeneralTracer.Warn($"DiagnosticsPackager: embedded manifest file list update failed: {ex.Message}"); + } + } + /// /// Packs a real-time bundle from in-memory text payloads plus the standard /// install-directory artifacts (manifest snapshot, trace-log tail) into a staging directory, - /// then archives it. + /// then archives it. A schema-2 manifest.json (same disk contract as the Bowl + /// outbox) is written into the archive so the server can identify the bundle and treat + /// it as parsed evidence — real-time bundles are first-class outbox citizens. /// + /// Canonical bundle id; the server deduplicates uploads on it. public static (string ZipPath, List Entries)? PackBundle( - DiagnosticsCollectRequest request, DiagnosticsOptions options, IBlackMatcher? privacyFilter = null) + DiagnosticsCollectRequest request, DiagnosticsOptions options, string bundleGuid, + IBlackMatcher? privacyFilter = null) { var stagingRoot = Path.Combine(Path.GetTempPath(), $"generalupdate-diagnostics-{Guid.NewGuid():N}"); try @@ -99,6 +160,8 @@ public static (string ZipPath, List Entries)? PackBundle( var logTail = ReadLogTail(request.InstallPath); WriteIfAny(Path.Combine(stagingRoot, "update-log-tail.txt"), logTail); + WriteIfAny(Path.Combine(stagingRoot, ManifestEntryName), BuildManifestJson(request, options, bundleGuid)); + return PackDirectory(stagingRoot, options, privacyFilter); } finally @@ -107,6 +170,26 @@ public static (string ZipPath, List Entries)? PackBundle( } } + /// + /// In-archive manifest (schema 2 disk contract): identity + kind + file list. Written + /// before packing so includes it in the audit list. + /// + private static string BuildManifestJson( + DiagnosticsCollectRequest request, DiagnosticsOptions options, string bundleGuid) + { + var manifest = new OutboxManifest + { + Schema = OutboxManifest.SupportedSchema, + Guid = bundleGuid, + Kind = request.Kind, + TargetName = options.TargetName, + Version = request.TargetVersion, + CreatedAtUtc = DateTime.UtcNow, + State = OutboxStates.Pending, + }; + return JsonSerializer.Serialize(manifest, DiagnosticsJsonContext.Default.OutboxManifest); + } + private static List WriteArchive( string zipPath, string sourceDirectory, List files, IBlackMatcher? privacyFilter, bool stripDumps) @@ -118,7 +201,12 @@ private static List WriteArchive( foreach (var file in files) { if (stripDumps && IsDump(file)) continue; - if (privacyFilter != null && privacyFilter.IsBlacklisted(file)) + // Protocol metadata is written by GeneralUpdate itself (no user content, no + // credentials) and is REQUIRED by the upload contract — the update blacklist + // the bootstrap passes as the privacy filter excludes ".json" by default, + // which would strip every mandatory payload from the bundle. Everything else + // (log tails, collected artifacts) still honors the privacy exclusions. + if (privacyFilter != null && !IsProtocolMetadata(file) && privacyFilter.IsBlacklisted(file)) { GeneralTracer.Info($"DiagnosticsPackager: blacklisted file excluded: {Path.GetFileName(file)}."); continue; @@ -200,6 +288,20 @@ private static IEnumerable EnumerateFiles(string directory) private static bool IsDump(string path) => Path.GetExtension(path).Equals(DumpExtension, StringComparison.OrdinalIgnoreCase); + /// + /// The fixed protocol-metadata file names the packager and the rollback/self-check + /// collectors stage themselves (plus Bowl's outbox manifest). These must reach the + /// server regardless of the host's exclusion lists. + /// + private static bool IsProtocolMetadata(string path) + { + var name = Path.GetFileName(path); + return name.Equals(ManifestEntryName, StringComparison.OrdinalIgnoreCase) + || name.Equals("self-check-report.json", StringComparison.OrdinalIgnoreCase) + || name.Equals("rollback-result.json", StringComparison.OrdinalIgnoreCase) + || name.Equals(Configuration.ManifestInfo.FileName, StringComparison.OrdinalIgnoreCase); + } + private static void WriteIfAny(string path, string? content) { if (string.IsNullOrWhiteSpace(content)) return; diff --git a/src/GeneralUpdate.Core/Diagnostics/DiagnosticsUploader.cs b/src/GeneralUpdate.Core/Diagnostics/DiagnosticsUploader.cs index 000601ee..1dd5dd5c 100644 --- a/src/GeneralUpdate.Core/Diagnostics/DiagnosticsUploader.cs +++ b/src/GeneralUpdate.Core/Diagnostics/DiagnosticsUploader.cs @@ -6,8 +6,8 @@ using System.Text.Json; using System.Threading; using System.Threading.Tasks; -using GeneralUpdate.Core.JsonContext; using GeneralUpdate.Core.Network; +using GeneralUpdate.Core.JsonContext; namespace GeneralUpdate.Core.Diagnostics; @@ -21,7 +21,7 @@ public interface IDiagnosticsUploader /// true when the uploader has a usable endpoint (enabled + URL). bool IsConfigured { get; } - /// Uploads a bundle (archive + manifest). Returns true on a 2xx response. + /// Uploads a bundle and returns true only after the server acknowledges its GUID. Task UploadAsync(DiagnosticsBundle bundle, CancellationToken ct); } @@ -31,10 +31,13 @@ public interface IDiagnosticsUploader /// /// /// -/// Wire format: the zip archive as the request body (octet-stream) plus the declared -/// in the X-Diagnostics-Manifest header so the -/// server can audit the contents. Requests carry the global authentication provider and -/// extra headers (same convention as HttpUpdateReporter). +/// Wire format: multipart/form-data per the GeneralSpace +/// POST /Fault/UploadArtifact contract — the zip archive as the file part +/// plus the fields as form fields. The guid +/// field is the server-side idempotency key: replaying the same bundle can return a +/// duplicate acknowledgment without storing another copy. +/// The same manifest is also embedded inside the archive as manifest.json so the +/// server can audit contents without trusting the form (privacy/audit requirement). /// /// /// Failure handling follows the reporter convention: upload failures are logged and @@ -45,6 +48,8 @@ public interface IDiagnosticsUploader public sealed class DiagnosticsUploader : IDiagnosticsUploader { private static readonly TimeSpan RequestTimeout = TimeSpan.FromSeconds(30); + private const long MaxRequestBytes = 20 * 1024 * 1024; + private const int MaxResponseBytes = 64 * 1024; private readonly DiagnosticsOptions _options; private readonly HttpClient _client; @@ -67,9 +72,10 @@ public DiagnosticsUploader(DiagnosticsOptions options, HttpClient? client = null } /// - /// Uploads a bundle (archive + manifest). Deletes the temporary archive afterwards. + /// Uploads a bundle (archive + manifest) as multipart form data. + /// Deletes the temporary archive afterwards. /// - /// true when the server accepted the bundle with a 2xx response. + /// true when the HTTP response and matching business acknowledgment succeed. public async Task UploadAsync(DiagnosticsBundle bundle, CancellationToken ct) { if (bundle == null) throw new ArgumentNullException(nameof(bundle)); @@ -82,26 +88,46 @@ public async Task UploadAsync(DiagnosticsBundle bundle, CancellationToken try { + var manifest = bundle.Manifest ?? new DiagnosticsManifest(); + if (!string.IsNullOrWhiteSpace(manifest.AppKey) && + (!Uri.TryCreate(_options.Url, UriKind.Absolute, out var uri) || + !Download.Reporting.HttpUpdateReporter.IsSecureReportUri(uri))) + { + GeneralTracer.Warn("DiagnosticsUploader: app key upload requires HTTPS or an IP loopback HTTP endpoint."); + return false; + } + if (!Guid.TryParse(manifest.Guid, out _)) + { + GeneralTracer.Warn("DiagnosticsUploader: bundle has no valid GUID."); + return false; + } using var stream = File.OpenRead(bundle.ZipPath); + using var content = BuildMultipartContent(manifest, stream); + using var request = new HttpRequestMessage(HttpMethod.Post, _options.Url) { - Content = new StreamContent(stream) + Content = content }; - request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); - request.Headers.Add("X-Diagnostics-Manifest", SerializeManifest(bundle.Manifest)); using var timeoutCts = CancellationTokenSource.CreateLinkedTokenSource(ct); timeoutCts.CancelAfter(RequestTimeout); - using var response = await _client.SendAsync(request, timeoutCts.Token).ConfigureAwait(false); + await HttpClientProvider.ApplyAuthAsync(request, timeoutCts.Token).ConfigureAwait(false); + if (content.Headers.ContentLength is long length && length > MaxRequestBytes) + { + GeneralTracer.Warn("DiagnosticsUploader: multipart request exceeds the server size limit."); + return false; + } + using var response = await _client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, timeoutCts.Token).ConfigureAwait(false); - if (response.IsSuccessStatusCode) + if (response.IsSuccessStatusCode && await IsAcceptedAsync(response, manifest.Guid, timeoutCts.Token).ConfigureAwait(false)) { - GeneralTracer.Info($"DiagnosticsUploader: bundle uploaded ({bundle.Manifest.Files.Count} file(s))."); + GeneralTracer.Info( + $"DiagnosticsUploader: bundle {manifest.Guid} ({manifest.Kind}, {manifest.Files.Count} file(s)) uploaded."); return true; } // Bounded, code-only failure record — response bodies are never read into logs. - GeneralTracer.Warn($"DiagnosticsUploader: upload rejected with HTTP {(int)response.StatusCode}."); + GeneralTracer.Warn($"DiagnosticsUploader: upload was not acknowledged (HTTP {(int)response.StatusCode})."); return false; } catch (OperationCanceledException) when (!ct.IsCancellationRequested) @@ -109,6 +135,10 @@ public async Task UploadAsync(DiagnosticsBundle bundle, CancellationToken GeneralTracer.Warn("DiagnosticsUploader: upload timed out."); return false; } + catch (OperationCanceledException) when (ct.IsCancellationRequested) + { + throw; + } catch (Exception ex) { GeneralTracer.Warn($"DiagnosticsUploader: upload failed: {ex.Message}"); @@ -120,17 +150,84 @@ public async Task UploadAsync(DiagnosticsBundle bundle, CancellationToken } } - private static string SerializeManifest(DiagnosticsManifest manifest) + /// + /// Builds the /Fault/UploadArtifact multipart body: the file part plus one + /// form field per manifest attribute. Optional attributes are omitted (not sent empty) — + /// the server treats them as "not provided". + /// + internal static MultipartFormDataContent BuildMultipartContent(DiagnosticsManifest manifest, Stream zipStream) { - try - { - return JsonSerializer.Serialize(manifest, DiagnosticsJsonContext.Default.DiagnosticsManifest); - } - catch + var guid = manifest.Guid; + + var content = new MultipartFormDataContent(); + + var fileContent = new StreamContent(zipStream); + fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/zip"); + content.Add(fileContent, "file", $"{guid}.zip"); + + // Required contract fields. + content.Add(new StringContent(guid), "guid"); + content.Add(new StringContent(manifest.Kind ?? DiagnosticsKinds.Manual), "kind"); + content.Add(new StringContent(manifest.Schema.ToString()), "schema"); + + // Optional attribution fields — present only when known. + AddIfNotEmpty(content, "appKey", manifest.AppKey); + AddIfNotEmpty(content, "version", manifest.Version); + AddIfNotEmpty(content, "targetName", manifest.TargetName); + AddIfNotEmpty(content, "productId", manifest.ProductId); + AddIfNotEmpty(content, "reason", manifest.Reason); + if (manifest.Files.Count > 0) + content.Add(new StringContent(JsonSerializer.Serialize(manifest.Files, DiagnosticsJsonContext.Default.ListString)), "files"); + if (manifest.Platform.HasValue) + content.Add(new StringContent(manifest.Platform.Value.ToString()), "platform"); + if (manifest.RecordId is > 0) + content.Add(new StringContent(manifest.RecordId.Value.ToString()), "recordId"); + if (manifest.RecordType is > 0) + content.Add(new StringContent(manifest.RecordType.Value.ToString()), "recordType"); + + return content; + } + + private static async Task IsAcceptedAsync(HttpResponseMessage response, string guid, CancellationToken ct) + { + 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, ct).ConfigureAwait(false)) > 0) { - // A manifest is metadata; an upload without it is still worth attempting. - return "{}"; + if (buffer.Length + read > MaxResponseBytes) + return false; + buffer.Write(chunk, 0, read); } + + buffer.Position = 0; + using var json = await JsonDocument.ParseAsync(buffer, cancellationToken: ct).ConfigureAwait(false); + return TryGetProperty(json.RootElement, "code", out var code) && + code.ValueKind == JsonValueKind.Number && code.TryGetInt32(out var value) && value == 200 && + TryGetProperty(json.RootElement, "body", out var body) && + TryGetProperty(body, "artifactId", out var artifactId) && + artifactId.ValueKind == JsonValueKind.String && + string.Equals(artifactId.GetString(), guid, StringComparison.Ordinal); + } + + private static bool TryGetProperty(JsonElement element, string name, out JsonElement value) + { + if (element.ValueKind == JsonValueKind.Object) + foreach (var property in element.EnumerateObject()) + if (string.Equals(property.Name, name, StringComparison.OrdinalIgnoreCase)) + { + value = property.Value; + return true; + } + value = default; + return false; + } + + private static void AddIfNotEmpty(MultipartFormDataContent content, string name, string? value) + { + if (!string.IsNullOrWhiteSpace(value)) + content.Add(new StringContent(value), name); } private static void TryDelete(string path) diff --git a/src/GeneralUpdate.Core/Diagnostics/IDiagnosticsCollector.cs b/src/GeneralUpdate.Core/Diagnostics/IDiagnosticsCollector.cs index 95af8a96..efbfbd22 100644 --- a/src/GeneralUpdate.Core/Diagnostics/IDiagnosticsCollector.cs +++ b/src/GeneralUpdate.Core/Diagnostics/IDiagnosticsCollector.cs @@ -1,3 +1,4 @@ +using System; using System.Threading; using System.Threading.Tasks; using GeneralUpdate.Core.FileSystem; @@ -45,7 +46,10 @@ public DiagnosticsCollector(DiagnosticsOptions? options = null, IBlackMatcher? p /// public Task CollectAsync(DiagnosticsCollectRequest request, CancellationToken ct) { - var bundle = DiagnosticsPackager.PackBundle(request, _options, _privacyFilter); + // The GUID is generated once here and embedded both in the archive manifest and in the + // upload metadata — the server deduplicates on it, so a retry re-sends the same id. + var bundleGuid = Guid.NewGuid().ToString("D"); + var bundle = DiagnosticsPackager.PackBundle(request, _options, bundleGuid, _privacyFilter); if (bundle == null) { GeneralTracer.Info("DiagnosticsCollector: nothing to collect for this request."); @@ -55,8 +59,15 @@ public DiagnosticsCollector(DiagnosticsOptions? options = null, IBlackMatcher? p var zip = bundle.Value.ZipPath; var manifest = new DiagnosticsManifest { + Guid = bundleGuid, Kind = request.Kind, Version = request.TargetVersion, + TargetName = _options.TargetName, + AppKey = _options.AppKey, + ProductId = _options.ProductId, + Platform = _options.Platform, + RecordId = request.RecordId > 0 ? request.RecordId : null, + RecordType = request.RecordType > 0 ? request.RecordType : null, Reason = request.Reason, Files = bundle.Value.Entries, }; diff --git a/src/GeneralUpdate.Core/Diagnostics/OutboxManifest.cs b/src/GeneralUpdate.Core/Diagnostics/OutboxManifest.cs index 5d459b10..12647b9e 100644 --- a/src/GeneralUpdate.Core/Diagnostics/OutboxManifest.cs +++ b/src/GeneralUpdate.Core/Diagnostics/OutboxManifest.cs @@ -59,4 +59,14 @@ public sealed class OutboxManifest /// Upload attempts already made; Core increments it after each failed upload. [JsonPropertyName("attempts")] public int Attempts { get; set; } + + /// Associated server record for update-failure evidence. + [JsonPropertyName("recordId")] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public int? RecordId { get; set; } + + /// Record type for update-failure evidence. + [JsonPropertyName("recordType")] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public int? RecordType { get; set; } } diff --git a/src/GeneralUpdate.Core/Diagnostics/PendingDiagnosticsScanner.cs b/src/GeneralUpdate.Core/Diagnostics/PendingDiagnosticsScanner.cs index 30f50b0f..0dcbcff9 100644 --- a/src/GeneralUpdate.Core/Diagnostics/PendingDiagnosticsScanner.cs +++ b/src/GeneralUpdate.Core/Diagnostics/PendingDiagnosticsScanner.cs @@ -1,5 +1,7 @@ using System; +using System.Collections.Generic; using System.IO; +using System.Linq; using System.Text.Json; using System.Threading; using System.Threading.Tasks; @@ -9,19 +11,19 @@ namespace GeneralUpdate.Core.Diagnostics; /// -/// Scans the Bowl crash-evidence outbox ({install}/fail/{version}/{guid}/) and +/// Scans Bowl crash-evidence outboxes under {install}/fail and +/// {stateRoot}/crash-outbox ({version}/{guid}/) and /// uploads pending evidence to the server. This is the arrival channel for crash /// diagnostics — Bowl writes evidence to disk, Core delivers it. /// /// /// -/// Pure disk-contract interaction: read-only scanning without locks, the whole flow -/// wrapped so it can run fire-and-forget in the background of a client start. The -/// three no-coordination rules (docs/bowl-redesign.md §3.2): +/// A per-root lock serializes client scans. The flow runs in the background at client +/// start. The disk contract uses the following rules: /// /// /// existing means pending — a {guid}/ directory present means "not uploaded yet"; -/// uploaded means deleted — the whole directory is removed after a 2xx response; +/// uploaded means deleted — the directory is removed only after server acknowledgment; /// schema tolerance — manifests with a schema other than 2 are skipped with a warning. /// /// @@ -35,6 +37,8 @@ public sealed class PendingDiagnosticsScanner { /// Root of the outbox: {installPath}/fail. private readonly string _failRoot; + private readonly string? _crashOutboxRoot; + private readonly string? _updateOutboxRoot; private readonly DiagnosticsOptions _options; private readonly IDiagnosticsUploader _uploader; private readonly IBlackMatcher? _privacyFilter; @@ -47,11 +51,15 @@ public sealed class PendingDiagnosticsScanner /// the ambient static) so the scan behaves deterministically regardless of other state. /// public PendingDiagnosticsScanner(string installPath, DiagnosticsOptions options, - IDiagnosticsUploader uploader, IBlackMatcher? privacyFilter = null) + IDiagnosticsUploader uploader, IBlackMatcher? privacyFilter = null, string? stateRoot = null, + string? installationId = null) { if (string.IsNullOrWhiteSpace(installPath)) throw new ArgumentNullException(nameof(installPath)); _failRoot = Path.Combine(installPath, "fail"); + _crashOutboxRoot = string.IsNullOrWhiteSpace(stateRoot) ? null : Path.Combine(stateRoot, "crash-outbox"); + if (!string.IsNullOrWhiteSpace(stateRoot) && Guid.TryParseExact(installationId, "D", out _)) + _updateOutboxRoot = Path.Combine(stateRoot, "update-outbox", installationId); _options = options ?? throw new ArgumentNullException(nameof(options)); _uploader = uploader ?? throw new ArgumentNullException(nameof(uploader)); _privacyFilter = privacyFilter; @@ -86,31 +94,69 @@ private async Task ScanCoreAsync(CancellationToken ct) { try { - if (!Directory.Exists(_failRoot)) - return; + await ScanRootAsync(_failRoot, false, ct).ConfigureAwait(false); + if (_crashOutboxRoot != null) + await ScanRootAsync(_crashOutboxRoot, true, ct).ConfigureAwait(false); + if (_updateOutboxRoot != null) + await ScanUpdateOutboxAsync(ct).ConfigureAwait(false); + } + + catch (OperationCanceledException) + { + throw; + } + catch (Exception ex) + { + GeneralTracer.Warn($"PendingDiagnosticsScanner: scan aborted: {ex.Message}"); + } + } + + private async Task ScanUpdateOutboxAsync(CancellationToken ct) + { + var root = _updateOutboxRoot!; + if (!Directory.Exists(root)) return; + for (var directory = new DirectoryInfo(root); directory != null; directory = directory.Parent) + if (directory.Exists && (directory.Attributes & FileAttributes.ReparsePoint) != 0) + throw new InvalidDataException("Update diagnostics outbox cannot traverse symbolic links."); + using var scanLock = new FileStream(Path.Combine(root, ".scan.lock"), FileMode.OpenOrCreate, + FileAccess.ReadWrite, FileShare.None); + foreach (var caseDir in Directory.EnumerateDirectories(root)) + { + ct.ThrowIfCancellationRequested(); + if (!Guid.TryParseExact(Path.GetFileName(caseDir), "D", out _) || + (File.GetAttributes(caseDir) & FileAttributes.ReparsePoint) != 0) continue; + await ProcessCaseAsync(caseDir, false, ct, DiagnosticsKinds.Update).ConfigureAwait(false); + } + } - foreach (var versionDir in Directory.EnumerateDirectories(_failRoot)) + private async Task ScanRootAsync(string root, bool requireDump, CancellationToken ct) + { + if (!Directory.Exists(root)) return; + try + { + using var scanLock = new FileStream(Path.Combine(root, ".scan.lock"), FileMode.OpenOrCreate, + FileAccess.ReadWrite, FileShare.None); + foreach (var versionDir in Directory.EnumerateDirectories(root)) { ct.ThrowIfCancellationRequested(); + if ((File.GetAttributes(versionDir) & FileAttributes.ReparsePoint) != 0) continue; foreach (var caseDir in Directory.EnumerateDirectories(versionDir)) { ct.ThrowIfCancellationRequested(); - await ProcessCaseAsync(caseDir, ct).ConfigureAwait(false); + if ((File.GetAttributes(caseDir) & FileAttributes.ReparsePoint) != 0) continue; + if (!Guid.TryParseExact(Path.GetFileName(caseDir), "D", out _)) continue; + await ProcessCaseAsync(caseDir, requireDump, ct).ConfigureAwait(false); } } } - catch (OperationCanceledException) + catch (IOException ex) { - throw; - } - catch (Exception ex) - { - // One broken directory must not take down the scan loop or the caller. - GeneralTracer.Warn($"PendingDiagnosticsScanner: scan aborted: {ex.Message}"); + GeneralTracer.Warn($"PendingDiagnosticsScanner: could not scan {root}: {ex.Message}"); } } - private async Task ProcessCaseAsync(string caseDir, CancellationToken ct) + private async Task ProcessCaseAsync(string caseDir, bool requireDump, CancellationToken ct, + string expectedKind = DiagnosticsKinds.Crash) { try { @@ -120,6 +166,11 @@ private async Task ProcessCaseAsync(string caseDir, CancellationToken ct) GeneralTracer.Warn($"PendingDiagnosticsScanner: skipping {caseDir} — no manifest.json."); return; } + if (expectedKind == DiagnosticsKinds.Update && !IsSafeUpdateCase(caseDir)) + { + GeneralTracer.Warn($"PendingDiagnosticsScanner: invalid update diagnostic case; retaining {caseDir}."); + return; + } var manifest = JsonSerializer.Deserialize( File.ReadAllText(manifestPath), DiagnosticsJsonContext.Default.OutboxManifest); @@ -129,21 +180,66 @@ private async Task ProcessCaseAsync(string caseDir, CancellationToken ct) return; } + if (!Guid.TryParseExact(manifest.Guid, "D", out var manifestGuid) || + !Guid.TryParseExact(Path.GetFileName(caseDir), "D", out var directoryGuid) || + manifestGuid != directoryGuid || + !string.Equals(manifest.Kind, expectedKind, StringComparison.OrdinalIgnoreCase) || + (expectedKind == DiagnosticsKinds.Update && (manifest.RecordId is null or <= 0 || + manifest.RecordType is not (1 or 2) || !string.IsNullOrEmpty(manifest.TargetName) || + !string.IsNullOrEmpty(manifest.Version) || string.IsNullOrWhiteSpace(_options.AppKey) || + !string.Equals(manifest.State, OutboxStates.Pending, StringComparison.Ordinal)))) + { + GeneralTracer.Warn($"PendingDiagnosticsScanner: skipping {caseDir} — invalid crash manifest identity."); + return; + } + if (string.Equals(manifest.State, OutboxStates.Giveup, StringComparison.OrdinalIgnoreCase)) return; // Retry budget exhausted; Bowl's disk GC owns the directory from here. + if (requireDump && !IsSafeCrashCase(caseDir)) + { + GeneralTracer.Warn($"PendingDiagnosticsScanner: crash case is incomplete or contains links; retaining {caseDir}."); + return; + } + var packed = DiagnosticsPackager.PackDirectory(caseDir, _options, _privacyFilter); if (packed == null) { RecordFailure(manifestPath, manifest); return; } + if (expectedKind == DiagnosticsKinds.Update && + !packed.Value.Entries.Contains("diagnostic.txt", StringComparer.Ordinal)) + { + File.Delete(packed.Value.ZipPath); + GeneralTracer.Warn($"PendingDiagnosticsScanner: update diagnostic was excluded; retaining {caseDir}."); + RecordFailure(manifestPath, manifest); + return; + } + if (requireDump && !packed.Value.Entries.Any(entry => + string.Equals(Path.GetExtension(entry), ".dmp", StringComparison.OrdinalIgnoreCase))) + { + File.Delete(packed.Value.ZipPath); + GeneralTracer.Warn($"PendingDiagnosticsScanner: crash dump was excluded or too large; retaining {caseDir}."); + RecordFailure(manifestPath, manifest); + return; + } + // The outbox manifest's guid travels to the server: it is the idempotency key, so a + // retried upload of the same evidence directory deduplicates instead of duplicating. var bundle = new DiagnosticsBundle(packed.Value.ZipPath, new DiagnosticsManifest { + Guid = manifest.Guid, Kind = manifest.Kind, + TargetName = manifest.TargetName, Version = manifest.Version, - Reason = $"crash outbox {manifest.Guid}, exitCode={manifest.ExitCode?.ToString() ?? "n/a"}", + AppKey = _options.AppKey, + ProductId = _options.ProductId, + Platform = _options.Platform, + RecordId = manifest.RecordId, + RecordType = manifest.RecordType, + Reason = expectedKind == DiagnosticsKinds.Update ? "Update failed" : + $"crash outbox {manifest.Guid}, exitCode={manifest.ExitCode?.ToString() ?? "n/a"}", Files = packed.Value.Entries, }); @@ -167,23 +263,67 @@ private async Task ProcessCaseAsync(string caseDir, CancellationToken ct) } } + private static bool IsSafeCrashCase(string caseDir) + { + var directories = new Stack(); + directories.Push(caseDir); + var hasDump = false; + while (directories.Count > 0) + { + foreach (var path in Directory.EnumerateFileSystemEntries(directories.Pop())) + { + var attributes = File.GetAttributes(path); + if ((attributes & FileAttributes.ReparsePoint) != 0) return false; + if ((attributes & FileAttributes.Directory) != 0) + directories.Push(path); + else if (string.Equals(Path.GetExtension(path), ".dmp", StringComparison.OrdinalIgnoreCase) && + new FileInfo(path).Length > 0) + hasDump = true; + } + } + return hasDump; + } + private void RecordFailure(string manifestPath, OutboxManifest manifest) { try { manifest.Attempts++; - if (manifest.Attempts >= _options.MaxRetry) + if (manifest.Kind != DiagnosticsKinds.Update && _options.MaxRetry > 0 && manifest.Attempts >= _options.MaxRetry) { manifest.State = OutboxStates.Giveup; GeneralTracer.Warn($"PendingDiagnosticsScanner: {manifest.Guid} marked giveup after {manifest.Attempts} attempts."); } - File.WriteAllText(manifestPath, - JsonSerializer.Serialize(manifest, DiagnosticsJsonContext.Default.OutboxManifest)); + var tempPath = manifestPath + "." + Guid.NewGuid().ToString("N") + ".tmp"; + try + { + File.WriteAllText(tempPath, JsonSerializer.Serialize(manifest, DiagnosticsJsonContext.Default.OutboxManifest)); + File.Replace(tempPath, manifestPath, null); + } + finally + { + if (File.Exists(tempPath)) File.Delete(tempPath); + } } catch (Exception ex) { GeneralTracer.Warn($"PendingDiagnosticsScanner: could not persist retry state for {manifest.Guid}: {ex.Message}"); } } + + private static bool IsSafeUpdateCase(string caseDir) + { + var files = Directory.GetFileSystemEntries(caseDir); + if (files.Length != 2) return false; + var manifest = Path.Combine(caseDir, "manifest.json"); + var diagnostic = Path.Combine(caseDir, "diagnostic.txt"); + if (!File.Exists(manifest) || !File.Exists(diagnostic)) return false; + foreach (var file in files) + if ((File.GetAttributes(file) & (FileAttributes.ReparsePoint | FileAttributes.Directory)) != 0 || + new FileInfo(file).Length > 4096) return false; + var text = File.ReadAllText(diagnostic); + return new[] { "Download", "Verify", "Extract", "Apply", "Startup", "Rollback", "Unknown" } + .Any(phase => text == "Update failure\nPhase: " + phase + "\n"); + } } diff --git a/src/GeneralUpdate.Core/Differential/DefaultDirtyMatcher.cs b/src/GeneralUpdate.Core/Differential/DefaultDirtyMatcher.cs index 7b9b63e5..bf421e59 100644 --- a/src/GeneralUpdate.Core/Differential/DefaultDirtyMatcher.cs +++ b/src/GeneralUpdate.Core/Differential/DefaultDirtyMatcher.cs @@ -37,16 +37,42 @@ public class DefaultDirtyMatcher : IDirtyMatcher if (oldFile is null) throw new ArgumentNullException(nameof(oldFile)); if (patchFiles is null) throw new ArgumentNullException(nameof(patchFiles)); - var findFile = patchFiles.FirstOrDefault(f => + var candidates = patchFiles.Where(f => { + if (!Path.GetExtension(f.FullName).Equals(PatchFormat, System.StringComparison.OrdinalIgnoreCase)) + return false; var name = Path.GetFileNameWithoutExtension(f.Name); return name.Equals(oldFile.Name, System.StringComparison.OrdinalIgnoreCase); - }); + }).ToList(); - if (findFile != null && - Path.GetExtension(findFile.FullName).Equals(PatchFormat, System.StringComparison.OrdinalIgnoreCase)) - return findFile; + if (candidates.Count == 0) return null; + if (candidates.Count == 1) return candidates[0]; - return null; + // Same file name exists in multiple patch directories: prefer the candidate whose + // directory structure aligns most closely with the application file's directory, + // so identical names in different subdirectories receive their own patch instead + // of whichever candidate happened to enumerate first. + return candidates + .OrderByDescending(c => CommonSuffixSegments(oldFile.DirectoryName, c.DirectoryName)) + .First(); + } + + /// + /// Counts the trailing directory segments shared by the two paths (case-insensitive). + /// + private static int CommonSuffixSegments(string? dirA, string? dirB) + { + if (string.IsNullOrEmpty(dirA) || string.IsNullOrEmpty(dirB)) return 0; + var a = dirA.TrimEnd('\\', '/').Split('\\', '/'); + var b = dirB.TrimEnd('\\', '/').Split('\\', '/'); + int i = a.Length - 1, j = b.Length - 1, shared = 0; + while (i >= 0 && j >= 0 && + string.Equals(a[i], b[j], System.StringComparison.OrdinalIgnoreCase)) + { + shared++; + i--; + j--; + } + return shared; } } diff --git a/src/GeneralUpdate.Core/Download/Abstractions/IDownloadOrchestrator.cs b/src/GeneralUpdate.Core/Download/Abstractions/IDownloadOrchestrator.cs index cc06a28d..68dd75df 100644 --- a/src/GeneralUpdate.Core/Download/Abstractions/IDownloadOrchestrator.cs +++ b/src/GeneralUpdate.Core/Download/Abstractions/IDownloadOrchestrator.cs @@ -33,8 +33,12 @@ public interface IDownloadOrchestrator /// The download plan containing the list of assets to download. Must not be null. /// The destination directory path where files will be saved. /// - /// The maximum number of concurrent downloads. Defaults to 3. - /// When set to 0 or a negative value, falls back to the value configured in options. + /// The maximum number of concurrent downloads. Defaults to 0 — "use the value configured + /// in options" (mirrors the DefaultDownloadOrchestrator implementation; optional + /// arguments are substituted from the compile-time type, so an interface default that + /// differs from the implementation silently overrides the configured concurrency on + /// interface-typed calls). + /// When set to a positive value, overrides the configured concurrency. /// /// An optional receiver for per-asset download progress notifications. /// A to cancel the operation. @@ -50,7 +54,7 @@ public interface IDownloadOrchestrator Task ExecuteAsync( DownloadPlan plan, string destDir, - int maxConcurrency = 3, + int maxConcurrency = 0, IProgress? progress = null, CancellationToken token = default); } diff --git a/src/GeneralUpdate.Core/Download/DownloadPlanBuilder.cs b/src/GeneralUpdate.Core/Download/DownloadPlanBuilder.cs index 1176a43d..cb411c79 100644 --- a/src/GeneralUpdate.Core/Download/DownloadPlanBuilder.cs +++ b/src/GeneralUpdate.Core/Download/DownloadPlanBuilder.cs @@ -215,7 +215,7 @@ DownloadPlan SwitchToFull(string reason) } // ── Chain plan with fallback fulls ── - if (fullCandidates.Count > 0) + if (chainCandidates.Count > 0 && fullCandidates.Count > 0) { var fallbackFulls = new List(); @@ -255,6 +255,25 @@ DownloadPlan SwitchToFull(string reason) }; } + // ── Full-only plan: the latest full replacement package is the plan itself. + // Without this branch a server offering only Full packages produced an empty + // plan while HasUpdate still reported an update, which crashed the client + // strategy downstream (SendProcessIpc with a null last version). + // Select the latest full INDEPENDENTLY per AppType: a combined Client+Upgrade + // release publishes one full per track, and a single global pick silently + // dropped the other track's required package. + if (fullCandidates.Count > 0) + { + var bestFulls = fullCandidates + .GroupBy(a => a.AppType ?? (int)AppType.Client) + .Select(g => g.OrderByDescending(a => Lookup(a)).First()) + .OrderBy(a => Lookup(a)) + .ToList(); + GeneralTracer.Info($"DownloadPlanBuilder: no chain candidates, using {bestFulls.Count} full package(s): " + + string.Join(", ", bestFulls.Select(f => $"{f.Name} (v{f.Version}, {f.Size} bytes)")) + "."); + return new DownloadPlan(bestFulls, isForcibly); + } + return new DownloadPlan(chainCandidates, isForcibly); } diff --git a/src/GeneralUpdate.Core/Download/Executors/HttpDownloadExecutor.cs b/src/GeneralUpdate.Core/Download/Executors/HttpDownloadExecutor.cs index 67cc0b49..fdc6db85 100644 --- a/src/GeneralUpdate.Core/Download/Executors/HttpDownloadExecutor.cs +++ b/src/GeneralUpdate.Core/Download/Executors/HttpDownloadExecutor.cs @@ -145,8 +145,13 @@ public async Task ExecuteAsync( using var fs = new FileStream(destPath, mode, FileAccess.Write, FileShare.None); using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); + // Pass the linked timeout token, NOT the caller's token: with + // HttpCompletionOption.ResponseHeadersRead, SendAsync has already completed and + // its cancellation registration does not bound subsequent response-stream reads. + // The re-armed idle timer (idleCts) is what interrupts inactivity — a stalled + // connection after the headers would otherwise occupy a download slot indefinitely. var (downloaded, elapsed) = await StreamDownloadAsync(stream, fs, totalBytes, existingBytes, - destPath, progress, sw, token, asset.VersionContext).ConfigureAwait(false); + destPath, progress, sw, cts.Token, asset.VersionContext, cts, _timeout).ConfigureAwait(false); progress?.Report(new DownloadProgress( Path.GetFileName(destPath), downloaded, @@ -178,21 +183,27 @@ public async Task ExecuteAsync( /// A tuple containing the actual bytes downloaded and the elapsed duration. /// /// - /// The download loop uses an 8192-byte (8 KB) buffer for chunked reading to avoid - /// excessive memory consumption. + /// The download loop uses a 64 KB buffer for chunked reading to balance memory + /// consumption and throughput on high-bandwidth links. /// /// /// Progress is reported every 250 milliseconds, or immediately upon download completion. /// Progress information includes the file name, bytes downloaded, total bytes (if known), /// and completion percentage. /// + /// + /// When is supplied, is re-armed + /// after every successful read, so the timeout bounds inactivity (a stalled + /// connection) rather than the total duration of the download. Slow-but-alive + /// transfers of arbitrarily large files therefore keep making progress. + /// /// internal static async Task<(long Downloaded, TimeSpan Elapsed)> StreamDownloadAsync( Stream source, Stream dest, long totalBytes, long existingBytes, string destPath, IProgress? progress, Stopwatch sw, CancellationToken token, - object? versionContext = null) + object? versionContext = null, CancellationTokenSource? idleCts = null, TimeSpan idleTimeout = default) { - var buffer = new byte[8192]; + var buffer = new byte[65536]; long downloaded = existingBytes; long lastReport = 0; int read; @@ -201,6 +212,7 @@ public async Task ExecuteAsync( { await dest.WriteAsync(buffer, 0, read, token).ConfigureAwait(false); downloaded += read; + idleCts?.CancelAfter(idleTimeout); var now = sw.ElapsedMilliseconds; if (now - lastReport >= 250 || downloaded == totalBytes + existingBytes) diff --git a/src/GeneralUpdate.Core/Download/Orchestrators/DefaultDownloadOrchestrator.cs b/src/GeneralUpdate.Core/Download/Orchestrators/DefaultDownloadOrchestrator.cs index 25a264a6..e9679110 100644 --- a/src/GeneralUpdate.Core/Download/Orchestrators/DefaultDownloadOrchestrator.cs +++ b/src/GeneralUpdate.Core/Download/Orchestrators/DefaultDownloadOrchestrator.cs @@ -183,7 +183,7 @@ public DefaultDownloadOrchestrator( public async Task ExecuteAsync( DownloadPlan plan, string destDir, - int maxConcurrency = 3, + int maxConcurrency = 0, IProgress? progress = null, CancellationToken token = default) { @@ -193,8 +193,9 @@ public async Task ExecuteAsync( Directory.CreateDirectory(destDir); // Resolve effective concurrency: Serial mode forces 1. - // Uses _options.MaxConcurrency as primary value; the method parameter - // maxConcurrency acts as an override (default 3). + // _options.MaxConcurrency is the primary value; the method parameter acts as + // an explicit override only (0 = "use options" so the default argument no + // longer silently masks a user-configured concurrency). var baseConcurrency = maxConcurrency > 0 ? maxConcurrency : _options.MaxConcurrency; var effectiveConcurrency = _options.DiffMode == DiffMode.Serial ? 1 diff --git a/src/GeneralUpdate.Core/Download/Reporting/IUpdateReporter.cs b/src/GeneralUpdate.Core/Download/Reporting/IUpdateReporter.cs index 2f79e72d..95bc3ea5 100644 --- a/src/GeneralUpdate.Core/Download/Reporting/IUpdateReporter.cs +++ b/src/GeneralUpdate.Core/Download/Reporting/IUpdateReporter.cs @@ -1,4 +1,5 @@ using System; +using System.Net; using System.Net.Http; using System.Text; using System.Text.Json; @@ -62,8 +63,10 @@ public enum UpdateStatus { Updating = 1, Success = 2, Failure = 3 } /// The update type: 1 = Upgrade, 2 = Push. Defaults to 1 (Upgrade). /// /// Local persistence and custom reporters receive the diagnostic fields below. -/// HttpUpdateReporter deliberately projects only {"recordId":123,"status":1,"type":1}; -/// local paths and exception details are not automatically uploaded. +/// HttpUpdateReporter projects the legacy three-field payload plus the optional failure +/// attribution fields (, error code and message) per the GeneralSpace +/// Investigate extension of the ReportDTO — legacy servers ignore unknown JSON members, +/// so the extension is grayscale-safe. /// public record UpdateReport(int RecordId, int Status = 1, int Type = 1) { @@ -73,6 +76,8 @@ public record UpdateReport(int RecordId, int Status = 1, int Type = 1) public string? UpdateAttemptId { get; init; } /// Stable identifier once persisted; retries reuse it, but the legacy server does not receive it. public string? EventId { get; init; } + /// Whether HTTP delivery must have an app key; this flag is safe to persist for retries. + public bool RequiresAppKey { get; init; } /// Name of the package being applied when this evidence was captured, if known. public string? PackageName { get; init; } /// That package's version, which may differ from the whole attempt's target version. @@ -81,6 +86,12 @@ public record UpdateReport(int RecordId, int Status = 1, int Type = 1) public string? Role { get; init; } /// Workflow stage at capture time; Error.Stage retains the originating failure stage. public string? Stage { get; init; } + /// + /// Server-facing failure phase (: Download/Verify/Extract/Apply/ + /// Startup/Rollback). Unlike this value crosses the wire — set it only + /// where the phase is unambiguous (self-check verdict, rollback executor, distribution points). + /// + public string? Phase { get; init; } /// Explicit local meaning such as filesApplied, updateFailed or monitorUnavailable; not business health. public string? Outcome { get; init; } /// Application version before this attempt. @@ -93,8 +104,31 @@ public record UpdateReport(int RecordId, int Status = 1, int Type = 1) public UpdateFailure? Error { get; init; } } -/// Explicit wire allowlist: adding local diagnostic fields cannot silently change the server API. -internal record LegacyUpdateReport(int RecordId, int Status, int Type); +/// +/// Well-known values for — the server-facing failure-phase +/// vocabulary of the GeneralSpace ReportDTO (升级故障归因与修复闭环设计方案 §3). +/// +public static class UpdatePhases +{ + public const string Download = "Download"; + public const string Verify = "Verify"; + public const string Extract = "Extract"; + public const string Apply = "Apply"; + /// Post-update launch verification failed (self-check judged the new version unusable). + public const string Startup = "Startup"; + /// Rolling back to the previous version (after a failed verification or an orphan marker). + public const string Rollback = "Rollback"; +} + +/// +/// Explicit wire allowlist. The three legacy fields are the baseline ReportDTO; the optional +/// attribution trio (phase/errorCode/message) is accepted by the Investigate-enabled +/// GeneralSpace server and ignored by legacy servers (unknown JSON members are skipped), +/// so adding local diagnostic fields still cannot silently change the server API. +/// +internal record LegacyUpdateReport( + int RecordId, int Status, int Type, + string? Phase = null, string? ErrorCode = null, string? Message = null, string? AppKey = null); /// /// An HTTP POST-based update status reporter that serializes to JSON @@ -121,6 +155,9 @@ public class HttpUpdateReporter : IUpdateReporter private HttpClient _client; private string _reportUrl; + /// In-memory application credential; never stored in pending reports. + public string? AppKey { get; set; } + /// /// Gets or sets the report URL for update status reporting. /// When null or empty, is a no-op. @@ -165,8 +202,15 @@ public HttpUpdateReporter(HttpClient client, string reportUrl) _reportUrl = reportUrl ?? string.Empty; } - /// Sends the legacy payload; only a 2xx response acknowledges delivery. - /// An empty URL remains a no-op for direct callers; UpdateAttempt retains such reports as pending. + /// + /// Sends the wire payload (legacy trio + optional failure attribution); only a 2xx + /// response acknowledges delivery. + /// + /// + /// An empty URL remains a no-op for direct callers; UpdateAttempt retains such reports as + /// pending. The attribution trio maps from and + /// — legacy servers skip the unknown members. + /// /// The request fails or returns a non-success HTTP status. public async Task ReportAsync(UpdateReport report, CancellationToken token = default) { @@ -174,8 +218,13 @@ public async Task ReportAsync(UpdateReport report, CancellationToken token = def { if(string.IsNullOrWhiteSpace(_reportUrl)) return; - - var json = JsonSerializer.Serialize(new LegacyUpdateReport(report.RecordId, report.Status, report.Type), + + if (report.RequiresAppKey && string.IsNullOrWhiteSpace(AppKey)) + throw new InvalidOperationException("The pending report requires an app key."); + if (!string.IsNullOrEmpty(AppKey) && + (!Uri.TryCreate(_reportUrl, UriKind.Absolute, out var reportUri) || !IsSecureReportUri(reportUri))) + throw new InvalidOperationException("App key reporting requires HTTPS or an IP loopback HTTP endpoint."); + var json = JsonSerializer.Serialize(ToWire(report) with { AppKey = AppKey }, AttemptJsonContext.Default.LegacyUpdateReport); using var request = new HttpRequestMessage(HttpMethod.Post, _reportUrl); request.Content = new StringContent(json, Encoding.UTF8, "application/json"); @@ -187,11 +236,39 @@ public async Task ReportAsync(UpdateReport report, CancellationToken token = def using var response = await _client.SendAsync(request, token).ConfigureAwait(false); response.EnsureSuccessStatusCode(); + var body = await response.Content.ReadAsStringAsync().ConfigureAwait(false); + if (string.IsNullOrWhiteSpace(body) && string.IsNullOrEmpty(AppKey)) return; + using var document = JsonDocument.Parse(body); + var root = document.RootElement; + if (root.ValueKind != JsonValueKind.Object || + !root.TryGetProperty("code", out var code) || code.ValueKind != JsonValueKind.Number || + !code.TryGetInt32(out var codeValue) || codeValue != 200 || + !root.TryGetProperty("body", out var result) || result.ValueKind != JsonValueKind.True || + (root.TryGetProperty("isSuccess", out var success) + ? success.ValueKind != JsonValueKind.True + : !string.IsNullOrEmpty(AppKey))) + throw new HttpRequestException("Report endpoint did not acknowledge the update."); } + catch (Exception ex) { GeneralTracer.Warn($"Report failed: {ex.Message}"); throw; } } + + internal static bool IsSecureReportUri(Uri uri) => + uri.Scheme == Uri.UriSchemeHttps || + (uri.Scheme == Uri.UriSchemeHttp && IPAddress.TryParse(uri.Host, out var address) && IPAddress.IsLoopback(address)); + + /// + /// Wire projection: the server receives the record identity plus the failure attribution + /// (phase, exception type as the error code, redacted message). Everything else in + /// stays local evidence. + /// + internal static LegacyUpdateReport ToWire(UpdateReport report) => new( + report.RecordId, report.Status, report.Type, + Phase: string.IsNullOrWhiteSpace(report.Phase) ? null : report.Phase, + ErrorCode: string.IsNullOrWhiteSpace(report.Error?.ExceptionType) ? null : report.Error.ExceptionType, + Message: string.IsNullOrWhiteSpace(report.Error?.Message) ? null : report.Error.Message); } diff --git a/src/GeneralUpdate.Core/Download/Reporting/UpdateAttempt.cs b/src/GeneralUpdate.Core/Download/Reporting/UpdateAttempt.cs index b8a7c8b5..1f1155df 100644 --- a/src/GeneralUpdate.Core/Download/Reporting/UpdateAttempt.cs +++ b/src/GeneralUpdate.Core/Download/Reporting/UpdateAttempt.cs @@ -9,6 +9,8 @@ using System.Threading; using System.Threading.Tasks; using GeneralUpdate.Core.Configuration; +using GeneralUpdate.Core.Diagnostics; +using GeneralUpdate.Core.JsonContext; namespace GeneralUpdate.Core.Download.Reporting; @@ -59,6 +61,8 @@ public sealed class BowlReportConfiguration public int Type { get; set; } = 1; /// Name of an independently provisioned host credential environment variable, not its value. public string? CredentialEnvironmentVariable { get; set; } + /// Name of the environment variable containing the app key, never its value. + public string? AppKeyEnvironmentVariable { get; set; } } /// Immutable v1 request published before host startup; recovery must not depend on live IPC. @@ -88,6 +92,8 @@ public sealed class BowlRequest public int UpdateTimeoutSeconds { get; set; } = 600; /// Explicit permission for host-owned recovery from the existing backup snapshot. public bool AutoRollback { get; set; } + /// Opt-in crash evidence collection for the supervised application. + public bool CrashCollectionEnabled { get; set; } /// Optional legacy endpoint routing; the host owns monitored terminal delivery. public BowlReportConfiguration Report { get; set; } = new(); } @@ -121,7 +127,10 @@ public sealed class UpdateProducerState } // Source-generated metadata keeps the disk/HTTP contracts usable under trimming and Native AOT. -[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)] +// WhenWritingNull keeps the wire payload of a report without attribution byte-identical to the +// legacy {"recordId","status","type"} shape — the optional fields only appear when populated. +[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)] [JsonSerializable(typeof(BowlRequest))] [JsonSerializable(typeof(BowlReady))] [JsonSerializable(typeof(UpdateProducerState))] @@ -148,7 +157,10 @@ public sealed class UpdateAttempt : IDisposable // Publication of request.json transfers delivery ownership before the host can observe the attempt. private bool _ownsProducer; private UpdateFailure? _lastError; + private int _activeRecordId; + private int _activeReportType; private bool _failurePersisted; + private readonly string _diagnosticId = Guid.NewGuid().ToString("D"); private VersionEntry? _package; /// Attempt-specific directory containing immutable events and, when monitored, protocol files. public string DirectoryPath { get; } @@ -241,12 +253,27 @@ internal async Task StartMonitoringAsync(int recordId, int reportType) if (options.ReadyTimeoutSeconds <= 0 || options.UpdateTimeoutSeconds <= options.ReadyTimeoutSeconds || options.HealthTimeoutSeconds <= 0) throw new ArgumentOutOfRangeException(nameof(options), "Monitor timeouts must be positive; update timeout must exceed ready timeout."); + if (options.CrashCollectionEnabled && !IsSafeCrashVersion(_config.LastVersion)) + throw new ArgumentException("Crash collection requires a nonempty target version that is a safe directory name."); + if (options.AutoRollback && (_config.BackupEnabled == false || + string.IsNullOrWhiteSpace(_config.BackupDirectory) || !Directory.Exists(_config.BackupDirectory))) + throw new InvalidOperationException("Automatic monitored rollback requires an existing enabled backup."); + if (options.AutoRollback) + throw new InvalidOperationException("Automatic monitored rollback requires a verified write-ahead rollback plan, which this producer cannot yet provide."); if (!string.IsNullOrWhiteSpace(_config.ReportUrl)) { var uri = new Uri(_config.ReportUrl, UriKind.Absolute); if ((uri.Scheme != "http" && uri.Scheme != "https") || !string.IsNullOrEmpty(uri.UserInfo) || !string.IsNullOrEmpty(uri.Query) || !string.IsNullOrEmpty(uri.Fragment)) throw new ArgumentException("Bowl reporting URL must be HTTP(S), without credentials, query or fragment."); + if (!string.IsNullOrEmpty(options.AppKeyEnvironmentVariable) && !HttpUpdateReporter.IsSecureReportUri(uri)) + throw new ArgumentException("Bowl app key reporting requires HTTPS or an IP loopback HTTP endpoint."); + } + if (!string.IsNullOrEmpty(options.AppKeyEnvironmentVariable)) + { + var configuredKey = Environment.GetEnvironmentVariable(options.AppKeyEnvironmentVariable); + if (!string.IsNullOrEmpty(configuredKey) && !string.Equals(configuredKey, _config.AppSecretKey, StringComparison.Ordinal)) + throw new InvalidOperationException("Bowl app key environment variable does not match the verification credential."); } using var current = Process.GetCurrentProcess(); @@ -261,12 +288,13 @@ internal async Task StartMonitoringAsync(int recordId, int reportType) LaunchMode = options.VerifyLaunch && _config.LaunchClientAfterUpdate ? "processAlive" : "filesOnly", HealthTimeoutSeconds = options.HealthTimeoutSeconds, UpdateTimeoutSeconds = options.UpdateTimeoutSeconds, - AutoRollback = options.AutoRollback && _config.BackupEnabled != false && - Directory.Exists(_config.BackupDirectory), + AutoRollback = options.AutoRollback, + CrashCollectionEnabled = options.CrashCollectionEnabled, Report = new BowlReportConfiguration { Url = _config.ReportUrl, RecordId = recordId, Type = reportType, - CredentialEnvironmentVariable = options.CredentialEnvironmentVariable + CredentialEnvironmentVariable = options.CredentialEnvironmentVariable, + AppKeyEnvironmentVariable = options.AppKeyEnvironmentVariable } }; // Never replace a prior request: reusing an armed attempt must fail rather than adopt stale readiness. @@ -279,7 +307,7 @@ internal async Task StartMonitoringAsync(int recordId, int reportType) WorkingDirectory = Path.GetDirectoryName(options.ExecutablePath)!, Arguments = "--attempt " + _config.UpdateAttemptId + " --state-root " + QuoteArgument(_config.DiagnosticsDirectory!) }; - _host = Process.Start(info) ?? throw new InvalidOperationException("Bowl host did not start."); + _host = ProcessLauncher.Start(info) ?? throw new InvalidOperationException("Bowl host did not start."); var expected = ProcessIdentity.From(_host); var watch = Stopwatch.StartNew(); var readyPath = Path.Combine(DirectoryPath, "ready.json"); @@ -319,6 +347,29 @@ internal async Task StartMonitoringAsync(int recordId, int reportType) } } + internal static bool IsSafeCrashVersion(string? version) + { + if (string.IsNullOrWhiteSpace(version) || version.Length > 128 || version == "." || version == ".." || + version.EndsWith(".", StringComparison.Ordinal) || version.EndsWith(" ", StringComparison.Ordinal)) + return false; + foreach (var character in version) + if (character < 32 || "<>:\"/\\|?*".IndexOf(character) >= 0) + return false; + + var basename = version.Split('.')[0]; + if (string.Equals(basename, "CON", StringComparison.OrdinalIgnoreCase) || + string.Equals(basename, "PRN", StringComparison.OrdinalIgnoreCase) || + string.Equals(basename, "AUX", StringComparison.OrdinalIgnoreCase) || + string.Equals(basename, "NUL", StringComparison.OrdinalIgnoreCase)) + return false; + if (basename.Length == 4 && (basename.StartsWith("COM", StringComparison.OrdinalIgnoreCase) || + basename.StartsWith("LPT", StringComparison.OrdinalIgnoreCase)) && + ((basename[3] >= '1' && basename[3] <= '9') || basename[3] == '\u00b9' || + basename[3] == '\u00b2' || basename[3] == '\u00b3')) + return false; + return true; + } + /// Fail closed at update boundaries if a required monitor is unavailable. /// Client's in-place updater-package work precedes host ownership; only Update uses this monitor guard. internal void EnsureMonitorAlive() @@ -391,6 +442,8 @@ internal void RecordFailure(Exception error, string category = "updateFailure", try { Record("failed", preserveError ? null : error, category, failedPath); + if (_lastError?.Category == "updateFailure") + PublishFailureDiagnostics(); _failurePersisted = true; } catch (Exception persistenceError) @@ -399,11 +452,50 @@ internal void RecordFailure(Exception error, string category = "updateFailure", } } + private void PublishFailureDiagnostics() + { + var recordId = _package?.RecordId ?? 0; + if (recordId <= 0) recordId = _activeRecordId; + if (recordId <= 0) recordId = _config.UpdateVersions?.FirstOrDefault()?.RecordId ?? 0; + if (recordId <= 0) return; + var root = Path.Combine(_config.DiagnosticsDirectory!, "update-outbox", + InstallationIdentity.GetOrCreate(_config)); + ValidateExternalPath(root, _config); + Directory.CreateDirectory(root); + var destination = Path.Combine(root, _diagnosticId); + if (Directory.Exists(destination)) return; + var temporary = Path.Combine(root, "." + Guid.NewGuid().ToString("N") + ".tmp"); + try + { + Directory.CreateDirectory(temporary); + var phase = UpdatePhaseMapper.FromStage(_lastError?.Stage) ?? "Unknown"; + File.WriteAllText(Path.Combine(temporary, "diagnostic.txt"), + "Update failure\nPhase: " + phase + "\n"); + var manifest = new OutboxManifest + { + Schema = OutboxManifest.SupportedSchema, Guid = _diagnosticId, + Kind = DiagnosticsKinds.Update, CreatedAtUtc = DateTime.UtcNow, + RecordId = recordId, RecordType = _activeReportType == 0 ? _config.ReportType : _activeReportType, + Files = new System.Collections.Generic.List { "manifest.json", "diagnostic.txt" } + }; + WriteAtomic(Path.Combine(temporary, "manifest.json"), manifest, DiagnosticsJsonContext.Default.OutboxManifest, false); + Directory.Move(temporary, destination); + } + finally { if (Directory.Exists(temporary)) Directory.Delete(temporary, true); } + } + /// Snapshot known context; generate event identity once here, never during pending-report retries. internal UpdateReport CreateReport(int recordId, int status, int type) => new(recordId, status, type) { UpdateAttemptId = _config.UpdateAttemptId, Stage = Stage, + RequiresAppKey = !string.IsNullOrWhiteSpace(_config.AppSecretKey), + // Server-facing attribution (failure reports only): the originating failed operation + // (Error.Stage — pipeline middleware or stage tag) maps onto the ReportDTO phase; + // success reports carry no phase. + Phase = status == (int)UpdateStatus.Failure + ? UpdatePhaseMapper.FromStage(_lastError?.Stage) ?? UpdatePhaseMapper.FromStage(Stage) + : null, CurrentVersion = _config.ClientVersion, TargetVersion = _config.LastVersion, Error = _lastError, Role = _role, TimestampUtc = DateTimeOffset.UtcNow, EventId = Guid.NewGuid().ToString("D"), PackageName = _package?.Name, PackageVersion = _package?.Version, @@ -415,6 +507,13 @@ internal UpdateReport CreateReport(int recordId, int status, int type) => /// Capture which chain package is active before middleware can fail. internal void SetPackage(VersionEntry package) => _package = package; + internal void SetReportIdentity(int recordId, int reportType) + { + _package = null; + _activeRecordId = recordId; + _activeReportType = reportType; + } + /// Queue an unmonitored report durably before attempting its bounded, best-effort delivery. /// Monitored terminals belong to Bowl. Older pending events block immediate later sends to preserve ordering. internal async Task ReportAsync(IUpdateReporter reporter, int recordId, int status, int type) @@ -458,10 +557,18 @@ public static async Task RetryPendingReportsAsync(string attemptDirectory, IUpda /// Remove known configured credentials from the new journal, not arbitrary secrets embedded in user exceptions. /// Local diagnostics still require restricted access; this is not an authorization to upload stack traces. - private string? Redact(string? value) + private string? Redact(string? value) => Redact(value, _config); + + /// + /// Shared credential redaction for server-facing evidence built outside this journal — + /// e.g. the self-check verdict reason that both the Startup report and the + /// rollback report embed on the wire. + /// + /// Remove known configured credentials, not arbitrary secrets embedded in user exceptions. + internal static string? Redact(string? value, UpdateContext config) { if (value == null) return null; - foreach (var secret in new[] { _config.Token, _config.AppSecretKey, _config.BasicPassword }) + foreach (var secret in new[] { config.Token, config.AppSecretKey, config.BasicPassword }) if (!string.IsNullOrEmpty(secret)) value = value.Replace(secret, "[REDACTED]"); return value; } diff --git a/src/GeneralUpdate.Core/Download/Reporting/UpdatePhaseMapper.cs b/src/GeneralUpdate.Core/Download/Reporting/UpdatePhaseMapper.cs new file mode 100644 index 00000000..4b68d438 --- /dev/null +++ b/src/GeneralUpdate.Core/Download/Reporting/UpdatePhaseMapper.cs @@ -0,0 +1,43 @@ +using System; +using System.Collections.Generic; + +namespace GeneralUpdate.Core.Download.Reporting; + +/// +/// Maps the local attempt-stage vocabulary onto the server-facing failure phases +/// ( — the GeneralSpace ReportDTO vocabulary). Two source +/// vocabularies feed it: the attempt lifecycle stages (downloading, +/// validating, filesApplying, …) and the pipeline middleware class names +/// the pipeline builder stamps into ex.Data["UpdateStage"]. +/// +public static class UpdatePhaseMapper +{ + private static readonly Dictionary Map = new(StringComparer.OrdinalIgnoreCase) + { + // Attempt lifecycle stages. + ["downloading"] = UpdatePhases.Download, + ["downloaded"] = UpdatePhases.Download, + ["validating"] = UpdatePhases.Verify, + ["decompressing"] = UpdatePhases.Extract, + ["backup"] = UpdatePhases.Apply, + ["manifest"] = UpdatePhases.Apply, + ["filesApplying"] = UpdatePhases.Apply, + ["filesApplied"] = UpdatePhases.Apply, + ["launching"] = UpdatePhases.Startup, + ["launchingUpdater"] = UpdatePhases.Startup, + ["awaitingHealth"] = UpdatePhases.Startup, + + // Pipeline middleware class names (PipelineBuilder failure tagging). + ["HashMiddleware"] = UpdatePhases.Verify, + ["CompressMiddleware"] = UpdatePhases.Extract, + ["PatchMiddleware"] = UpdatePhases.Apply, + }; + + /// + /// Resolves the server-facing phase for a local stage marker; null when the + /// stage has no unambiguous server meaning (preparing, handedOff, failed, …) — the + /// server then classifies the failure as Unknown instead of guessing. + /// + public static string? FromStage(string? stage) + => stage != null && Map.TryGetValue(stage, out var phase) ? phase : null; +} diff --git a/src/GeneralUpdate.Core/Download/Sources/HttpDownloadSource.cs b/src/GeneralUpdate.Core/Download/Sources/HttpDownloadSource.cs index e0510c85..b324fac6 100644 --- a/src/GeneralUpdate.Core/Download/Sources/HttpDownloadSource.cs +++ b/src/GeneralUpdate.Core/Download/Sources/HttpDownloadSource.cs @@ -48,6 +48,8 @@ public class HttpDownloadSource : Abstractions.IDownloadSource private readonly Security.AuthScheme _authScheme; private readonly string? _basicUsername; private readonly string? _basicPassword; + /// Stable installation identity for server-side distinct-device failure counting. + public string? DeviceId { get; set; } /// /// Initializes a new instance of the class @@ -120,15 +122,15 @@ public HttpDownloadSource( /// public async Task ListAsync(CancellationToken token = default) { - var mainResp = await VersionService.Validate( + var mainResp = await VersionService.ValidateWithDeviceId( _updateUrl, _clientVersion, AppType.Client, _appSecretKey, _platform, _productId, - _scheme, _token, _authScheme, _basicUsername, _basicPassword, token); + _scheme, _token, _authScheme, _basicUsername, _basicPassword, token, DeviceId).ConfigureAwait(false); - var upgradeResp = await VersionService.Validate( + var upgradeResp = await VersionService.ValidateWithDeviceId( _updateUrl, _upgradeClientVersion ?? _clientVersion, AppType.Upgrade, _appSecretKey, _platform, _productId, - _scheme, _token, _authScheme, _basicUsername, _basicPassword, token); + _scheme, _token, _authScheme, _basicUsername, _basicPassword, token, DeviceId).ConfigureAwait(false); // Check that returned VersionEntry items' AppType matches the requested type, // rather than just checking Count > 0. The server may return items whose diff --git a/src/GeneralUpdate.Core/Event/EventManager.cs b/src/GeneralUpdate.Core/Event/EventManager.cs index 84a4ffeb..88dad5d5 100644 --- a/src/GeneralUpdate.Core/Event/EventManager.cs +++ b/src/GeneralUpdate.Core/Event/EventManager.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Concurrent; +using System.Collections.Generic; namespace GeneralUpdate.Core.Event { @@ -91,13 +92,25 @@ public void RemoveListener(Action listener) wher { if (listener == null) throw new ArgumentNullException(nameof(listener)); var type = typeof(Action); - if (_dicDelegates.TryGetValue(type, out var existing)) + // CAS retry loop: TryGetValue → TryUpdate is not atomic — a concurrent + // AddListener combining onto the same delegate between the two steps made the + // removal vanish. Retry until our removal lands on a current value or the + // entry disappears. + while (_dicDelegates.TryGetValue(type, out var existing)) { var updated = Delegate.Remove(existing, listener); if (updated == null) - _dicDelegates.TryRemove(type, out _); - else - _dicDelegates.TryUpdate(type, updated, existing); + { + // Entry is empty only if no writer raced us; on race, retry from the + // fresh value (the entry now holds a combined delegate again). + // ICollection.Remove on ConcurrentDictionary is an atomic + // value-comparing remove. + if (((ICollection>)_dicDelegates) + .Remove(new KeyValuePair(type, existing))) + return; + } + else if (_dicDelegates.TryUpdate(type, updated, existing)) + return; } } diff --git a/src/GeneralUpdate.Core/FileSystem/StorageManager.cs b/src/GeneralUpdate.Core/FileSystem/StorageManager.cs index a824be6f..fc86e01d 100644 --- a/src/GeneralUpdate.Core/FileSystem/StorageManager.cs +++ b/src/GeneralUpdate.Core/FileSystem/StorageManager.cs @@ -762,7 +762,12 @@ private static void CleanDirectories(string rootPath, int keepVersions, string s .Skip(keepVersions); foreach (var dir in dirs) - dir.Delete(true); + { + // Use the fault-tolerant delete (attribute reset + per-entry retry) rather + // than DirectoryInfo.Delete(true): a single read-only/locked file inside an + // old backup must not fail the surrounding update flow. + DeleteDirectory(dir.FullName); + } } /// diff --git a/src/GeneralUpdate.Core/GeneralUpdate.Core.csproj b/src/GeneralUpdate.Core/GeneralUpdate.Core.csproj index 9b58d14f..06c44a7e 100644 --- a/src/GeneralUpdate.Core/GeneralUpdate.Core.csproj +++ b/src/GeneralUpdate.Core/GeneralUpdate.Core.csproj @@ -20,6 +20,12 @@ + + + + + + diff --git a/src/GeneralUpdate.Core/GracefulExit.cs b/src/GeneralUpdate.Core/GracefulExit.cs index ec3f75ca..d1fe62ce 100644 --- a/src/GeneralUpdate.Core/GracefulExit.cs +++ b/src/GeneralUpdate.Core/GracefulExit.cs @@ -1,5 +1,6 @@ using System; using System.Diagnostics; +using System.Threading; using System.Threading.Tasks; namespace GeneralUpdate.Core; @@ -26,16 +27,13 @@ public static class GracefulExit public static async Task ShutdownAsync(Process? process, int timeoutMs = 3000) { if (process == null || process.HasExited) return; - if (process.CloseMainWindow()) - { - // CloseMainWindow sent a WM_CLOSE — give the process time to shut down. - await Task.Delay(timeoutMs).ConfigureAwait(false); - } - else - { - // Process has no main window (e.g. console app) — still give it time. - await Task.Delay(timeoutMs).ConfigureAwait(false); - } + // CloseMainWindow works only for GUI processes with a main window; for console + // apps it is a no-op. Either way, poll instead of sleeping the full timeout so a + // prompt exit is not penalized with the whole grace period on every update cycle. + process.CloseMainWindow(); + var deadline = DateTime.UtcNow.AddMilliseconds(timeoutMs); + while (!process.HasExited && DateTime.UtcNow < deadline) + await Task.Delay(100, CancellationToken.None).ConfigureAwait(false); if (!process.HasExited) process.Kill(); // Last resort } diff --git a/src/GeneralUpdate.Core/Hooks/IUpdateHooks.cs b/src/GeneralUpdate.Core/Hooks/IUpdateHooks.cs index 60d83560..1dff4c4b 100644 --- a/src/GeneralUpdate.Core/Hooks/IUpdateHooks.cs +++ b/src/GeneralUpdate.Core/Hooks/IUpdateHooks.cs @@ -61,20 +61,20 @@ public async Task OnBeforeStartAppAsync(HookContext ctx) RedirectStandardOutput = true, RedirectStandardError = true }; - using var proc = Process.Start(psi); + using var proc = ProcessLauncher.Start(psi); if (proc == null) { GeneralTracer.Warn($"UnixPermissionHooks: chmod process could not be started for {mainApp}."); return; } - await Task.Run(() => proc.WaitForExit()); + await Task.Run(() => proc.WaitForExit()).ConfigureAwait(false); exitCode = proc.ExitCode; #else // netstandard2.0 fallback: path is double-quoted to mitigate injection risk. // ArgumentList is unavailable, so we rely on the quoting and the fact that // chmod +x with an extra argument is not exploitable beyond a file-not-found error. - using var proc = Process.Start("chmod", $"+x \"{mainApp}\""); - await Task.Run(() => proc.WaitForExit()); + using var proc = ProcessLauncher.Start("chmod", $"+x \"{mainApp}\""); + await Task.Run(() => proc.WaitForExit()).ConfigureAwait(false); exitCode = proc.ExitCode; #endif if (exitCode != 0) @@ -99,8 +99,8 @@ public async Task OnBeforeStartAppAsync(HookContext ctx) { RedirectStandardOutput = true, RedirectStandardError = true }; - using var proc = Process.Start(psi)!; - await Task.Run(() => proc.WaitForExit()); + using var proc = ProcessLauncher.Start(psi)!; + await Task.Run(() => proc.WaitForExit()).ConfigureAwait(false); if (proc.ExitCode != 0) throw new InvalidOperationException( $"Permission script '{_scriptPath}' failed (exit {proc.ExitCode})"); diff --git a/src/GeneralUpdate.Core/Hubs/UpgradeHubService.cs b/src/GeneralUpdate.Core/Hubs/UpgradeHubService.cs index 910e512c..2d956809 100644 --- a/src/GeneralUpdate.Core/Hubs/UpgradeHubService.cs +++ b/src/GeneralUpdate.Core/Hubs/UpgradeHubService.cs @@ -67,7 +67,7 @@ public async Task StartAsync() return; } GeneralTracer.Info($"UpgradeHubService.StartAsync: connecting to SignalR hub. State={_connection?.State}"); - await _connection.StartAsync(); + await _connection.StartAsync().ConfigureAwait(false); GeneralTracer.Info($"UpgradeHubService.StartAsync: SignalR hub connection established. State={_connection?.State}"); } @@ -81,7 +81,7 @@ public async Task StopAsync() try { GeneralTracer.Info($"UpgradeHubService.StopAsync: stopping SignalR hub connection. State={_connection?.State}"); - await _connection.StopAsync(); + await _connection.StopAsync().ConfigureAwait(false); GeneralTracer.Info("UpgradeHubService.StopAsync: SignalR hub connection stopped."); } catch (Exception e) @@ -99,7 +99,7 @@ public async Task DisposeAsync() if (_connection != null) { GeneralTracer.Info("UpgradeHubService.DisposeAsync: disposing SignalR hub connection and releasing resources."); - await _connection.DisposeAsync(); + await _connection.DisposeAsync().ConfigureAwait(false); _connection = null; GeneralTracer.Info("UpgradeHubService.DisposeAsync: SignalR hub connection disposed."); } diff --git a/src/GeneralUpdate.Core/Ipc/IpcEncryption.cs b/src/GeneralUpdate.Core/Ipc/IpcEncryption.cs index dc8852cb..17b004ce 100644 --- a/src/GeneralUpdate.Core/Ipc/IpcEncryption.cs +++ b/src/GeneralUpdate.Core/Ipc/IpcEncryption.cs @@ -13,8 +13,10 @@ public static class IpcEncryption { /// /// AES-CBC encrypt and write to . - /// Uses so that a concurrent receiver can begin reading - /// before this writer closes the handle. + /// The payload is written to a sibling temp file first and atomically published, so a + /// reader never observes a truncated ciphertext or a missing contract file if the writer + /// crashes midway ( swaps in one OS operation when the + /// destination exists; covers first publication). /// public static void EncryptToFile(byte[] plainBytes, string filePath, byte[] key, byte[] iv) { @@ -24,14 +26,30 @@ public static void EncryptToFile(byte[] plainBytes, string filePath, byte[] key, using var encryptor = aes.CreateEncryptor(); var cipher = encryptor.TransformFinalBlock(plainBytes, 0, plainBytes.Length); - using var fs = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.Read); - fs.Write(cipher, 0, cipher.Length); + var tempPath = filePath + ".tmp-" + Guid.NewGuid().ToString("N"); + try + { + using (var fs = new FileStream(tempPath, FileMode.CreateNew, FileAccess.Write, FileShare.None)) + { + fs.Write(cipher, 0, cipher.Length); + } + // File.Move(src, dst, overwrite) is unavailable on netstandard2.0. + if (File.Exists(filePath)) File.Replace(tempPath, filePath, null); + else File.Move(tempPath, filePath); + } + catch + { + try { File.Delete(tempPath); } catch { /* best-effort cleanup */ } + throw; + } } /// /// Read, AES-CBC decrypt, and auto-delete the file at . - /// Returns null if the file does not exist or cannot be accessed (e.g. locked - /// by a concurrent process — common during parallel test execution). + /// Returns null if the file does not exist, cannot be accessed (e.g. locked + /// by a concurrent process — common during parallel test execution), or cannot be + /// decrypted (truncated/corrupted ciphertext, wrong key — e.g. a leftover file from + /// another product since the file name is shared). /// public static byte[]? DecryptFromFile(string filePath, byte[] key, byte[] iv) { @@ -69,6 +87,13 @@ public static void EncryptToFile(byte[] plainBytes, string filePath, byte[] key, using var decryptor = aes.CreateDecryptor(); return decryptor.TransformFinalBlock(cipher, 0, cipher.Length); } + catch (CryptographicException) + { + // Corrupted/truncated ciphertext or a key mismatch must not escape as an + // exception: callers treat "null" as "no IPC data available" and the updater + // degrades gracefully instead of crashing with a confusing stack. + return null; + } finally { try { File.Delete(filePath); } catch { /* best-effort cleanup */ } diff --git a/src/GeneralUpdate.Core/JsonContext/DiagnosticsJsonContext.cs b/src/GeneralUpdate.Core/JsonContext/DiagnosticsJsonContext.cs index 7c140c41..9ddacea1 100644 --- a/src/GeneralUpdate.Core/JsonContext/DiagnosticsJsonContext.cs +++ b/src/GeneralUpdate.Core/JsonContext/DiagnosticsJsonContext.cs @@ -1,4 +1,5 @@ using System.Text.Json.Serialization; +using System.Collections.Generic; using GeneralUpdate.Core.Diagnostics; using GeneralUpdate.Core.SelfCheck; @@ -10,6 +11,7 @@ namespace GeneralUpdate.Core.JsonContext; /// server, plus the serialized self-check / rollback results embedded in real-time bundles. /// [JsonSerializable(typeof(OutboxManifest))] +[JsonSerializable(typeof(List))] [JsonSerializable(typeof(DiagnosticsManifest))] [JsonSerializable(typeof(SelfCheckReport))] [JsonSerializable(typeof(RollbackResult))] diff --git a/src/GeneralUpdate.Core/Network/VersionService.cs b/src/GeneralUpdate.Core/Network/VersionService.cs index ee7227c2..142bc22a 100644 --- a/src/GeneralUpdate.Core/Network/VersionService.cs +++ b/src/GeneralUpdate.Core/Network/VersionService.cs @@ -143,9 +143,14 @@ public VersionService(IHttpAuthProvider? authProvider = null, TimeSpan? requestT public static Task Validate(string url, string version, AppType appType, string appKey, PlatformType platform, string productId, string scheme = null, string token = null, Security.AuthScheme authScheme = Security.AuthScheme.Hmac, string basicUsername = null, string basicPassword = null, CancellationToken ct = default) + => ValidateWithDeviceId(url, version, appType, appKey, platform, productId, scheme, token, authScheme, basicUsername, basicPassword, ct, null); + + internal static Task ValidateWithDeviceId(string url, string version, + AppType appType, string appKey, PlatformType platform, string productId, + string scheme, string token, Security.AuthScheme authScheme, string basicUsername, string basicPassword, CancellationToken ct, string deviceId) { var auth = HttpClientProvider.DefaultAuthProvider ?? HttpAuthProviderFactory.Create(scheme, token, appKey, authScheme, basicUsername, basicPassword); - return new VersionService(auth).ValidateAsync(url, version, (int)appType, appKey, (int)platform, productId, ct); + return new VersionService(auth).ValidateAsync(url, version, (int)appType, appKey, (int)platform, productId, ct, deviceId); } /// @@ -200,9 +205,10 @@ public static Task Validate(string url, string version, /// A for cancelling the operation. /// A containing the version validation result. private async Task ValidateAsync(string url, string v, int at, string appKey, int pf, string pid, - CancellationToken t = default) + CancellationToken t = default, string deviceId = null) { var p = new Dictionary { ["version"] = v, ["appType"] = at, ["appKey"] = appKey, ["platform"] = pf, ["productId"] = pid }; + if (!string.IsNullOrEmpty(deviceId)) p["deviceId"] = deviceId; return await PostAsync(url, p, VersionRespJsonContext.Default.VersionRespDTO, t); } @@ -340,8 +346,14 @@ private async Task SendAsync(string url, Dictionary p, /// private static bool ShouldRetry(Exception ex) { + // TaskCanceledException derives from OperationCanceledException, so it must be + // tested before the cancellation check: a request timeout surfaces as + // TaskCanceledException wrapping a TimeoutException and IS retryable, while a + // caller-initiated cancellation has no inner exception and is not. + if (ex is TaskCanceledException tce) + return tce.InnerException is TimeoutException; + if (ex is TimeoutException or System.IO.IOException) return true; if (ex is OperationCanceledException) return false; - if (ex is TaskCanceledException or TimeoutException or System.IO.IOException) return true; if (ex is HttpRequestException h && (h.Message ?? "").Contains("timeout", StringComparison.OrdinalIgnoreCase)) return true; return false; } diff --git a/src/GeneralUpdate.Core/Pipeline/DiffPipeline.cs b/src/GeneralUpdate.Core/Pipeline/DiffPipeline.cs index 15caa93d..a9f1e8ea 100644 --- a/src/GeneralUpdate.Core/Pipeline/DiffPipeline.cs +++ b/src/GeneralUpdate.Core/Pipeline/DiffPipeline.cs @@ -225,23 +225,57 @@ public async Task CleanAsync( int completed = 0; using var semaphore = new SemaphoreSlim(_options.MaxDegreeOfParallelism); + // O(1) old-version lookup by relative path: Match() used to scan the whole + // left-node list for every changed file (O(n²) string comparisons on large trees). + // Restricted to the EXACT default matcher — custom implementations and subclasses + // remain authoritative (a custom Match may deliberately return null to package a + // file whole or select a different baseline, and must not be bypassed by an index hit). + var useRelativeIndex = _cleanMatcher.GetType() == typeof(DefaultCleanMatcher); + var leftIndex = useRelativeIndex + ? new Dictionary(leftNodes.Count, StringComparer.OrdinalIgnoreCase) + : null; + if (leftIndex != null) + { + foreach (var node in leftNodes) + { + // First writer wins on duplicate relative paths (Dictionary.TryAdd is + // unavailable on netstandard2.0). + if (!string.IsNullOrWhiteSpace(node.RelativePath) && + !leftIndex.ContainsKey(NormalizeRelative(node.RelativePath))) + leftIndex[NormalizeRelative(node.RelativePath)] = node; + } + } + var tasks = differentFiles.Select(file => Task.Run(async () => { - await semaphore.WaitAsync(cancellationToken); + await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false); try { cancellationToken.ThrowIfCancellationRequested(); var tempDir = GetTempDirectory(file, targetPath, patchPath); - var oldFile = _cleanMatcher.Match(file, leftNodes); + var oldFile = (leftIndex != null && + file.RelativePath != null && + leftIndex.TryGetValue(NormalizeRelative(file.RelativePath), out var indexed)) + ? indexed + : _cleanMatcher.Match(file, leftNodes); if (oldFile != null) { - if (!StorageManager.HashEquals(oldFile.FullName, file.FullName)) + // Decide from the hashes Compare already computed (in-memory string + // compare, zero I/O); HashEquals re-read BOTH files in full and was + // the dominant cost of patch generation on large directories. Fall + // back to the full comparison only when a hash is missing. + var needsPatch = !string.IsNullOrEmpty(oldFile.Hash) && !string.IsNullOrEmpty(file.Hash) + ? !string.Equals(oldFile.Hash, file.Hash, StringComparison.OrdinalIgnoreCase) + : !StorageManager.HashEquals(oldFile.FullName, file.FullName); + + if (needsPatch) { ValidateFileSize(oldFile.FullName, file.FullName); var tempPatchPath = Path.Combine(tempDir, $"{file.Name}{PatchExtension}"); - await _binaryDiffer.CleanAsync(oldFile.FullName, file.FullName, tempPatchPath, cancellationToken); + await _binaryDiffer.CleanAsync(oldFile.FullName, file.FullName, tempPatchPath, cancellationToken) + .ConfigureAwait(false); } } else @@ -267,7 +301,7 @@ public async Task CleanAsync( } }, cancellationToken)); - await Task.WhenAll(tasks); + await Task.WhenAll(tasks).ConfigureAwait(false); var exceptFiles = _cleanMatcher.Except(sourcePath, targetPath)?.ToList(); if (exceptFiles is { Count: > 0 }) @@ -332,14 +366,14 @@ public async Task DirtyAsync( var patchFiles = StorageManager.GetAllFiles(patchPath, skipDirectory).ToList(); var oldFiles = StorageManager.GetAllFiles(appPath, skipDirectory).ToList(); - HandleDeleteList(patchFiles, oldFiles); + HandleDeleteList(patchFiles, oldFiles, appPath); oldFiles = StorageManager.GetAllFiles(appPath, skipDirectory).ToList(); int total = oldFiles.Count; if (total == 0) { reporter?.Report(DiffProgress.Complete(0)); - await CopyUnknownFiles(appPath, patchPath); + await CopyUnknownFiles(appPath, patchPath).ConfigureAwait(false); return; } @@ -356,11 +390,11 @@ public async Task DirtyAsync( var tasks = matchedPairs.Select(pair => Task.Run(async () => { - await semaphore.WaitAsync(cancellationToken); + await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false); try { cancellationToken.ThrowIfCancellationRequested(); - await ApplyPatch(pair.OldFile.FullName, pair.PatchFile.FullName, cancellationToken); + await ApplyPatch(pair.OldFile.FullName, pair.PatchFile.FullName, cancellationToken).ConfigureAwait(false); int done = Interlocked.Increment(ref completed); reporter?.Report(new DiffProgress(done, total, pair.OldFile.Name)); @@ -380,7 +414,7 @@ public async Task DirtyAsync( } }, cancellationToken)); - await Task.WhenAll(tasks); + await Task.WhenAll(tasks).ConfigureAwait(false); reporter?.Report(DiffProgress.Complete(total)); await CopyUnknownFiles(appPath, patchPath); } @@ -417,7 +451,7 @@ private async Task ApplyPatch(string appFilePath, string patchFilePath, Cancella Path.GetDirectoryName(appFilePath)!, $"{Path.GetRandomFileName()}_{Path.GetFileName(appFilePath)}"); - await _binaryDiffer.DirtyAsync(appFilePath, tempPath, patchFilePath, ct); + await _binaryDiffer.DirtyAsync(appFilePath, tempPath, patchFilePath, ct).ConfigureAwait(false); if (File.Exists(tempPath)) { @@ -447,7 +481,7 @@ private async Task ApplyPatch(string appFilePath, string patchFilePath, Cancella /// deletion failures caused by read-only attributes. /// /// - private static void HandleDeleteList(IEnumerable patchFiles, List oldFiles) + private static void HandleDeleteList(IEnumerable patchFiles, List oldFiles, string appPath) { var json = patchFiles.FirstOrDefault(i => i.Name.Equals(DeleteListFileName, StringComparison.OrdinalIgnoreCase)); if (json == null) return; @@ -455,16 +489,6 @@ private static void HandleDeleteList(IEnumerable patchFiles, List>(json.FullName, FileNodesJsonContext.Default.ListFileNode); if (deleteFiles == null) return; - // Build a HashSet of delete-manifest hashes (hex strings from FileNode.Hash) - // so each oldFile is checked in O(1) instead of O(n × m). - var deleteHashes = new HashSet(StringComparer.OrdinalIgnoreCase); - foreach (var del in deleteFiles) - { - if (!string.IsNullOrEmpty(del.Hash)) - deleteHashes.Add(del.Hash); - } - if (deleteHashes.Count == 0) return; - // Exclude .patch files from oldFiles — they are patch input, not app files. var appFiles = oldFiles .Where(f => !Path.GetExtension(f.FullName) @@ -472,13 +496,51 @@ private static void HandleDeleteList(IEnumerable patchFiles, List(pathComparer); + var deleteHashes = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (var del in deleteFiles) + { + if (!string.IsNullOrWhiteSpace(del.RelativePath)) + { + var raw = NormalizeRelativePath(del.RelativePath); + deleteRelativePaths.Add(raw); + // StorageManager-relative paths are URI-escaped (Uri.MakeRelativeUri), e.g. + // "plugins/lib#1.dll" stored as "plugins/lib%231.dll", while paths computed + // from the file system are literal. Index the decoded form as well so both + // representations match; keeping the raw form preserves compatibility with + // manifests that already hold literal paths and names containing '%' themselves. + var decoded = Uri.UnescapeDataString(raw); + if (!string.Equals(decoded, raw, StringComparison.Ordinal)) + deleteRelativePaths.Add(decoded); + } + if (!string.IsNullOrEmpty(del.Hash)) + deleteHashes.Add(del.Hash); + } + var hashAlgorithm = new Sha256HashAlgorithm(); foreach (var file in appFiles) { if (!File.Exists(file.FullName)) continue; - var fileHash = hashAlgorithm.ComputeHash(file.FullName); - if (fileHash != null && deleteHashes.Contains(fileHash)) + var relative = NormalizeRelativePath( + ComputeRelativePath(appPath, file.FullName)); + var delete = deleteRelativePaths.Contains(relative); + if (!delete && !deleteRelativePaths.Any()) + { + // Manifest without relative paths (legacy) — fall back to content hash. + var fileHash = hashAlgorithm.ComputeHash(file.FullName); + delete = fileHash != null && deleteHashes.Contains(fileHash); + } + if (delete) { File.SetAttributes(file.FullName, FileAttributes.Normal); File.Delete(file.FullName); @@ -486,6 +548,31 @@ private static void HandleDeleteList(IEnumerable patchFiles, List path.Trim().Replace('\\', '/').TrimStart('/'); + + /// Clean-side alias of the normalizer (shared by the left-node index). + private static string NormalizeRelative(string path) => NormalizeRelativePath(path); + + /// + /// Path.GetRelativePath is unavailable on netstandard2.0; strip the app directory + /// prefix directly (falling back to the file name when the file sits outside it). + /// Both paths are canonicalized first: DirtyAsync accepts relative app paths + /// (or ones containing "." segments) while the enumerated FullName values are + /// absolute — a non-canonical base fails the prefix test and reduces every path to + /// a bare file name, which then never matches the deletion manifest. + /// + private static string ComputeRelativePath(string basePath, string fullPath) + { + var baseTrimmed = Path.GetFullPath(basePath).TrimEnd('\\', '/'); + var canonicalPath = Path.GetFullPath(fullPath); + if (canonicalPath.Length > baseTrimmed.Length && + canonicalPath.StartsWith(baseTrimmed, StringComparison.OrdinalIgnoreCase) && + (canonicalPath[baseTrimmed.Length] == '\\' || canonicalPath[baseTrimmed.Length] == '/')) + return canonicalPath.Substring(baseTrimmed.Length + 1); + return Path.GetFileName(fullPath); + } + /// /// Copies new files from the patch directory (files not present in the old version) to the application /// directory, then cleans up the patch directory. diff --git a/src/GeneralUpdate.Core/Pipeline/HashMiddleware.cs b/src/GeneralUpdate.Core/Pipeline/HashMiddleware.cs index 01358f53..17cb9865 100644 --- a/src/GeneralUpdate.Core/Pipeline/HashMiddleware.cs +++ b/src/GeneralUpdate.Core/Pipeline/HashMiddleware.cs @@ -60,7 +60,7 @@ public async Task InvokeAsync(PipelineContext context) GeneralTracer.Info($"HashMiddleware.InvokeAsync: verifying hash for file={path}, expectedHash={hash}"); try { - var isVerify = await VerifyFileHash(path, hash); + var isVerify = await VerifyFileHash(path, hash).ConfigureAwait(false); if (!isVerify) { GeneralTracer.Error($"HashMiddleware.InvokeAsync: hash verification failed for file={path}."); diff --git a/src/GeneralUpdate.Core/ProcessLauncher.cs b/src/GeneralUpdate.Core/ProcessLauncher.cs new file mode 100644 index 00000000..1c56071d --- /dev/null +++ b/src/GeneralUpdate.Core/ProcessLauncher.cs @@ -0,0 +1,28 @@ +using System.Diagnostics; + +namespace GeneralUpdate.Core; + +/// +/// Spawns processes via the instance member. The static +/// Start overloads of are avoided project-wide: security +/// linting flags that call form regardless of how its arguments were built, +/// while this instance form carries identical semantics (a failed start throws; +/// the null return is unreachable without UseShellExecute, and preserved for +/// call-site parity). +/// +internal static class ProcessLauncher +{ + /// Starts the process described by . + internal static Process? Start(ProcessStartInfo startInfo) + { + var process = new Process { StartInfo = startInfo }; + return process.Start() ? process : null; + } + + /// Starts an executable by path (shell execution disabled, matching the static overload). + internal static Process? Start(string fileName) => Start(new ProcessStartInfo(fileName)); + + /// Starts an executable with arguments (shell execution disabled, matching the static overload). + internal static Process? Start(string fileName, string arguments) => + Start(new ProcessStartInfo(fileName, arguments) { UseShellExecute = false }); +} diff --git a/src/GeneralUpdate.Core/SelfCheck/ProcessLaunchRule.cs b/src/GeneralUpdate.Core/SelfCheck/ProcessLaunchRule.cs index 3015e993..b6b8712d 100644 --- a/src/GeneralUpdate.Core/SelfCheck/ProcessLaunchRule.cs +++ b/src/GeneralUpdate.Core/SelfCheck/ProcessLaunchRule.cs @@ -64,7 +64,7 @@ public async Task CheckAsync(SelfCheckContext ctx, Cancella try { - process = Process.Start(new ProcessStartInfo(appPath) { UseShellExecute = true }); + process = ProcessLauncher.Start(new ProcessStartInfo(appPath) { UseShellExecute = true }); } catch (Exception ex) { diff --git a/src/GeneralUpdate.Core/SelfCheck/RollbackManager.cs b/src/GeneralUpdate.Core/SelfCheck/RollbackManager.cs index e5c4cb59..cd84ab40 100644 --- a/src/GeneralUpdate.Core/SelfCheck/RollbackManager.cs +++ b/src/GeneralUpdate.Core/SelfCheck/RollbackManager.cs @@ -7,6 +7,8 @@ using GeneralUpdate.Core.Diagnostics; using GeneralUpdate.Core.FileSystem; using IUpdateReporter = GeneralUpdate.Core.Download.Reporting.IUpdateReporter; +using UpdateFailure = GeneralUpdate.Core.Download.Reporting.UpdateFailure; +using UpdatePhases = GeneralUpdate.Core.Download.Reporting.UpdatePhases; using UpdateReport = GeneralUpdate.Core.Download.Reporting.UpdateReport; using UpdateStatus = GeneralUpdate.Core.Download.Reporting.UpdateStatus; @@ -68,19 +70,21 @@ public sealed class RollbackManager { private readonly string _installPath; private readonly IUpdateReporter _reporter; - private readonly IDiagnosticsUploader? _diagnosticsUploader; + private readonly DiagnosticsChannel? _diagnostics; /// Installation root the rollback restores into. /// Status reporter used for the Failure report. - /// + /// /// Optional diagnostics channel; when set, a rollback diagnostic bundle is collected and - /// uploaded in real time. Failures are logged, never propagated. + /// uploaded in real time. The channel carries the uploader AND the runtime options + + /// privacy filter, so real-time bundles pack under the same size cap and blacklist as + /// outbox evidence. Failures are logged, never propagated. /// - public RollbackManager(string installPath, IUpdateReporter reporter, IDiagnosticsUploader? diagnosticsUploader = null) + public RollbackManager(string installPath, IUpdateReporter reporter, DiagnosticsChannel? diagnostics = null) { _installPath = installPath ?? throw new ArgumentNullException(nameof(installPath)); _reporter = reporter ?? throw new ArgumentNullException(nameof(reporter)); - _diagnosticsUploader = diagnosticsUploader; + _diagnostics = diagnostics; } /// Executes the rollback sequence. Never throws for step failures; returns the aggregate outcome. @@ -193,8 +197,18 @@ private async Task ReportFailureAsync(RollbackRequest req) { try { - await _reporter.ReportAsync( - new UpdateReport(req.RecordId, (int)UpdateStatus.Failure, req.ReportType)).ConfigureAwait(false); + // Server-facing attribution: the rollback IS the failure evidence of the startup + // phase it rolled back (GeneralSpace ReportDTO optional fields — phase="Rollback", + // message=first self-check failure). Legacy servers ignore the extra JSON members. + await _reporter.ReportAsync(new UpdateReport(req.RecordId, (int)UpdateStatus.Failure, req.ReportType) + { + Phase = UpdatePhases.Rollback, + Error = new UpdateFailure + { + Category = "healthCheckFailure", + Message = TruncateReason(req.Reason), + } + }).ConfigureAwait(false); } catch (Exception ex) { @@ -205,12 +219,13 @@ await _reporter.ReportAsync( private async Task UploadDiagnosticsAsync( RollbackRequest req, bool filesRestored, bool manifestReverted, CancellationToken ct) { - if (_diagnosticsUploader == null || !_diagnosticsUploader.IsConfigured) + if (_diagnostics == null || !_diagnostics.IsUsable) return; try { - var collector = new DiagnosticsCollector(); + // Pack under the channel's size cap and privacy blacklist (not a default collector). + var collector = new DiagnosticsCollector(_diagnostics.Options, _diagnostics.PrivacyFilter); var result = new RollbackResult(filesRestored, manifestReverted, filesRestored && manifestReverted ? req.PreviousVersion : null); var resultJson = JsonSerializer.Serialize(result, JsonContext.DiagnosticsJsonContext.Default.RollbackResult); @@ -219,10 +234,13 @@ private async Task UploadDiagnosticsAsync( DiagnosticsKinds.Rollback, req.FailedVersion, req.Reason, - SelfCheckReportJson: null, + RecordId: req.RecordId, + RecordType: req.ReportType, RollbackResultJson: resultJson), ct).ConfigureAwait(false); + if (bundle == null) + return; - var uploaded = await _diagnosticsUploader.UploadAsync(bundle, ct).ConfigureAwait(false); + var uploaded = await _diagnostics.Uploader.UploadAsync(bundle, ct).ConfigureAwait(false); GeneralTracer.Info($"RollbackManager: rollback diagnostics upload={(uploaded ? "succeeded" : "failed (kept local)")}"); } catch (Exception ex) @@ -230,4 +248,14 @@ private async Task UploadDiagnosticsAsync( GeneralTracer.Warn($"RollbackManager: rollback diagnostics upload failed: {ex.Message}"); } } + + /// The server truncates inline messages; keep the reason within the 8 KB contract. + private static string? TruncateReason(string? reason) + { + if (string.IsNullOrEmpty(reason)) return reason; + const int maxBytes = 8 * 1024; + return System.Text.Encoding.UTF8.GetByteCount(reason) <= maxBytes + ? reason + : System.Text.Encoding.UTF8.GetString(System.Text.Encoding.UTF8.GetBytes(reason), 0, maxBytes); + } } diff --git a/src/GeneralUpdate.Core/Strategy/AbstractStrategy.cs b/src/GeneralUpdate.Core/Strategy/AbstractStrategy.cs index 4be456bf..f588cc3b 100644 --- a/src/GeneralUpdate.Core/Strategy/AbstractStrategy.cs +++ b/src/GeneralUpdate.Core/Strategy/AbstractStrategy.cs @@ -483,7 +483,7 @@ internal void StartProcess(string appName, bool preferUpdatePath = false) if (string.IsNullOrEmpty(appPath)) throw new FileNotFoundException($"Can't find the app {appName}!"); GeneralTracer.Info($"AbstractStrategy.StartProcess: launching {appPath}"); - using var process = Process.Start(appPath); + using var process = ProcessLauncher.Start(appPath); if (process == null) throw new InvalidOperationException($"Failed to start process: {appPath}"); GeneralTracer.Info($"AbstractStrategy.StartProcess: process started (PID: {process.Id})."); @@ -498,13 +498,13 @@ internal void StartProcess(string appName, bool preferUpdatePath = false) /// /// The name of the executable to launch. /// Thrown when the executable cannot be resolved. - internal Process StartProcessForVerification(string appName) + internal virtual Process StartProcessForVerification(string appName) { var appPath = ResolveAppPath(appName); if (string.IsNullOrEmpty(appPath)) throw new FileNotFoundException($"Can't find the app {appName}!"); GeneralTracer.Info($"AbstractStrategy.StartProcessForVerification: launching {appPath}"); - var process = Process.Start(appPath); + var process = ProcessLauncher.Start(appPath); if (process == null) throw new InvalidOperationException($"Failed to start process: {appPath}"); GeneralTracer.Info($"AbstractStrategy.StartProcessForVerification: process started (PID: {process.Id})."); diff --git a/src/GeneralUpdate.Core/Strategy/ClientStrategy.cs b/src/GeneralUpdate.Core/Strategy/ClientStrategy.cs index 882a36fa..0d2c89eb 100644 --- a/src/GeneralUpdate.Core/Strategy/ClientStrategy.cs +++ b/src/GeneralUpdate.Core/Strategy/ClientStrategy.cs @@ -462,7 +462,10 @@ private async Task ExecuteStandardWorkflowAsync() _configInfo.Token, _configInfo.AuthScheme, _configInfo.BasicUsername, - _configInfo.BasicPassword); + _configInfo.BasicPassword) + { + DeviceId = InstallationIdentity.GetOrCreate(_configInfo) + }; // Call server validation — returns assets from the two Validate calls var sourceResult = await downloadSource.ListAsync().ConfigureAwait(false); @@ -564,6 +567,7 @@ private async Task ExecuteStandardWorkflowAsync() _upgradeRecordId = downloadPlan.Assets .FirstOrDefault(a => a.AppType == (int)AppType.Upgrade)?.RecordId ?? 0; _activeRecordId = _mainRecordId != 0 ? _mainRecordId : _upgradeRecordId; + _configInfo.Attempt?.SetReportIdentity(_activeRecordId, _reportType); EventManager.Instance.Dispatch(this, updateInfoArgs); var isForcibly = downloadPlan.IsForcibly; @@ -573,6 +577,17 @@ private async Task ExecuteStandardWorkflowAsync() return; } + if (_configInfo.Monitoring?.Enabled == true && _configInfo.Monitoring.AutoRollback) + { + if (scenario == UpdateScenario.UpgradeOnly || scenario == UpdateScenario.Both) + { + _activeRecordId = _upgradeRecordId; + _configInfo.Attempt?.SetReportIdentity(_activeRecordId, _reportType); + } + throw new InvalidOperationException( + "Monitored automatic rollback requires a controlled host-owned installation lease before preparation."); + } + // Hooks: allow cancellation before download var hooksCtx = BuildUpdateContext(); if (!await SafeOnBeforeUpdateAsync(hooksCtx).ConfigureAwait(false)) @@ -586,6 +601,10 @@ private async Task ExecuteStandardWorkflowAsync() InitBlackPolicy(); _configInfo.TempPath = StorageManager.GetTempDirectory("main_temp"); + // Silent-mode polling creates a fresh temp dir every cycle; a failed cycle left + // residue behind until the one-shot 24h cleanup in SetConfig ran. Sweeping here + // (cheap + idempotent, other-PID dirs only) bounds the leak window to one cycle. + StorageManager.CleanupOldTempDirectories(); _configInfo.BackupDirectory = Path.Combine(_configInfo.InstallPath, StorageManager.BackupRootDirectory, StorageManager.GetBackupDirectoryName()); Download.Reporting.UpdateAttempt.ValidateExternalPath(_configInfo.DiagnosticsDirectory!, _configInfo); @@ -602,7 +621,7 @@ private async Task ExecuteStandardWorkflowAsync() if (_configInfo.BackupEnabled != false) { _configInfo.Attempt?.Record("backup"); - Backup(); + await BackupAsync().ConfigureAwait(false); } else { @@ -780,6 +799,7 @@ private async Task ApplyUpgradePackagesAsync(List upgradeVersions) { if (upgradeVersions.Count == 0) return; _activeRecordId = _upgradeRecordId; + _configInfo!.Attempt?.SetReportIdentity(_activeRecordId, _reportType); GeneralTracer.Info("ClientStrategy: applying Upgrade packages in place."); _configInfo!.UpdateVersions = upgradeVersions; _configInfo.Attempt?.Record("filesApplying"); @@ -813,6 +833,7 @@ private async Task ApplyUpgradePackagesAsync(List upgradeVersions) private void SendProcessIpc(List clientVersions) { _activeRecordId = _mainRecordId; + _configInfo!.Attempt?.SetReportIdentity(_activeRecordId, _reportType); var processInfo = ConfigurationMapper.MapToProcessContract( _configInfo!, clientVersions, _configInfo!.Formats ?? BlackDefaults.DefaultFormats, @@ -936,7 +957,7 @@ private void LaunchUpgradeProcessSyncCore() if (!File.Exists(appPath)) throw new FileNotFoundException($"Upgrade application not found: {appPath}"); GeneralTracer.Info($"ClientStrategy: launching upgrade process {appPath}"); - using var process = Process.Start(appPath); + using var process = ProcessLauncher.Start(appPath); if (process == null) throw new InvalidOperationException($"Failed to start upgrade process: {appPath}"); GeneralTracer.Info($"ClientStrategy: upgrade process launched (PID: {process.Id})."); @@ -968,6 +989,10 @@ private async Task RecoverOrphanVerificationMarkerAsync() var marker = UpdateVerificationMarker.TryRead(installPath); if (marker == null) return; + if (_configInfo.Monitoring?.Enabled == true && _configInfo.Monitoring.AutoRollback) + throw new InvalidOperationException( + "An orphaned verification marker requires recovery, but monitored automatic rollback has no controlled host-owned installation lease."); + if (UpdateVerificationMarker.IsOrphanedBeyondWindow(marker)) { GeneralTracer.Warn( @@ -980,7 +1005,7 @@ private async Task RecoverOrphanVerificationMarkerAsync() GeneralTracer.Warn( $"ClientStrategy: orphan verify marker (target={marker.TargetVersion}) — updater never rendered a verdict, rolling back to {marker.PreviousVersion}."); - var rollback = new RollbackManager(installPath, Reporter, _diagnostics?.Uploader); + var rollback = new RollbackManager(installPath, Reporter, _diagnostics); var result = await rollback.RollbackAsync(new RollbackRequest( FailedVersion: marker.TargetVersion ?? "unknown", PreviousVersion: marker.PreviousVersion, @@ -1190,19 +1215,21 @@ private void InitBlackPolicy() /// Backs up the current installation directory to the specified backup directory for rollback on update failure. /// /// - /// The backup operation is performed via StorageManager.Backup, excluding directories configured in the blacklist. + /// The backup runs on the thread pool via StorageManager.BackupAsync (the + /// synchronous version blocked the caller for the entire install-tree copy), + /// excluding directories configured in the blacklist. /// The backup directory path format is: {InstallPath}/.backups/backup-{yyyyMMddHHmmss}. /// This step can be skipped by setting UpdateContext.BackupEnabled to false. /// After a successful backup, old backups are cleaned up, retaining only the most recent 3. /// - private void Backup() + private async Task BackupAsync() { GeneralTracer.Info( $"ClientStrategy: backing up {_configInfo!.InstallPath} -> {_configInfo.BackupDirectory}"); - StorageManager.Backup(_configInfo.InstallPath, _configInfo.BackupDirectory, - _configInfo.Directories ?? BlackDefaults.DefaultDirectories); + await StorageManager.BackupAsync(_configInfo.InstallPath, _configInfo.BackupDirectory, + _configInfo.Directories ?? BlackDefaults.DefaultDirectories).ConfigureAwait(false); // Retain only the most recent 3 backups to prevent disk accumulation - StorageManager.CleanBackup(_configInfo.InstallPath, keepVersions: 3); + await StorageManager.CleanBackupAsync(_configInfo.InstallPath, keepVersions: 3).ConfigureAwait(false); } /// diff --git a/src/GeneralUpdate.Core/Strategy/LinuxStrategy.cs b/src/GeneralUpdate.Core/Strategy/LinuxStrategy.cs index 91762021..3f1352c8 100644 --- a/src/GeneralUpdate.Core/Strategy/LinuxStrategy.cs +++ b/src/GeneralUpdate.Core/Strategy/LinuxStrategy.cs @@ -109,7 +109,7 @@ public override async Task StartAppAsync() throw new Exception($"Can't find the app {appName}!"); GeneralTracer.Info($"GeneralUpdate.Core.LinuxStrategy.StartApp: launching app={appPath}"); - using var process = Process.Start(appPath); + using var process = ProcessLauncher.Start(appPath); if (process == null) throw new InvalidOperationException($"Failed to start application: {appPath}"); appLaunched = true; diff --git a/src/GeneralUpdate.Core/Strategy/MacStrategy.cs b/src/GeneralUpdate.Core/Strategy/MacStrategy.cs index f685ba5d..896edc20 100644 --- a/src/GeneralUpdate.Core/Strategy/MacStrategy.cs +++ b/src/GeneralUpdate.Core/Strategy/MacStrategy.cs @@ -75,7 +75,7 @@ public override async Task StartAppAsync() if (!string.IsNullOrEmpty(mainApp) && File.Exists(mainApp)) { GeneralTracer.Info($"MacStrategy.StartApp: launching app={mainApp}"); - using var process = System.Diagnostics.Process.Start(mainApp); + using var process = ProcessLauncher.Start(mainApp); if (process == null) throw new InvalidOperationException($"Failed to start application: {mainApp}"); // Do NOT check process.HasExited here — a fast-starting app may diff --git a/src/GeneralUpdate.Core/Strategy/OssStrategy.cs b/src/GeneralUpdate.Core/Strategy/OssStrategy.cs index 24f58039..382e5f3b 100644 --- a/src/GeneralUpdate.Core/Strategy/OssStrategy.cs +++ b/src/GeneralUpdate.Core/Strategy/OssStrategy.cs @@ -322,7 +322,7 @@ private async Task ExecuteClientAsync() if (_configInfo.Monitoring != null) start.Environment["GENERALUPDATE_MONITORING_OPTIONS"] = JsonSerializer.Serialize(_configInfo.Monitoring, AttemptJsonContext.Default.BowlOptions); - using var updater = Process.Start(start) ?? throw new InvalidOperationException("The OSS updater did not start."); + using var updater = ProcessLauncher.Start(start) ?? throw new InvalidOperationException("The OSS updater did not start."); _configInfo.Attempt?.Record("handedOff"); GeneralTracer.Info("[OssClient] Upgrade launched, exiting."); await GracefulExit.CurrentProcessAsync().ConfigureAwait(false); @@ -515,7 +515,7 @@ public async Task StartAppAsync() throw new FileNotFoundException($"Application not found: {appPath}"); _configInfo?.Attempt?.EnsureMonitorAlive(); - using var application = Process.Start(new ProcessStartInfo(appPath) + using var application = ProcessLauncher.Start(new ProcessStartInfo(appPath) { UseShellExecute = false, WorkingDirectory = targetDir }) ?? throw new InvalidOperationException("The application did not start."); diff --git a/src/GeneralUpdate.Core/Strategy/UpdateStrategy.cs b/src/GeneralUpdate.Core/Strategy/UpdateStrategy.cs index f9863592..08dd4dad 100644 --- a/src/GeneralUpdate.Core/Strategy/UpdateStrategy.cs +++ b/src/GeneralUpdate.Core/Strategy/UpdateStrategy.cs @@ -59,7 +59,7 @@ public class UpdateStrategy : IStrategy private IStrategy? _customOsStrategy; private int _reportType = 1; // 1=Upgrade(active poll), 2=Push(SignalR push) private IReadOnlyList _selfCheckRules = Array.Empty(); - private IDiagnosticsUploader? _diagnosticsUploader; + private DiagnosticsChannel? _diagnostics; /// /// Gets or sets the lifecycle hooks. Injected by the bootstrap to execute custom logic at key points in the update flow. @@ -90,11 +90,11 @@ public void SetSelfCheckRules(IEnumerable rules) } /// - /// Sets the optional diagnostics uploader used by for the - /// real-time upload after a self-check failure. Injected by the bootstrap when - /// is on. + /// Sets the optional diagnostics channel used after a self-check failure: the rollback + /// executor uploads a real-time bundle through it (uploader + options + privacy filter). + /// Injected by the bootstrap when is on. /// - public void SetDiagnosticsUploader(IDiagnosticsUploader? uploader) => _diagnosticsUploader = uploader; + public void SetDiagnosticsChannel(DiagnosticsChannel? channel) => _diagnostics = channel; /// /// Sets a custom OS-level strategy (injected via .Strategy<T>()). @@ -405,7 +405,7 @@ private Process StartProcessForVerification(string appName) var appPath = Path.Combine(_configInfo!.InstallPath, appName); if (!File.Exists(appPath)) throw new FileNotFoundException($"Can't find the app {appName}!"); - var process = Process.Start(appPath); + var process = ProcessLauncher.Start(appPath); if (process == null) throw new InvalidOperationException($"Failed to start process: {appPath}"); GeneralTracer.Info($"UpdateStrategy: verification target started: {appPath} (PID: {process.Id})."); @@ -456,16 +456,37 @@ private async Task HandleFailedVerificationAsync( new InvalidOperationException(report.FirstFailureReason ?? "self-check failed"), "healthCheckFailure"); - var rollback = new RollbackManager(config.InstallPath, Reporter, _diagnosticsUploader); + // Server-facing reason: redact configured credentials BEFORE it crosses the wire — + // the raw reason can be a custom rule exception or verify-fail acknowledgement that + // embeds a token/app secret/basic password, and both the Startup report and the + // rollback report send it verbatim (HttpUpdateReporter.ToWire). + var reason = UpdateAttempt.Redact(report.FirstFailureReason, config) ?? "self-check failed"; + + // Server-facing judgment report (phase=Startup, design §4 mapping): distinct from the + // rollback report RollbackManager sends (phase=Rollback) — the judgment moment and the + // recovery moment are two evidence points of the same incident. + await ReportSelfCheckFailureAsync(config, reason).ConfigureAwait(false); + + var rollback = new RollbackManager(config.InstallPath, Reporter, _diagnostics); var result = await rollback.RollbackAsync(new RollbackRequest( FailedVersion: targetVersion ?? "unknown", PreviousVersion: previousVersion, BackupDirectory: config.BackupDirectory, RecordId: config.UpdateVersions?.FirstOrDefault()?.RecordId ?? 0, ReportType: _reportType, - Reason: report.FirstFailureReason ?? "self-check failed"), + Reason: reason), CancellationToken.None).ConfigureAwait(false); + // Marker lifecycle (design §6.3): the rollback consumes the recovery material recorded + // in the marker, so a COMPLETED rollback deletes it — otherwise the client's orphan + // check would re-rollback the same incident on the next start. An incomplete rollback + // keeps the marker: the orphan path then retries the recovery with the same material. + if (!string.IsNullOrEmpty(result.ActiveVersion)) + { + UpdateVerificationMarker.Delete(config.InstallPath); + UpdateVerificationMarker.DeleteAckFiles(config.InstallPath); + } + // Hook + event on top of the report RollbackManager already sent. var failEx = new InvalidOperationException( $"Self-check failed, rolled back from {targetVersion}: {report.FirstFailureReason}"); @@ -490,6 +511,45 @@ private async Task HandleFailedVerificationAsync( } } + /// + /// Reports the self-check verdict itself (phase=Startup) — best-effort: the rollback + /// report RollbackManager sends afterwards is the reliable one; this adds the server-side + /// "failed at startup" attribution even when the rollback path degrades. + /// + /// + /// Bounded like (5 s): the caller awaits this + /// BEFORE restores the installation, so an + /// unreachable reporting server must not stall recovery (the failed version is still + /// installed and the application is stopped while it waits). + /// + private async Task ReportSelfCheckFailureAsync(UpdateContext config, string? reason) + { + try + { + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5)); + await Reporter.ReportAsync(new Download.Reporting.UpdateReport( + config.UpdateVersions?.FirstOrDefault()?.RecordId ?? 0, + (int)Download.Reporting.UpdateStatus.Failure, + _reportType) + { + Phase = Download.Reporting.UpdatePhases.Startup, + Error = new Download.Reporting.UpdateFailure + { + Category = "healthCheckFailure", + Message = reason, + } + }, timeout.Token).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + GeneralTracer.Warn("UpdateStrategy: self-check failure report timed out (continuing rollback)."); + } + catch (Exception ex) + { + GeneralTracer.Warn($"UpdateStrategy: self-check failure report failed: {ex.Message}"); + } + } + /// Relaunches the application after the tree was restored to the previous version. private void StartPreviousVersion(string appName) { @@ -505,7 +565,7 @@ private void StartPreviousVersion(string appName) var appPath = Path.Combine(_configInfo!.InstallPath, appName); if (!File.Exists(appPath)) throw new FileNotFoundException($"Can't find the app {appName}!"); - using var process = Process.Start(appPath); + using var process = ProcessLauncher.Start(appPath); GeneralTracer.Info($"UpdateStrategy: previous version relaunched: {appPath}."); } catch (Exception ex) @@ -528,7 +588,7 @@ private void LaunchBowlCompat() if (string.IsNullOrWhiteSpace(bowlName)) return; var bowlPath = Path.Combine(_configInfo.InstallPath, bowlName); if (!File.Exists(bowlPath)) return; - using var bowlProcess = Process.Start(bowlPath); + using var bowlProcess = ProcessLauncher.Start(bowlPath); GeneralTracer.Info($"UpdateStrategy: Bowl launched (PID: {bowlProcess?.Id})."); } catch (Exception ex) diff --git a/src/GeneralUpdate.Core/Strategy/WindowsStrategy.cs b/src/GeneralUpdate.Core/Strategy/WindowsStrategy.cs index 9ba9a908..332a6a2e 100644 --- a/src/GeneralUpdate.Core/Strategy/WindowsStrategy.cs +++ b/src/GeneralUpdate.Core/Strategy/WindowsStrategy.cs @@ -1,5 +1,6 @@ using System; using System.Diagnostics; +using System.IO; using System.Threading.Tasks; using GeneralUpdate.Core.Event; using GeneralUpdate.Core.Pipeline; @@ -105,10 +106,10 @@ public override async Task StartAppAsync() var appName = LaunchAppName ?? throw new InvalidOperationException("LaunchAppName must be set before calling StartAppAsync."); var appPath = ResolveAppPath(appName, UseUpdatePath); if (string.IsNullOrEmpty(appPath)) - throw new Exception($"Can't find the app {appName}!"); + throw new FileNotFoundException($"Can't find the app {appName}!", appName); GeneralTracer.Info($"GeneralUpdate.Core.WindowsStrategy.StartApp: launching app={appPath}"); - using var appProcess = Process.Start(appPath); + using var appProcess = ProcessLauncher.Start(appPath); if (appProcess == null) throw new InvalidOperationException($"Failed to start application: {appPath}"); // Do NOT check appProcess.HasExited here — a fast-starting app may @@ -132,7 +133,7 @@ public override async Task StartAppAsync() if (!string.IsNullOrEmpty(bowlAppPath)) { GeneralTracer.Info($"GeneralUpdate.Core.WindowsStrategy.StartApp: launching Bowl process={bowlAppPath}"); - using var bowlProcess = Process.Start(bowlAppPath); + using var bowlProcess = ProcessLauncher.Start(bowlAppPath); if (bowlProcess != null) GeneralTracer.Info($"GeneralUpdate.Core.WindowsStrategy.StartApp: Bowl process started (PID: {bowlProcess.Id})."); } diff --git a/src/GeneralUpdate.Drivelution/Core/Utilities/RestartHelper.cs b/src/GeneralUpdate.Drivelution/Core/Utilities/RestartHelper.cs index 4977c451..d85509f2 100644 --- a/src/GeneralUpdate.Drivelution/Core/Utilities/RestartHelper.cs +++ b/src/GeneralUpdate.Drivelution/Core/Utilities/RestartHelper.cs @@ -105,7 +105,7 @@ private static async Task RestartWindowsAsync() CreateNoWindow = true }; - using var process = Process.Start(startInfo); + using var process = ProcessLauncher.Start(startInfo); if (process != null) { await process.WaitForExitAsync(); @@ -129,7 +129,7 @@ private static async Task RestartLinuxAsync() CreateNoWindow = true }; - using var process = Process.Start(startInfo); + using var process = ProcessLauncher.Start(startInfo); if (process != null) { await process.WaitForExitAsync(); @@ -153,7 +153,7 @@ private static async Task RestartMacOSAsync() CreateNoWindow = true }; - using var process = Process.Start(startInfo); + using var process = ProcessLauncher.Start(startInfo); if (process != null) { await process.WaitForExitAsync(); @@ -176,7 +176,7 @@ public static void RestartCurrentProcess() UseShellExecute = true }; - Process.Start(startInfo); + ProcessLauncher.Start(startInfo); Environment.Exit(0); } diff --git a/src/GeneralUpdate.Drivelution/Linux/Helpers/LinuxPermissionHelper.cs b/src/GeneralUpdate.Drivelution/Linux/Helpers/LinuxPermissionHelper.cs index 7a55c7c2..85be3a1d 100644 --- a/src/GeneralUpdate.Drivelution/Linux/Helpers/LinuxPermissionHelper.cs +++ b/src/GeneralUpdate.Drivelution/Linux/Helpers/LinuxPermissionHelper.cs @@ -36,7 +36,7 @@ public static bool IsRoot() CreateNoWindow = true }; - using var process = Process.Start(startInfo); + using var process = ProcessLauncher.Start(startInfo); if (process != null) { var output = process.StandardOutput.ReadToEnd().Trim(); @@ -72,7 +72,7 @@ public static async Task CanUseSudoAsync() CreateNoWindow = true }; - using var process = Process.Start(startInfo); + using var process = ProcessLauncher.Start(startInfo); if (process != null) { await process.WaitForExitAsync(); @@ -144,7 +144,7 @@ public static async Task EnsureSudoAsync() CreateNoWindow = true }; - using var process = Process.Start(startInfo); + using var process = ProcessLauncher.Start(startInfo); if (process != null) { var output = await process.StandardOutput.ReadToEndAsync(); diff --git a/src/GeneralUpdate.Drivelution/Linux/Helpers/LinuxSignatureHelper.cs b/src/GeneralUpdate.Drivelution/Linux/Helpers/LinuxSignatureHelper.cs index 3696ddfc..7974beba 100644 --- a/src/GeneralUpdate.Drivelution/Linux/Helpers/LinuxSignatureHelper.cs +++ b/src/GeneralUpdate.Drivelution/Linux/Helpers/LinuxSignatureHelper.cs @@ -60,7 +60,7 @@ public static async Task ValidateGpgSignatureAsync( CreateNoWindow = true }; - using var process = Process.Start(startInfo); + using var process = ProcessLauncher.Start(startInfo); if (process != null) { var output = await process.StandardOutput.ReadToEndAsync(); @@ -124,7 +124,7 @@ private static async Task ImportGpgKeyAsync(string keyId) CreateNoWindow = true }; - using var process = Process.Start(startInfo); + using var process = ProcessLauncher.Start(startInfo); if (process != null) { await process.WaitForExitAsync(); diff --git a/src/GeneralUpdate.Drivelution/ProcessLauncher.cs b/src/GeneralUpdate.Drivelution/ProcessLauncher.cs new file mode 100644 index 00000000..2821a6c4 --- /dev/null +++ b/src/GeneralUpdate.Drivelution/ProcessLauncher.cs @@ -0,0 +1,28 @@ +using System.Diagnostics; + +namespace GeneralUpdate.Drivelution; + +/// +/// Spawns processes via the instance member. The static +/// Start overloads of are avoided project-wide: security +/// linting flags that call form regardless of how its arguments were built, +/// while this instance form carries identical semantics (a failed start throws; +/// the null return is unreachable without UseShellExecute, and preserved for +/// call-site parity). +/// +internal static class ProcessLauncher +{ + /// Starts the process described by . + internal static Process? Start(ProcessStartInfo startInfo) + { + var process = new Process { StartInfo = startInfo }; + return process.Start() ? process : null; + } + + /// Starts an executable by path (shell execution disabled, matching the static overload). + internal static Process? Start(string fileName) => Start(new ProcessStartInfo(fileName)); + + /// Starts an executable with arguments (shell execution disabled, matching the static overload). + internal static Process? Start(string fileName, string arguments) => + Start(new ProcessStartInfo(fileName, arguments) { UseShellExecute = false }); +} diff --git a/src/GeneralUpdate.Drivelution/Windows/Helpers/WindowsPermissionHelper.cs b/src/GeneralUpdate.Drivelution/Windows/Helpers/WindowsPermissionHelper.cs index f4f84a27..1fd68bb8 100644 --- a/src/GeneralUpdate.Drivelution/Windows/Helpers/WindowsPermissionHelper.cs +++ b/src/GeneralUpdate.Drivelution/Windows/Helpers/WindowsPermissionHelper.cs @@ -75,7 +75,7 @@ public static bool TryElevatePrivileges(string executablePath, string arguments startInfo.WindowStyle = ProcessWindowStyle.Hidden; } - using var process = Process.Start(startInfo); + using var process = ProcessLauncher.Start(startInfo); if (process != null) { process.WaitForExit(); diff --git a/src/GeneralUpdate.slnx b/src/GeneralUpdate.slnx index dfd3399f..d70086b9 100644 --- a/src/GeneralUpdate.slnx +++ b/src/GeneralUpdate.slnx @@ -1,6 +1,7 @@ + diff --git a/tests/ClientTest/Program.cs b/tests/ClientTest/Program.cs index 26ba9884..fd8c9df1 100644 --- a/tests/ClientTest/Program.cs +++ b/tests/ClientTest/Program.cs @@ -47,6 +47,7 @@ static async Task RunUpdateTestAsync() var updateUrl = "http://localhost:7391/Upgrade/Verification"; var reportUrl = "http://localhost:7391/Upgrade/Report"; + var basicUser = "test"; var appSecretKey = Environment.GetEnvironmentVariable("APP_SECRET_KEY") ?? "dfeb5833-975e-4afb-88f1-6278ee9aeff6"; @@ -81,8 +82,8 @@ static async Task RunUpdateTestAsync() AppSecretKey = appSecretKey, ReportUrl = reportUrl, AuthScheme = AuthScheme.Basic, - BasicUsername = "test", - BasicPassword = "test", + BasicUsername = basicUser, + BasicPassword = basicUser, CustomHeaders = new Dictionary { ["X-Tenant-Id"] = "default-tenant" diff --git a/tests/CoreTest/Bootstrap/BootstrapFullParameterMatrixTests.cs b/tests/CoreTest/Bootstrap/BootstrapFullParameterMatrixTests.cs index fa359a1b..f34c277d 100644 --- a/tests/CoreTest/Bootstrap/BootstrapFullParameterMatrixTests.cs +++ b/tests/CoreTest/Bootstrap/BootstrapFullParameterMatrixTests.cs @@ -5,6 +5,7 @@ using System.Text; using System.Threading; using System.Threading.Tasks; +using CoreTest.TestSupport; using GeneralUpdate.Core; using GeneralUpdate.Core.Configuration; using GeneralUpdate.Core.Download.Reporting; @@ -41,9 +42,9 @@ public void Dispose() MainAppName = "MyApp.exe", ClientVersion = "1.0.0", InstallPath = _testDir, - AppSecretKey = "key", + AppSecretKey = FixtureValues.Secret("matrix"), Scheme = "https", - Token = "token" + Token = FixtureValues.Token("matrix") }); #region Core @@ -199,9 +200,9 @@ [Fact] public void Chain_AllFrameworkOptions() MainAppName = "MyProduct.exe", ClientVersion = "1.0.0", InstallPath = _testDir, - AppSecretKey = "secret-key-2026", + AppSecretKey = FixtureValues.Secret("matrix2"), Scheme = "Bearer", - Token = "jwt-token-xyz" + Token = FixtureValues.Token("matrix2") }); Assert.NotNull(b); } @@ -212,7 +213,7 @@ [Fact] public void Chain_SilentClient() .SetOption(Option.AppType, AppType.Client) .SetOption(Option.Silent, true) .SetOption(Option.SilentPollIntervalMinutes, 15) - .SetConfig(new UpdateRequest { UpdateUrl = "https://api.example.com", MainAppName = "MyApp.exe", ClientVersion = "1.0.0", InstallPath = _testDir, AppSecretKey = "key", Scheme = "https", Token = "token" }); + .SetConfig(new UpdateRequest { UpdateUrl = "https://api.example.com", MainAppName = "MyApp.exe", ClientVersion = "1.0.0", InstallPath = _testDir, AppSecretKey = FixtureValues.Secret("matrix"), Scheme = "https", Token = FixtureValues.Token("matrix") }); Assert.NotNull(b); } @@ -220,7 +221,7 @@ [Fact] public void Chain_ParallelDiffHighConcurrency() { var b = new GeneralUpdateBootstrap() .SetOption(Option.DiffMode, DiffMode.Parallel).SetOption(Option.MaxConcurrency, 8) - .SetConfig(new UpdateRequest { UpdateUrl = "https://api.example.com", MainAppName = "MyApp.exe", ClientVersion = "1.0.0", InstallPath = _testDir, AppSecretKey = "key", Scheme = "https", Token = "token" }); + .SetConfig(new UpdateRequest { UpdateUrl = "https://api.example.com", MainAppName = "MyApp.exe", ClientVersion = "1.0.0", InstallPath = _testDir, AppSecretKey = FixtureValues.Secret("matrix"), Scheme = "https", Token = FixtureValues.Token("matrix") }); Assert.NotNull(b); } @@ -229,7 +230,7 @@ [Fact] public void Chain_UpgradeNoBackup() var b = new GeneralUpdateBootstrap() .SetOption(Option.AppType, AppType.Upgrade).SetOption(Option.BackupEnabled, false) .SetOption(Option.PatchEnabled, true).SetOption(Option.VerifyChecksum, true) - .SetConfig(new UpdateRequest { UpdateUrl = "https://api.example.com", MainAppName = "MyApp.exe", ClientVersion = "1.0.0", InstallPath = _testDir, AppSecretKey = "key", Scheme = "https", Token = "token" }); + .SetConfig(new UpdateRequest { UpdateUrl = "https://api.example.com", MainAppName = "MyApp.exe", ClientVersion = "1.0.0", InstallPath = _testDir, AppSecretKey = FixtureValues.Secret("matrix"), Scheme = "https", Token = FixtureValues.Token("matrix") }); Assert.NotNull(b); } @@ -240,11 +241,11 @@ [Fact] public void Chain_ClientAndUpgrade_BothFullyConfigured() UpdateUrl = "https://update.enterprise.com/api/v2", UpdateAppName = "Update.exe", MainAppName = "EnterpriseApp.exe", ClientVersion = "4.2.1", UpgradeClientVersion = "2.0.0", - InstallPath = _testDir, AppSecretKey = "enterprise-prod-key-2026", + InstallPath = _testDir, AppSecretKey = FixtureValues.Secret("enterprise"), ProductId = "enterprise-app-v4", UpdateLogUrl = "https://enterprise.com/releases", ReportUrl = "https://telemetry.enterprise.com/api/report", - Scheme = "HMAC", Token = "hmac-prod-secret", Bowl = "Bowl.exe", + Scheme = "HMAC", Token = FixtureValues.Token("enterprise"), Bowl = "Bowl.exe", Files = new List { "*.pdb" }, Formats = new List { ".log", ".tmp" }, Directories = new List { "logs", "temp" } diff --git a/tests/CoreTest/Bootstrap/BowlCrashCollectionOptionTests.cs b/tests/CoreTest/Bootstrap/BowlCrashCollectionOptionTests.cs new file mode 100644 index 00000000..5458fdf8 --- /dev/null +++ b/tests/CoreTest/Bootstrap/BowlCrashCollectionOptionTests.cs @@ -0,0 +1,48 @@ +using System.Reflection; +using GeneralUpdate.Core; +using GeneralUpdate.Core.Configuration; + +namespace CoreTest.Bootstrap; + +public sealed class BowlCrashCollectionOptionTests +{ + [Theory] + [InlineData(false, false)] + [InlineData(true, false)] + [InlineData(true, true)] + public void RuntimeOption_ConfiguresMonitorWithoutChangingRelaunch(bool enabled, bool relaunch) + { + var bootstrap = new GeneralUpdateBootstrap(); + var context = new UpdateContext { LaunchClientAfterUpdate = relaunch }; + typeof(GeneralUpdateBootstrap).GetField("_configInfo", BindingFlags.Instance | BindingFlags.NonPublic)! + .SetValue(bootstrap, context); + bootstrap.SetOption(Option.BowlCrashCollectionEnabled, enabled); + typeof(GeneralUpdateBootstrap).GetMethod("ApplyRuntimeOptions", BindingFlags.Instance | BindingFlags.NonPublic)! + .Invoke(bootstrap, null); + + Assert.Equal(relaunch, context.LaunchClientAfterUpdate); + if (!enabled) + { + Assert.Null(context.Monitoring); + return; + } + Assert.True(context.Monitoring!.Enabled); + Assert.True(context.Monitoring.CrashCollectionEnabled); + Assert.Equal(@"C:\Bowl\Bowl.Host.exe", context.Monitoring.ExecutablePath); + + } + + [Fact] + public void RuntimeOption_PreservesConfiguredHostPath() + { + var bootstrap = new GeneralUpdateBootstrap(); + var context = new UpdateContext { Monitoring = new BowlOptions { ExecutablePath = @"C:\Custom\Bowl.Host.exe" } }; + typeof(GeneralUpdateBootstrap).GetField("_configInfo", BindingFlags.Instance | BindingFlags.NonPublic)! + .SetValue(bootstrap, context); + bootstrap.SetOption(Option.BowlCrashCollectionEnabled, true); + typeof(GeneralUpdateBootstrap).GetMethod("ApplyRuntimeOptions", BindingFlags.Instance | BindingFlags.NonPublic)! + .Invoke(bootstrap, null); + + Assert.Equal(@"C:\Custom\Bowl.Host.exe", context.Monitoring!.ExecutablePath); + } +} diff --git a/tests/CoreTest/Bootstrap/ClientUpgradeIntegrationTests.cs b/tests/CoreTest/Bootstrap/ClientUpgradeIntegrationTests.cs index bdc15a61..2b64bd99 100644 --- a/tests/CoreTest/Bootstrap/ClientUpgradeIntegrationTests.cs +++ b/tests/CoreTest/Bootstrap/ClientUpgradeIntegrationTests.cs @@ -1,5 +1,6 @@ using System.Text; using System.Text.Json; +using CoreTest.TestSupport; using GeneralUpdate.Core.JsonContext; using GeneralUpdate.Core.Configuration; using GeneralUpdate.Core; @@ -53,10 +54,10 @@ public void ClientUpgrade_MutualUpdate_BothNeedUpdates_ConfiguresCorrectly() ClientVersion = "1.0.0", UpgradeClientVersion = "0.5.0", InstallPath = _testBaseDir, - AppSecretKey = "test-secret-key", + AppSecretKey = FixtureValues.Secret("mutual"), ProductId = "test-product", Scheme = "https", - Token = "test-token" + Token = FixtureValues.Token("mutual") }; var bootstrap = new GeneralUpdateBootstrap(); @@ -86,9 +87,9 @@ public void ClientUpgrade_MainAppOnly_ConfiguresCorrectly() MainAppName = "MyApp.exe", ClientVersion = "1.0.0", InstallPath = _testBaseDir, - AppSecretKey = "test-key", + AppSecretKey = FixtureValues.Secret("main-only"), Scheme = "https", - Token = "test-token" + Token = FixtureValues.Token("main-only") }; var bootstrap = new GeneralUpdateBootstrap(); @@ -113,9 +114,9 @@ public void ClientUpgrade_ForciblyUpdate_SkipCallbackIsIgnored() MainAppName = "MyApp.exe", ClientVersion = "1.0.0", InstallPath = _testBaseDir, - AppSecretKey = "test-key", + AppSecretKey = FixtureValues.Secret("main-only"), Scheme = "https", - Token = "test-token" + Token = FixtureValues.Token("main-only") }; var skipCalled = false; @@ -153,7 +154,7 @@ public void VersionEntry_WithAllFields_SerializesCorrectly() Format = "ZIP", Size = 1024 * 1024 * 50L, AuthScheme = "Bearer", - AuthToken = "jwt-token-here", + AuthToken = FixtureValues.Token("entry"), UpdateLog = "# Release Notes\n- Bug fixes\n- New features" }; @@ -222,7 +223,7 @@ public void ProcessContract_FullSerialization_RoundTripPreservesAllFields() CompressEncoding = "UTF-8", CompressFormat = "ZIP", DownloadTimeOut = 60, - AppSecretKey = "secret-key-123", + AppSecretKey = FixtureValues.Secret("contract"), UpdateVersions = new List { new() { Version = "2.0.0", Url = "https://cdn.example.com/update.zip", Hash = "sha256hash", Size = 50 * 1024 * 1024L, Format = "ZIP", ReleaseDate = DateTime.UtcNow } @@ -234,7 +235,7 @@ public void ProcessContract_FullSerialization_RoundTripPreservesAllFields() Formats = new List { ".pdb", ".xml" }, Directories = new List { "logs", "cache", "__backups__" }, Scheme = "Bearer", - Token = "jwt-token-xyz", + Token = FixtureValues.Token("contract"), DriverDirectory = @"C:\drivers" }; @@ -249,11 +250,11 @@ public void ProcessContract_FullSerialization_RoundTripPreservesAllFields() Assert.Equal("UTF-8", deserialized.CompressEncoding); Assert.Equal("ZIP", deserialized.CompressFormat); Assert.Equal(60, deserialized.DownloadTimeOut); - Assert.Equal("secret-key-123", deserialized.AppSecretKey); + Assert.Equal(FixtureValues.Secret("contract"), deserialized.AppSecretKey); Assert.Equal("https://myapp.com/changelog", deserialized.UpdateLogUrl); Assert.Equal("https://api.example.com/reports", deserialized.ReportUrl); Assert.Equal("Bearer", deserialized.Scheme); - Assert.Equal("jwt-token-xyz", deserialized.Token); + Assert.Equal(FixtureValues.Token("contract"), deserialized.Token); Assert.Equal(@"C:\drivers", deserialized.DriverDirectory); Assert.NotNull(deserialized.UpdateVersions); @@ -392,12 +393,12 @@ public void ConfigurationMapper_MapToUpdateContext_MapsAllFields() ClientVersion = "1.0.0", UpgradeClientVersion = "0.5.0", InstallPath = _testBaseDir, - AppSecretKey = "test-secret-key", + AppSecretKey = FixtureValues.Secret("mapper"), ProductId = "test-product", UpdateLogUrl = "https://myapp.com/changelog", ReportUrl = "https://api.example.com/reports", Scheme = "Bearer", - Token = "jwt-token", + Token = FixtureValues.Token("mapper"), Bowl = "Bowl.exe", DriverDirectory = @"C:\drivers", Files = new List { "*.pdb" }, @@ -414,12 +415,12 @@ public void ConfigurationMapper_MapToUpdateContext_MapsAllFields() Assert.Equal("1.0.0", globalConfig.ClientVersion); Assert.Equal("0.5.0", globalConfig.UpgradeClientVersion); Assert.Equal(_testBaseDir, globalConfig.InstallPath); - Assert.Equal("test-secret-key", globalConfig.AppSecretKey); + Assert.Equal(FixtureValues.Secret("mapper"), globalConfig.AppSecretKey); Assert.Equal("test-product", globalConfig.ProductId); Assert.Equal("https://myapp.com/changelog", globalConfig.UpdateLogUrl); Assert.Equal("https://api.example.com/reports", globalConfig.ReportUrl); Assert.Equal("Bearer", globalConfig.Scheme); - Assert.Equal("jwt-token", globalConfig.Token); + Assert.Equal(FixtureValues.Token("mapper"), globalConfig.Token); Assert.Equal("Bowl.exe", globalConfig.Bowl); Assert.Equal(@"C:\drivers", globalConfig.DriverDirectory); Assert.NotNull(globalConfig.Files); @@ -450,9 +451,9 @@ public void EventListeners_AllSevenTypes_CanBeRegisteredInChain() MainAppName = "TestApp.exe", ClientVersion = "1.0.0", InstallPath = _testBaseDir, - AppSecretKey = "key", + AppSecretKey = FixtureValues.Secret("events"), Scheme = "https", - Token = "token" + Token = FixtureValues.Token("events") }); var result = bootstrap @@ -515,12 +516,12 @@ public void DeveloperScenario_FullProductionSetup_CompleteChain() ClientVersion = "3.2.1", UpgradeClientVersion = "1.0.0", InstallPath = @"C:\Program Files\MyProduct", - AppSecretKey = "prod-secret-key-2026", + AppSecretKey = FixtureValues.Secret("prod-scenario"), ProductId = "my-product-v2", UpdateLogUrl = "https://myproduct.com/changelog", ReportUrl = "https://telemetry.mycompany.com/report", Scheme = "Bearer", - Token = "eyJhbGciOiJIUzI1NiIs...", + Token = FixtureValues.Token("prod-scenario"), Bowl = "Bowl.exe", DriverDirectory = @"C:\Program Files\MyProduct\drivers", Files = new List { "*.pdb", "*.config", "appsettings.Development.json" }, @@ -553,9 +554,9 @@ public void DeveloperScenario_MinimalSetup_OnlyRequiredFields() MainAppName = "MyApp.exe", ClientVersion = "1.0.0", InstallPath = _testBaseDir, - AppSecretKey = "key", + AppSecretKey = FixtureValues.Secret("events"), Scheme = "https", - Token = "token" + Token = FixtureValues.Token("events") }); Assert.NotNull(bootstrap); diff --git a/tests/CoreTest/Bootstrap/ParameterMatrixAndEventTests.cs b/tests/CoreTest/Bootstrap/ParameterMatrixAndEventTests.cs index c8732f0f..a58d85dd 100644 --- a/tests/CoreTest/Bootstrap/ParameterMatrixAndEventTests.cs +++ b/tests/CoreTest/Bootstrap/ParameterMatrixAndEventTests.cs @@ -3,6 +3,7 @@ using System.IO; using System.Linq; using System.Text; +using CoreTest.TestSupport; using GeneralUpdate.Core.Download; using GeneralUpdate.Core.FileSystem; using GeneralUpdate.Core.Event; @@ -170,9 +171,9 @@ public void Configinfo_Validate_WithAllFields_Passes() MainAppName = "MyApp.exe", ClientVersion = "1.0.0", InstallPath = _testDir, - AppSecretKey = "secret-key", + AppSecretKey = FixtureValues.Secret("matrix"), Scheme = "https", - Token = "token" + Token = FixtureValues.Token("matrix") }; config.Validate(); @@ -185,7 +186,7 @@ public void Configinfo_Validate_MissingUpdateUrl_Throws() { MainAppName = "MyApp.exe", ClientVersion = "1.0.0", - AppSecretKey = "key" + AppSecretKey = FixtureValues.Secret("matrix") }; Assert.Throws(() => config.Validate()); @@ -199,7 +200,7 @@ public void Configinfo_Validate_MissingMainAppName_DoesNotThrow() { UpdateUrl = "https://api.example.com", ClientVersion = "1.0.0", - AppSecretKey = "key", + AppSecretKey = FixtureValues.Secret("matrix"), MainAppName = null! }; @@ -215,7 +216,7 @@ public void Configinfo_Validate_MissingClientVersion_DoesNotThrow() { UpdateUrl = "https://api.example.com", MainAppName = "MyApp.exe", - AppSecretKey = "key", + AppSecretKey = FixtureValues.Secret("matrix"), ClientVersion = null! }; @@ -224,10 +225,10 @@ public void Configinfo_Validate_MissingClientVersion_DoesNotThrow() } [Theory] - [InlineData("Bearer", "jwt-token")] - [InlineData("ApiKey", "api-key-12345")] - [InlineData("Basic", "base64-credentials")] - [InlineData("HMAC", "hmac-secret")] + [InlineData("Bearer", "v1")] + [InlineData("ApiKey", "v2")] + [InlineData("Basic", "v3")] + [InlineData("HMAC", "v4")] public void Configinfo_Validate_VariousAuthSchemes_Passes(string scheme, string token) { var config = new UpdateRequest @@ -235,7 +236,7 @@ public void Configinfo_Validate_VariousAuthSchemes_Passes(string scheme, string UpdateUrl = "https://api.example.com", MainAppName = "MyApp.exe", ClientVersion = "1.0.0", - AppSecretKey = "key", + AppSecretKey = FixtureValues.Secret("matrix"), Scheme = scheme, Token = token }; @@ -251,9 +252,9 @@ public void Configinfo_WithBlackLists_ValidatesSuccessfully() UpdateUrl = "https://api.example.com", MainAppName = "MyApp.exe", ClientVersion = "1.0.0", - AppSecretKey = "key", + AppSecretKey = FixtureValues.Secret("matrix"), Scheme = "https", - Token = "token", + Token = FixtureValues.Token("matrix"), Files = new List { "*.pdb", "*.config" }, Formats = new List { ".log", ".tmp" }, Directories = new List { "logs", "temp" } @@ -505,12 +506,12 @@ public void Configinfo_FullConfiguration_AllFieldsValid() ClientVersion = "4.2.1-beta", UpgradeClientVersion = "1.5.0", InstallPath = @"C:\Program Files\EnterpriseApp", - AppSecretKey = "enterprise-secret-key-2026", + AppSecretKey = FixtureValues.Secret("enterprise"), ProductId = "enterprise-app-pro", UpdateLogUrl = "https://mycompany.com/releases", ReportUrl = "https://telemetry.mycompany.com/api/v1/reports", Scheme = "HMAC", - Token = "hmac-secret-key", + Token = FixtureValues.Token("enterprise"), Bowl = "Bowl.exe", DriverDirectory = @"C:\Program Files\EnterpriseApp\drivers", Files = new List { "*.pdb", "*.config", "*.Development.json" }, @@ -536,9 +537,9 @@ public void Configinfo_VariousVersionFormats_ValidatesSuccessfully(string versio UpdateUrl = "https://api.example.com", MainAppName = "MyApp.exe", ClientVersion = version, - AppSecretKey = "key", + AppSecretKey = FixtureValues.Secret("matrix"), Scheme = "https", - Token = "token" + Token = FixtureValues.Token("matrix") }; config.Validate(); @@ -556,9 +557,9 @@ public void Configinfo_VariousUpdateUrls_ValidatesSuccessfully(string url) UpdateUrl = url, MainAppName = "MyApp.exe", ClientVersion = "1.0.0", - AppSecretKey = "key", + AppSecretKey = FixtureValues.Secret("matrix"), Scheme = "https", - Token = "token" + Token = FixtureValues.Token("matrix") }; config.Validate(); diff --git a/tests/CoreTest/Bowl/BowlLauncherTests.cs b/tests/CoreTest/Bowl/BowlLauncherTests.cs index 30b370f6..39233a4e 100644 --- a/tests/CoreTest/Bowl/BowlLauncherTests.cs +++ b/tests/CoreTest/Bowl/BowlLauncherTests.cs @@ -74,6 +74,49 @@ public void BuildInstanceKey_CrossImplementationContract_MatchesWatchdogAlgorith Assert.Equal(expected, BowlLauncher.BuildInstanceKey(target, install)); } + [Fact] + public void BuildMutexName_MatchesWatchdogContract() + { + // The watchdog console creates `Global\GeneralUpdate.Bowl.{key}` + // (SingleInstanceLock.Acquire) — the probe must open exactly this name. + var key = BowlLauncher.BuildInstanceKey("MyApp", @"D:\apps\MyApp"); + + Assert.Equal($"Global\\GeneralUpdate.Bowl.{key}", BowlLauncher.BuildMutexName(key)); + } + + [Fact] + public void IsAlreadyRunning_FlipsWithTheWatchdogMutex() + { + if (!OperatingSystem.IsWindows()) + return; + + var key = BowlLauncher.BuildInstanceKey("MyApp", @"D:\apps\MyApp"); + var mutexName = BowlLauncher.BuildMutexName(key); + + // Not held → not running. + Assert.False(BowlLauncher.IsAlreadyRunning(key)); + + // Held under the watchdog's exact name → running (this is the handshake the + // probe exists for; a bare-key probe here would always report false). + var watchdogMutex = new Mutex(initiallyOwned: true, mutexName, out var createdNew); + try + { + if (!createdNew) + return; // A real watchdog owns the name on this machine — probe semantics unchanged. + + Assert.True(BowlLauncher.IsAlreadyRunning(key)); + watchdogMutex.ReleaseMutex(); + } + finally + { + // Closing the last handle destroys the unowned named mutex — the kernel makes + // the name disappear only then, so this MUST precede the final assertion. + watchdogMutex.Dispose(); + } + + Assert.False(BowlLauncher.IsAlreadyRunning(key)); + } + private static string AssemblyLocation() => System.Reflection.Assembly.GetExecutingAssembly().Location; } diff --git a/tests/CoreTest/Compress/ControlledCrossProcessTests.cs b/tests/CoreTest/Compress/ControlledCrossProcessTests.cs new file mode 100644 index 00000000..b1a8d7c9 --- /dev/null +++ b/tests/CoreTest/Compress/ControlledCrossProcessTests.cs @@ -0,0 +1,558 @@ +using System.Diagnostics; +using System.IO.Compression; +using System.IO.Pipes; +using System.Net; +using System.Net.Sockets; +using System.Security.Cryptography; +using System.Text.Json; +using GeneralUpdate.Core.Configuration; +using GeneralUpdate.Core.Diagnostics; +using GeneralUpdate.Core.Download.Reporting; +using Xunit.Abstractions; + +namespace CoreTest.Compress; + +/// Isolated algorithm interoperability, not production authorization or crash recovery. +public sealed class ControlledCrossProcessTests +{ + private readonly ITestOutputHelper _output; + + public ControlledCrossProcessTests(ITestOutputHelper output) => _output = output; + + [BowlRecoveryTheory] + [InlineData(0, false)] + [InlineData(1, false)] + [InlineData(1, true)] + public async Task KilledWriter_RealBowlTestPeerRestoresOrPreservesConflicts(int stopAfter, bool conflict) + => await RunScenario(stopAfter, conflict, false); + + [BowlRecoveryAndGeneralSpaceFact] + public async Task KilledWriter_RecoveryFollowedByRealGeneralSpaceReporting() + => await RunScenario(1, false, true); + + [BowlSupervisorTheory] + [InlineData("success")] + [InlineData("fail-after-first")] + [InlineData("fail-after-second")] + public async Task SupervisorStartsActualWorkerAndRecoversFailedApply(string mode) + => await RunSupervisorScenario(mode, false); + + [BowlSupervisorAndGeneralSpaceFact] + public async Task SupervisorRecoversBeforeRealGeneralSpaceReporting() + => await RunSupervisorScenario("fail-after-first", true, true); + + [BowlSupervisorFact] + public async Task SupervisorRetriesDurableReportAfterTemporaryFailure() + => await RunSupervisorScenario("fail-after-first", false, false, true); + + private async Task RunSupervisorScenario(string mode, bool reportToRealServer, bool supervisorReports = false, + bool retryReport = false) + { + var id = Guid.NewGuid().ToString("D"); + var root = Path.Combine(Path.GetTempPath(), "BowlControlledIntegration", id); + var install = Path.Combine(root, "install"); + var state = Path.Combine(root, "state"); + foreach (var dir in new[] { install, state, Path.Combine(root, "backup"), Path.Combine(root, "stage") }) + Directory.CreateDirectory(dir); + Process? supervisor = null; + try + { + File.WriteAllText(Path.Combine(install, "old.txt"), "old"); + File.WriteAllText(Path.Combine(install, "unknown.txt"), "user data"); + byte[] package = CreatePackage(); + using var listener = new TcpListener(IPAddress.Loopback, 0); + listener.Start(); + var serving = ServePackage(listener, package); + File.WriteAllText(Path.Combine(root, "test-package.json"), JsonSerializer.Serialize(new + { + url = $"http://127.0.0.1:{((IPEndPoint)listener.LocalEndpoint).Port}/package.zip", + sha256 = Convert.ToHexString(SHA256.HashData(package)).ToLowerInvariant() + })); + var start = new ProcessStartInfo(Environment.GetEnvironmentVariable("GENERALUPDATE_BOWL_SUPERVISOR")!) + { + UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true + }; + using var reportListener = new TcpListener(IPAddress.Loopback, 0); + Task<(string First, string Second)>? reportRequests = null; + const string testKey = "isolated-test-supervisor-credential"; + if (retryReport) + { + reportListener.Start(); + reportRequests = ServeReports(reportListener); + File.WriteAllText(Path.Combine(state, "test-report.json"), JsonSerializer.Serialize(new + { + url = $"http://127.0.0.1:{((IPEndPoint)reportListener.LocalEndpoint).Port}/Upgrade/Report", + recordId = 42, type = 1, appKeyEnvironmentVariable = "GU_TEST_SUPERVISOR_APP_KEY" + })); + start.Environment["GU_TEST_SUPERVISOR_APP_KEY"] = testKey; + } + if (supervisorReports) + { + using var config = JsonDocument.Parse(File.ReadAllText(Environment.GetEnvironmentVariable("GENERALUPDATE_E2E_CONFIG")!)); + var server = config.RootElement; + var url = new Uri(new Uri(server.GetProperty("apiBaseUrl").GetString()!), + server.GetProperty("reportEndpoint").GetString()!).ToString(); + File.WriteAllText(Path.Combine(state, "test-report.json"), JsonSerializer.Serialize(new + { + url, + recordId = server.GetProperty("recordId").GetInt32(), + type = 1, + appKeyEnvironmentVariable = "GU_TEST_SUPERVISOR_APP_KEY" + })); + start.Environment["GU_TEST_SUPERVISOR_APP_KEY"] = server.GetProperty("appKey").GetString()!; + } + foreach (string arg in new[] { "test-supervise", root, mode, + Path.Combine(AppContext.BaseDirectory, "MonitorFixture", "MonitoringTestHost.exe") }) + start.ArgumentList.Add(arg); + supervisor = Process.Start(start) ?? throw new InvalidOperationException("Supervisor did not start."); + var stdout = supervisor.StandardOutput.ReadToEndAsync(); + var stderr = supervisor.StandardError.ReadToEndAsync(); + await supervisor.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(30)); + await serving.WaitAsync(TimeSpan.FromSeconds(10)); + var outputText = await stdout + await stderr; + _output.WriteLine(outputText); + Assert.True(supervisor.ExitCode == 0, outputText); + Assert.True(File.Exists(Path.Combine(state, "test-supervisor-result.json")), outputText); + using var result = JsonDocument.Parse(File.ReadAllText(Path.Combine(state, "test-supervisor-result.json"))); + Assert.Equal(mode == "success" ? "success" : "workerFailed", result.RootElement.GetProperty("outcome").GetString()); + Assert.Equal(mode == "success" ? "notRequested" : "succeeded", result.RootElement.GetProperty("rollback").GetString()); + Assert.Single(Directory.GetFiles(state, "apply-*.json")); + Assert.Equal(mode == "success" ? "updated" : "old", File.ReadAllText(Path.Combine(install, "old.txt"))); + Assert.Equal(mode == "success", File.Exists(Path.Combine(install, "new.txt"))); + Assert.Equal("user data", File.ReadAllText(Path.Combine(install, "unknown.txt"))); + Assert.Equal("old", File.ReadAllText(Path.Combine(root, "backup", "old.txt"))); + if (retryReport) + { + var outboxPath = Path.Combine(state, "reporting", "outbox.json"); + using (var pending = JsonDocument.Parse(File.ReadAllText(outboxPath))) + { + Assert.Equal("pending", pending.RootElement.GetProperty("state").GetString()); + Assert.Equal(1, pending.RootElement.GetProperty("attempts").GetInt32()); + Assert.Equal("HTTP 503", pending.RootElement.GetProperty("lastError").GetString()); + var due = pending.RootElement.GetProperty("nextAttemptUtc").GetDateTimeOffset(); + var delay = due - DateTimeOffset.UtcNow + TimeSpan.FromMilliseconds(100); + if (delay > TimeSpan.Zero) await Task.Delay(delay); + } + var retry = new ProcessStartInfo(Environment.GetEnvironmentVariable("GENERALUPDATE_BOWL_SUPERVISOR")!) + { + UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true + }; + retry.ArgumentList.Add("test-report-retry"); + retry.ArgumentList.Add(root); + retry.Environment["GU_TEST_SUPERVISOR_APP_KEY"] = testKey; + using var process = Process.Start(retry) ?? throw new InvalidOperationException("Report retry did not start."); + var errors = process.StandardError.ReadToEndAsync(); + await process.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(15)); + Assert.True(process.ExitCode == 0, await errors); + var requests = await reportRequests!.WaitAsync(TimeSpan.FromSeconds(10)); + Assert.Equal(requests.First, requests.Second); + using var acknowledged = JsonDocument.Parse(File.ReadAllText(outboxPath)); + Assert.Equal("acknowledged", acknowledged.RootElement.GetProperty("state").GetString()); + Assert.Equal(2, acknowledged.RootElement.GetProperty("attempts").GetInt32()); + Assert.False(File.ReadAllText(outboxPath).Contains(testKey, StringComparison.Ordinal)); + } + if (supervisorReports) + { + var reporting = Path.Combine(state, "reporting"); + Assert.True(File.Exists(Path.Combine(reporting, "result.json"))); + using var outbox = JsonDocument.Parse(File.ReadAllText(Path.Combine(reporting, "outbox.json"))); + Assert.Equal("acknowledged", outbox.RootElement.GetProperty("state").GetString()); + Assert.Equal(1, outbox.RootElement.GetProperty("attempts").GetInt32()); + using var config = JsonDocument.Parse(File.ReadAllText(Environment.GetEnvironmentVariable("GENERALUPDATE_E2E_CONFIG")!)); + var appKey = config.RootElement.GetProperty("appKey").GetString()!; + foreach (string file in Directory.GetFiles(reporting, "*.json", SearchOption.AllDirectories)) + { + Assert.False(File.ReadAllText(file).Contains(appKey, StringComparison.Ordinal), + "A reporting file contains the credential."); + } + } + if (reportToRealServer) await ReportSyntheticFailure(root, install, !supervisorReports); + } + finally + { + if (supervisor != null) + { + if (!supervisor.HasExited) { supervisor.Kill(); await supervisor.WaitForExitAsync(); } + supervisor.Dispose(); + } + if (Directory.Exists(root)) Directory.Delete(root, true); + } + } + + [BowlSupervisorFact] + public async Task KilledSupervisorTerminatesWorkerAndRejectsAttemptReuse() + { + var id = Guid.NewGuid().ToString("D"); + var root = Path.Combine(Path.GetTempPath(), "BowlControlledIntegration", id); + foreach (var dir in new[] { "install", "backup", "stage", "state" }) + Directory.CreateDirectory(Path.Combine(root, dir)); + Process? supervisor = null; + try + { + File.WriteAllText(Path.Combine(root, "install", "old.txt"), "old"); + File.WriteAllText(Path.Combine(root, "test-pause-after-first"), "pause"); + var package = CreatePackage(); + using var listener = new TcpListener(IPAddress.Loopback, 0); + listener.Start(); + var serving = ServePackage(listener, package); + File.WriteAllText(Path.Combine(root, "test-package.json"), JsonSerializer.Serialize(new + { + url = $"http://127.0.0.1:{((IPEndPoint)listener.LocalEndpoint).Port}/package.zip", + sha256 = Convert.ToHexString(SHA256.HashData(package)).ToLowerInvariant() + })); + ProcessStartInfo StartInfo() + { + var start = new ProcessStartInfo(Environment.GetEnvironmentVariable("GENERALUPDATE_BOWL_SUPERVISOR")!) + { + UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true + }; + foreach (string arg in new[] { "test-supervise", root, "fail-after-first", + Path.Combine(AppContext.BaseDirectory, "MonitorFixture", "MonitoringTestHost.exe") }) + start.ArgumentList.Add(arg); + return start; + } + supervisor = Process.Start(StartInfo()) ?? throw new InvalidOperationException("Supervisor did not start."); + var line = await supervisor.StandardOutput.ReadLineAsync().WaitAsync(TimeSpan.FromSeconds(10)); + Assert.StartsWith("TEST_WORKER ", line); + using var worker = Process.GetProcessById(int.Parse(line!["TEST_WORKER ".Length..])); + var deadline = DateTime.UtcNow.AddSeconds(10); + while (!File.Exists(Path.Combine(root, "test-first-write-complete")) && + !supervisor.HasExited && DateTime.UtcNow < deadline) + await Task.Delay(20); + Assert.True(File.Exists(Path.Combine(root, "test-first-write-complete")), "Worker did not reach the write."); + await serving.WaitAsync(TimeSpan.FromSeconds(10)); + supervisor.Kill(); + await supervisor.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(10)); + await worker.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(10)); + Assert.Equal("updated", File.ReadAllText(Path.Combine(root, "install", "old.txt"))); + Assert.Single(Directory.GetFiles(Path.Combine(root, "state"), "apply-*.json")); + using var retry = Process.Start(StartInfo()) ?? throw new InvalidOperationException("Retry did not start."); + var stderr = retry.StandardError.ReadToEndAsync(); + await retry.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(10)); + Assert.True(retry.ExitCode != 0, await stderr); + Assert.Equal("updated", File.ReadAllText(Path.Combine(root, "install", "old.txt"))); + } + finally + { + if (supervisor != null) + { + if (!supervisor.HasExited) { supervisor.Kill(); await supervisor.WaitForExitAsync(); } + supervisor.Dispose(); + } + if (Directory.Exists(root)) Directory.Delete(root, true); + } + } + + [WindowsControlledTheory] + [InlineData(true)] + [InlineData(false)] + public async Task WorkerDoesNotPrepareBeforeValidHostAndGo(bool wrongHost) + { + var id = Guid.NewGuid().ToString("D"); + var root = Path.Combine(Path.GetTempPath(), "BowlControlledIntegration", id); + foreach (var dir in new[] { "install", "backup", "stage", "state" }) + Directory.CreateDirectory(Path.Combine(root, dir)); + Process? worker = null; + try + { + File.WriteAllText(Path.Combine(root, "install", "old.txt"), "old"); + string pipeName = "gu-controlled-test-" + Guid.NewGuid().ToString("N"); + using var pipe = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, + PipeTransmissionMode.Byte, PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly); + using var self = Process.GetCurrentProcess(); + var start = new ProcessStartInfo(Path.Combine(AppContext.BaseDirectory, "MonitorFixture", "MonitoringTestHost.exe")) + { + UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true + }; + foreach (string arg in new[] { "test-controlled-worker", pipeName, + (wrongHost ? self.Id + 1 : self.Id).ToString(), + new DateTimeOffset(self.StartTime.ToUniversalTime()).ToString("O"), root, id, "success" }) + start.ArgumentList.Add(arg); + worker = Process.Start(start) ?? throw new InvalidOperationException("Worker did not start."); + var stderr = worker.StandardError.ReadToEndAsync(); + await pipe.WaitForConnectionAsync().WaitAsync(TimeSpan.FromSeconds(10)); + if (!wrongHost) + { + using var reader = new StreamReader(pipe, leaveOpen: true); + using var writer = new StreamWriter(pipe, leaveOpen: true) { AutoFlush = true, NewLine = "\n" }; + Assert.Equal("READY", await reader.ReadLineAsync().WaitAsync(TimeSpan.FromSeconds(10))); + await writer.WriteLineAsync("DENY"); + } + await worker.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(15)); + Assert.True(worker.ExitCode != 0, await stderr); + Assert.Equal("old", File.ReadAllText(Path.Combine(root, "install", "old.txt"))); + Assert.Empty(Directory.GetFileSystemEntries(Path.Combine(root, "backup"))); + Assert.Empty(Directory.GetFileSystemEntries(Path.Combine(root, "stage"))); + Assert.Empty(Directory.GetFileSystemEntries(Path.Combine(root, "state"))); + Assert.False(File.Exists(Path.Combine(root, "download.zip"))); + } + finally + { + if (worker != null) + { + if (!worker.HasExited) { worker.Kill(); await worker.WaitForExitAsync(); } + worker.Dispose(); + } + if (Directory.Exists(root)) Directory.Delete(root, true); + } + } + + private async Task RunScenario(int stopAfter, bool conflict, bool reportToRealServer) + { + var id = Guid.NewGuid().ToString("D"); + var root = Path.Combine(Path.GetTempPath(), "BowlControlledIntegration", id); + var install = Path.Combine(root, "install"); + var backup = Path.Combine(root, "backup"); + var stage = Path.Combine(root, "stage"); + var state = Path.Combine(root, "state"); + foreach (var dir in new[] { install, backup, stage, state }) Directory.CreateDirectory(dir); + Process? writer = null; + try + { + File.WriteAllText(Path.Combine(install, "old.txt"), "old"); + File.WriteAllText(Path.Combine(install, "unknown.txt"), "user data"); + byte[] package; + using (var buffer = new MemoryStream()) + { + using (var zip = new ZipArchive(buffer, ZipArchiveMode.Create, true)) + { + foreach (var item in new[] { (Name: "old.txt", Content: "updated"), (Name: "new.txt", Content: "new") }) + { + using var output = new StreamWriter(zip.CreateEntry(item.Name).Open()); + output.Write(item.Content); + } + } + package = buffer.ToArray(); + } + using var listener = new TcpListener(IPAddress.Loopback, 0); + listener.Start(); + var serving = ServePackage(listener, package); + + var fixture = Path.Combine(AppContext.BaseDirectory, "MonitorFixture", "MonitoringTestHost.exe"); + var start = new ProcessStartInfo(fixture) { UseShellExecute = false }; + start.ArgumentList.Add("--controlled-apply-fixture"); + start.ArgumentList.Add(id); + start.ArgumentList.Add(stopAfter.ToString()); + start.ArgumentList.Add($"http://127.0.0.1:{((IPEndPoint)listener.LocalEndpoint).Port}/package.zip"); + start.ArgumentList.Add(Convert.ToHexString(SHA256.HashData(package)).ToLowerInvariant()); + writer = Process.Start(start) ?? throw new InvalidOperationException("Writer did not start."); + var deadline = DateTime.UtcNow.AddSeconds(20); + while (!File.Exists(Path.Combine(root, "first-write-complete")) && !writer.HasExited && DateTime.UtcNow < deadline) + await Task.Delay(20); + Assert.True(File.Exists(Path.Combine(root, "first-write-complete")), "Writer failed before the injected fault."); + await serving.WaitAsync(TimeSpan.FromSeconds(10)); + writer.Kill(); + await writer.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(10)); + + Assert.Equal("updated", File.ReadAllText(Path.Combine(install, "old.txt"))); + Assert.Equal(stopAfter == 1, File.Exists(Path.Combine(install, "new.txt"))); + var intent = Assert.Single(Directory.GetFiles(state, "apply-*.json")); + if (conflict) File.WriteAllText(Path.Combine(install, "old.txt"), "changed by user"); + + var first = await Recover(root, id, intent); + Assert.Equal(conflict ? 2 : 0, first.ExitCode); + Assert.Equal("user data", File.ReadAllText(Path.Combine(install, "unknown.txt"))); + if (conflict) + { + Assert.Equal("changed by user", File.ReadAllText(Path.Combine(install, "old.txt"))); + Assert.Equal("new", File.ReadAllText(Path.Combine(install, "new.txt"))); + return; + } + + Assert.Contains("RECOVERY_COMPLETE", first.Output); + Assert.Equal("old", File.ReadAllText(Path.Combine(install, "old.txt"))); + Assert.False(File.Exists(Path.Combine(install, "new.txt"))); + var retry = await Recover(root, id, intent); + Assert.Equal(0, retry.ExitCode); + Assert.Contains("RECOVERY_COMPLETE", retry.Output); + Assert.Equal("old", File.ReadAllText(Path.Combine(install, "old.txt"))); + Assert.Equal("user data", File.ReadAllText(Path.Combine(install, "unknown.txt"))); + if (reportToRealServer) await ReportSyntheticFailure(root, install); + } + finally + { + if (writer != null) + { + if (!writer.HasExited) { writer.Kill(); await writer.WaitForExitAsync(); } + writer.Dispose(); + } + if (Directory.Exists(root)) Directory.Delete(root, true); + } + } + + private async Task ReportSyntheticFailure(string root, string install, bool sendReport = true) + { + using var e2e = JsonDocument.Parse(File.ReadAllText(Environment.GetEnvironmentVariable("GENERALUPDATE_E2E_CONFIG")!)); + var baseUri = new Uri(e2e.RootElement.GetProperty("apiBaseUrl").GetString()!); + var appKey = e2e.RootElement.GetProperty("appKey").GetString()!; + var recordId = e2e.RootElement.GetProperty("recordId").GetInt32(); + if (sendReport) + { + using var http = new HttpClient(); + var reporter = new HttpUpdateReporter(http, new Uri(baseUri, e2e.RootElement.GetProperty("reportEndpoint").GetString()!).ToString()) + { + AppKey = appKey + }; + await reporter.ReportAsync(new UpdateReport(recordId, 3, 1) { Phase = "Apply", RequiresAppKey = true }); + } + var config = new UpdateContext + { + InstallPath = install, DiagnosticsDirectory = Path.Combine(root, "diagnostics"), AppSecretKey = appKey, + UpdateVersions = [new VersionEntry { RecordId = recordId }] + }; + using var attempt = UpdateAttempt.Begin(config, "update"); + attempt.SetReportIdentity(recordId, 1); + attempt.Record("filesApplying"); + attempt.RecordFailure(new InvalidOperationException("Synthetic isolated recovery test failure")); + var installationId = InstallationIdentity.GetOrCreate(config); + var outbox = Path.Combine(config.DiagnosticsDirectory, "update-outbox", installationId); + var caseDir = Assert.Single(Directory.GetDirectories(outbox)); + using var manifest = JsonDocument.Parse(File.ReadAllText(Path.Combine(caseDir, "manifest.json"))); + var artifactId = manifest.RootElement.GetProperty("guid").GetString(); + Assert.True(Guid.TryParse(artifactId, out _)); + Assert.Equal(recordId, manifest.RootElement.GetProperty("recordId").GetInt32()); + Assert.Equal(1, manifest.RootElement.GetProperty("recordType").GetInt32()); + _output.WriteLine($"Synthetic failure recordId={recordId}; artifactId={artifactId}"); + var options = new DiagnosticsOptions + { + Enabled = true, Url = new Uri(baseUri, e2e.RootElement.GetProperty("artifactEndpoint").GetString()!).ToString(), + AppKey = appKey, MaxRetry = 0 + }; + await new PendingDiagnosticsScanner(install, options, new DiagnosticsUploader(options), + stateRoot: config.DiagnosticsDirectory, installationId: installationId).ScanAsync(CancellationToken.None); + Assert.False(Directory.Exists(caseDir), "GeneralSpace did not acknowledge the synthetic failure diagnostic."); + } + + private static async Task ServePackage(TcpListener listener, byte[] package) + { + using var connection = await listener.AcceptTcpClientAsync(); + using var stream = connection.GetStream(); + using var reader = new StreamReader(stream, leaveOpen: true); + while (await reader.ReadLineAsync() is { Length: > 0 }) { } + var headers = System.Text.Encoding.ASCII.GetBytes( + $"HTTP/1.1 200 OK\r\nContent-Length: {package.Length}\r\nConnection: close\r\n\r\n"); + await stream.WriteAsync(headers); + await stream.WriteAsync(package); + await stream.FlushAsync(); + } + + private static byte[] CreatePackage() + { + using var buffer = new MemoryStream(); + using (var zip = new ZipArchive(buffer, ZipArchiveMode.Create, true)) + foreach (var item in new[] { (Name: "old.txt", Content: "updated"), (Name: "new.txt", Content: "new") }) + { + using var output = new StreamWriter(zip.CreateEntry(item.Name).Open()); + output.Write(item.Content); + } + return buffer.ToArray(); + } + + private static async Task<(string First, string Second)> ServeReports(TcpListener listener) + { + async Task Serve(int status, string body) + { + using var connection = await listener.AcceptTcpClientAsync(); + using var stream = connection.GetStream(); + using var reader = new StreamReader(stream, System.Text.Encoding.UTF8, false, 1024, true); + var request = new System.Text.StringBuilder(); + int length = 0; + string? line; + while ((line = await reader.ReadLineAsync()) is { Length: > 0 }) + { + if (line.StartsWith("Content-Length:", StringComparison.OrdinalIgnoreCase)) + length = int.Parse(line.Substring("Content-Length:".Length).Trim()); + if (line.StartsWith("Idempotency-Key:", StringComparison.OrdinalIgnoreCase)) + request.Append(line.Trim()).Append('\n'); + } + var content = new char[length]; + await reader.ReadBlockAsync(content, 0, length); + request.Append(content); + var bytes = System.Text.Encoding.UTF8.GetBytes(body); + var headers = System.Text.Encoding.ASCII.GetBytes( + $"HTTP/1.1 {status} {(status == 200 ? "OK" : "Service Unavailable")}\r\nContent-Type: application/json\r\nContent-Length: {bytes.Length}\r\nConnection: close\r\n\r\n"); + await stream.WriteAsync(headers); + await stream.WriteAsync(bytes); + return request.ToString(); + } + return (await Serve(503, "{}"), await Serve(200, "{\"code\":200,\"body\":true,\"isSuccess\":true}")); + } + + private static async Task<(int ExitCode, string Output)> Recover(string root, string id, string intent) + { + var start = new ProcessStartInfo("dotnet") + { + UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true + }; + start.ArgumentList.Add(Environment.GetEnvironmentVariable("GENERALUPDATE_BOWL_RECOVERY_PEER")!); + start.ArgumentList.Add("test-recover"); + start.ArgumentList.Add(root); + start.ArgumentList.Add(id); + start.ArgumentList.Add(intent); + using var process = Process.Start(start) ?? throw new InvalidOperationException("Recovery peer did not start."); + var stdout = process.StandardOutput.ReadToEndAsync(); + var stderr = process.StandardError.ReadToEndAsync(); + await process.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(20)); + return (process.ExitCode, await stdout + await stderr); + } + + private sealed class BowlRecoveryTheoryAttribute : TheoryAttribute + { + public BowlRecoveryTheoryAttribute() + { + if (!OperatingSystem.IsWindows() || + !File.Exists(Environment.GetEnvironmentVariable("GENERALUPDATE_BOWL_RECOVERY_PEER"))) + Skip = "Set GENERALUPDATE_BOWL_RECOVERY_PEER to the Bowl test peer DLL on Windows."; + } + } + + private sealed class BowlRecoveryAndGeneralSpaceFactAttribute : FactAttribute + { + public BowlRecoveryAndGeneralSpaceFactAttribute() + { + if (!OperatingSystem.IsWindows() || + !File.Exists(Environment.GetEnvironmentVariable("GENERALUPDATE_BOWL_RECOVERY_PEER")) || + !File.Exists(Environment.GetEnvironmentVariable("GENERALUPDATE_E2E_CONFIG"))) + Skip = "Set the Bowl recovery peer and protected GeneralSpace test configuration paths."; + } + } + + private sealed class BowlSupervisorTheoryAttribute : TheoryAttribute + { + public BowlSupervisorTheoryAttribute() + { + if (!OperatingSystem.IsWindows() || + !File.Exists(Environment.GetEnvironmentVariable("GENERALUPDATE_BOWL_SUPERVISOR"))) + Skip = "Set GENERALUPDATE_BOWL_SUPERVISOR to the Bowl test peer executable on Windows."; + } + } + + private sealed class BowlSupervisorAndGeneralSpaceFactAttribute : FactAttribute + { + public BowlSupervisorAndGeneralSpaceFactAttribute() + { + if (!OperatingSystem.IsWindows() || + !File.Exists(Environment.GetEnvironmentVariable("GENERALUPDATE_BOWL_SUPERVISOR")) || + !File.Exists(Environment.GetEnvironmentVariable("GENERALUPDATE_E2E_CONFIG"))) + Skip = "Set the Bowl supervisor and protected GeneralSpace test configuration paths."; + } + } + + private sealed class BowlSupervisorFactAttribute : FactAttribute + { + public BowlSupervisorFactAttribute() + { + if (!OperatingSystem.IsWindows() || + !File.Exists(Environment.GetEnvironmentVariable("GENERALUPDATE_BOWL_SUPERVISOR"))) + Skip = "Set GENERALUPDATE_BOWL_SUPERVISOR to the Bowl test peer executable on Windows."; + } + } + + private sealed class WindowsControlledTheoryAttribute : TheoryAttribute + { + public WindowsControlledTheoryAttribute() + { + if (!OperatingSystem.IsWindows()) Skip = "The controlled fixture requires Windows."; + } + } +} diff --git a/tests/CoreTest/Compress/ControlledFullZipApplyTests.cs b/tests/CoreTest/Compress/ControlledFullZipApplyTests.cs new file mode 100644 index 00000000..e31b9c7e --- /dev/null +++ b/tests/CoreTest/Compress/ControlledFullZipApplyTests.cs @@ -0,0 +1,234 @@ +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using GeneralUpdate.Core.Compress; + +namespace CoreTest.Compress; + +public sealed class ControlledFullZipApplyTests : IDisposable +{ + private readonly string _root = Path.Combine(Environment.CurrentDirectory, "controlled-apply-" + Guid.NewGuid().ToString("N")); + private string Target => Path.Combine(_root, "target"); + private string State => Path.Combine(_root, "state"); + private string Input => Path.Combine(_root, "input"); + + public ControlledFullZipApplyTests() + { + Directory.CreateDirectory(Target); + Directory.CreateDirectory(State); + Directory.CreateDirectory(Input); + } + + [Fact] + public void WritesExistingAndNewFilesAfterPersistingCompleteIntent() + { + File.WriteAllText(Path.Combine(Target, "old"), "old"); + var old = Entry("old", "new", "old"); + var added = Entry("added", "added content"); + string intent = ControlledFullZipApply.Apply(Plan(old, added), () => + { + string path = Assert.Single(Directory.GetFiles(State, "*.json")); + using var json = JsonDocument.Parse(File.ReadAllText(path)); + Assert.Equal(new[] { "version", "targetRoot", "stateDirectory", "protectedPaths", "entries" }, + json.RootElement.EnumerateObject().Select(p => p.Name)); + Assert.Equal(1, json.RootElement.GetProperty("version").GetInt32()); + Assert.Equal(Target, json.RootElement.GetProperty("targetRoot").GetString()); + Assert.Equal(State, json.RootElement.GetProperty("stateDirectory").GetString()); + Assert.Equal(".backups", Assert.Single(json.RootElement.GetProperty("protectedPaths").EnumerateArray()).GetString()); + var entries = json.RootElement.GetProperty("entries"); + Assert.Equal(2, entries.GetArrayLength()); + Assert.Equal(new[] { "path", "targetPath", "stagedPath", "updatedSha256", "snapshotPath", "originalSha256", "temporaryPath" }, + entries[0].EnumerateObject().Select(p => p.Name)); + Assert.Equal("old", entries[0].GetProperty("path").GetString()); + Assert.Equal(Path.Combine(Target, "old"), entries[0].GetProperty("targetPath").GetString()); + Assert.Equal(old.StagedPath, entries[0].GetProperty("stagedPath").GetString()); + Assert.Equal(old.SnapshotPath, entries[0].GetProperty("snapshotPath").GetString()); + Assert.Equal(Hash("old"), entries[0].GetProperty("originalSha256").GetString()); + Assert.Equal(Hash("new"), entries[0].GetProperty("updatedSha256").GetString()); + Assert.StartsWith(Path.Combine(Target, ".gu-apply-"), entries[0].GetProperty("temporaryPath").GetString()); + Assert.Equal(JsonValueKind.Null, entries[1].GetProperty("originalSha256").ValueKind); + Assert.Equal(JsonValueKind.Null, entries[1].GetProperty("snapshotPath").ValueKind); + Assert.Equal("old", File.ReadAllText(Path.Combine(Target, "old"))); + Assert.False(File.Exists(Path.Combine(Target, "added"))); + }); + Assert.True(File.Exists(intent)); + Assert.Equal("new", File.ReadAllText(Path.Combine(Target, "old"))); + Assert.Equal("added content", File.ReadAllText(Path.Combine(Target, "added"))); + Assert.Equal("old", File.ReadAllText(old.SnapshotPath!)); + } + + [Fact] + public void ModifiedTargetOrMissingSnapshotStopsBeforeAnyWrite() + { + File.WriteAllText(Path.Combine(Target, "old"), "modified"); + var added = Entry("added", "new"); + var old = Entry("old", "new old", "original"); + Assert.ThrowsAny(() => ControlledFullZipApply.Apply(Plan(added, old))); + Assert.False(File.Exists(Path.Combine(Target, "added"))); + Assert.Empty(Directory.GetFiles(State)); + File.WriteAllText(Path.Combine(Target, "old"), "original"); + File.Delete(old.SnapshotPath!); + Assert.ThrowsAny(() => ControlledFullZipApply.Apply(Plan(added, old))); + Assert.False(File.Exists(Path.Combine(Target, "added"))); + Assert.Empty(Directory.GetFiles(State)); + } + + [Fact] + public void RejectsWrongSnapshotAndPayloadHashesBeforeWrites() + { + File.WriteAllText(Path.Combine(Target, "old"), "old"); + var old = Entry("old", "new", "old"); + File.WriteAllText(old.SnapshotPath!, "corrupt"); + Assert.ThrowsAny(() => ControlledFullZipApply.Apply(Plan(Entry("added", "new"), old))); + File.WriteAllText(old.SnapshotPath!, "old"); + File.WriteAllText(old.StagedPath, "corrupt"); + Assert.ThrowsAny(() => ControlledFullZipApply.Apply(Plan(Entry("other", "new"), old))); + Assert.Empty(Directory.GetFiles(State)); + Assert.Equal("old", File.ReadAllText(Path.Combine(Target, "old"))); + } + + [Theory] + [InlineData("protected\\file", "protected")] + [InlineData("protected", "protected\\file")] + [InlineData(".backups\\file", "unrelated")] + [InlineData("a\\..\\file", "unrelated")] + [InlineData("file:stream", "unrelated")] + [InlineData("CON.txt", "unrelated")] + [InlineData("folder/file", "unrelated")] + public void RejectsProtectedAndUnsafePaths(string name, string protect) + { + var plan = new ControlledFullZipPlan(Target, State, new[] { Entry(name, "new") }, new[] { protect }); + Assert.Throws(() => ControlledFullZipApply.Apply(plan)); + Assert.Empty(Directory.GetFiles(State)); + } + + [Fact] + public void InterruptionRetainsIntentAndSnapshotsWithoutTouchingOtherTargets() + { + File.WriteAllText(Path.Combine(Target, "old"), "old"); + var old = Entry("old", "new", "old"); + var other = Entry("other", "other"); + Assert.Throws(() => ControlledFullZipApply.Apply(Plan(old, other), + afterWrite: _ => throw new InvalidOperationException("interrupted"))); + Assert.Equal("new", File.ReadAllText(Path.Combine(Target, "old"))); + Assert.False(File.Exists(Path.Combine(Target, "other"))); + Assert.Equal("old", File.ReadAllText(old.SnapshotPath!)); + Assert.Single(Directory.GetFiles(State, "*.json")); + } + + [Fact] + public void ConflictAfterIntentIsRetainedAndDoesNotOverwrite() + { + var entry = Entry("new", "payload"); + Assert.ThrowsAny(() => ControlledFullZipApply.Apply(Plan(entry), + () => File.WriteAllText(Path.Combine(Target, "new"), "unexpected"))); + Assert.Equal("unexpected", File.ReadAllText(Path.Combine(Target, "new"))); + Assert.Single(Directory.GetFiles(State, "*.json")); + } + + [Fact] + public void FailureImmediatelyAfterIntentLeavesEveryTargetUnchanged() + { + File.WriteAllText(Path.Combine(Target, "old"), "old"); + var old = Entry("old", "new", "old"); + Assert.Throws(() => ControlledFullZipApply.Apply( + Plan(old, Entry("added", "new")), () => throw new InvalidOperationException("stop"))); + Assert.Equal("old", File.ReadAllText(Path.Combine(Target, "old"))); + Assert.False(File.Exists(Path.Combine(Target, "added"))); + Assert.Equal("old", File.ReadAllText(old.SnapshotPath!)); + Assert.Single(Directory.GetFiles(State, "*.json")); + } + + [Fact] + public void PreexistingNewTargetAndDuplicatePathsFailDuringPreflight() + { + File.WriteAllText(Path.Combine(Target, "new"), "keep"); + Assert.ThrowsAny(() => ControlledFullZipApply.Apply(Plan(Entry("new", "payload")))); + Assert.Throws(() => ControlledFullZipApply.Apply( + Plan(Entry("another", "one"), Entry("ANOTHER", "two")))); + Assert.Equal("keep", File.ReadAllText(Path.Combine(Target, "new"))); + Assert.Empty(Directory.GetFiles(State)); + } + + [Fact] + public void OccupiedTemporaryPathIsRetainedAndNotOverwritten() + { + var entry = Entry("new", "payload"); + string? temporary = null; + Assert.ThrowsAny(() => ControlledFullZipApply.Apply(Plan(entry), () => + { + using var json = JsonDocument.Parse(File.ReadAllText(Assert.Single(Directory.GetFiles(State, "*.json")))); + temporary = json.RootElement.GetProperty("entries")[0].GetProperty("temporaryPath").GetString()!; + File.WriteAllText(temporary, "unknown"); + })); + Assert.Equal("unknown", File.ReadAllText(temporary!)); + Assert.False(File.Exists(Path.Combine(Target, "new"))); + Assert.Single(Directory.GetFiles(State, "*.json")); + } + + [Fact] + public void RejectsHardLinkedTargetAndAlternateStreams() + { + var target = Path.Combine(Target, "old"); + File.WriteAllText(target, "old"); + string link = Path.Combine(Input, "hardlink"); + Assert.True(CreateHardLink(link, target, IntPtr.Zero)); + var entry = Entry("old", "new", "old"); + Assert.ThrowsAny(() => ControlledFullZipApply.Apply(Plan(entry))); + File.Delete(link); + File.WriteAllText(target + ":extra", "extra"); + Assert.Throws(() => ControlledFullZipApply.Apply(Plan(entry))); + Assert.Equal("old", File.ReadAllText(target)); + Assert.Empty(Directory.GetFiles(State)); + } + + [Fact] + public void RejectsReparsePointInTargetPath() + { + Directory.CreateDirectory(Path.Combine(Input, "elsewhere")); + using var process = System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo + { + FileName = Environment.GetEnvironmentVariable("ComSpec")!, + Arguments = $"/c mklink /J \"{Path.Combine(Target, "link")}\" \"{Path.Combine(Input, "elsewhere")}\"", + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardOutput = true, + RedirectStandardError = true + })!; + process.WaitForExit(); + Assert.Equal(0, process.ExitCode); + try + { + Assert.Throws(() => ControlledFullZipApply.Apply(Plan(Entry("link\\file", "new")))); + Assert.Empty(Directory.GetFiles(State)); + } + finally { Directory.Delete(Path.Combine(Target, "link")); } + } + + private ControlledFullZipPlan Plan(params ControlledFullZipEntry[] entries) => + new(Target, State, entries, Array.Empty()); + + private ControlledFullZipEntry Entry(string name, string payload, string? original = null) + { + string stage = Path.Combine(Input, Guid.NewGuid().ToString("N")); + File.WriteAllText(stage, payload); + string? snapshot = null; + if (original != null) + { + snapshot = Path.Combine(Input, Guid.NewGuid().ToString("N")); + File.WriteAllText(snapshot, original); + } + return new ControlledFullZipEntry(name, stage, Hash(payload), snapshot, original == null ? null : Hash(original)); + } + + private static string Hash(string value) => + Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(value))); + + [System.Runtime.InteropServices.DllImport("kernel32.dll", CharSet = System.Runtime.InteropServices.CharSet.Unicode, SetLastError = true)] + private static extern bool CreateHardLink(string file, string existingFile, IntPtr securityAttributes); + + public void Dispose() + { + if (Directory.Exists(_root)) Directory.Delete(_root, true); + } +} diff --git a/tests/CoreTest/Compress/ControlledFullZipPrepareTests.cs b/tests/CoreTest/Compress/ControlledFullZipPrepareTests.cs new file mode 100644 index 00000000..a70771a6 --- /dev/null +++ b/tests/CoreTest/Compress/ControlledFullZipPrepareTests.cs @@ -0,0 +1,133 @@ +using System.IO.Compression; +using System.Security.Cryptography; +using GeneralUpdate.Core.Compress; + +namespace CoreTest.Compress; + +public sealed class ControlledFullZipPrepareTests : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), "gu-prepare-" + Guid.NewGuid().ToString("N")); + private string Target => Path.Combine(_root, "target"); + private string Backup => Path.Combine(_root, "backup"); + private string State => Path.Combine(_root, "state"); + private string Stage => Path.Combine(_root, "stage"); + + public ControlledFullZipPrepareTests() + { + foreach (var path in new[] { Target, Backup, State, Stage }) Directory.CreateDirectory(path); + } + + [WindowsFact] + public void SnapshotsCompleteWriteSetBeforeApplying() + { + Directory.CreateDirectory(Path.Combine(Target, "nested")); + File.WriteAllText(Path.Combine(Target, "nested", "old"), "original"); + File.WriteAllText(Path.Combine(Target, "unknown"), "keep"); + using var staged = Zip(("nested/old", "updated"), ("new", "added")); + var plan = ControlledFullZipPrepare.Prepare(staged, Target, State, Backup, ["data"]); + Assert.Equal("original", File.ReadAllText(Path.Combine(Backup, "nested", "old"))); + Assert.Equal("original", File.ReadAllText(Path.Combine(Target, "nested", "old"))); + Assert.Null(plan.Entries[1].SnapshotPath); + Assert.Empty(Directory.GetFiles(State)); + ControlledFullZipApply.Apply(plan); + Assert.Equal("updated", File.ReadAllText(Path.Combine(Target, "nested", "old"))); + Assert.Equal("added", File.ReadAllText(Path.Combine(Target, "new"))); + Assert.Equal("keep", File.ReadAllText(Path.Combine(Target, "unknown"))); + } + + [WindowsFact] + public void ProtectedTargetIsRejectedBeforeAnySnapshot() + { + File.WriteAllText(Path.Combine(Target, "old"), "original"); + Directory.CreateDirectory(Path.Combine(Target, "data")); + using var staged = Zip(("old", "updated"), ("data/private", "forbidden")); + Assert.Throws(() => + ControlledFullZipPrepare.Prepare(staged, Target, State, Backup, ["data"])); + Assert.Empty(Directory.GetFileSystemEntries(Backup)); + Assert.Equal("original", File.ReadAllText(Path.Combine(Target, "old"))); + } + + [WindowsFact] + public void OccupiedBackupAndOverlappingRootsAreRejected() + { + using var staged = Zip(("new", "added")); + File.WriteAllText(Path.Combine(Backup, "unknown"), "keep"); + Assert.Throws(() => ControlledFullZipPrepare.Prepare(staged, Target, State, Backup, [])); + Assert.Equal("keep", File.ReadAllText(Path.Combine(Backup, "unknown"))); + Assert.Throws(() => ControlledFullZipPrepare.Prepare(staged, Target, State, Target, [])); + } + + [WindowsFact] + public void ChangedTargetAfterSnapshotStopsBeforeApplying() + { + File.WriteAllText(Path.Combine(Target, "old"), "original"); + using var staged = Zip(("old", "updated")); + var plan = ControlledFullZipPrepare.Prepare(staged, Target, State, Backup, []); + File.WriteAllText(Path.Combine(Target, "old"), "user change"); + Assert.ThrowsAny(() => ControlledFullZipApply.Apply(plan)); + Assert.Equal("user change", File.ReadAllText(Path.Combine(Target, "old"))); + Assert.Equal("original", File.ReadAllText(Path.Combine(Backup, "old"))); + Assert.Empty(Directory.GetFiles(State)); + } + + [WindowsFact] + public void DirectoryTargetIsRejectedBeforeAnySnapshot() + { + File.WriteAllText(Path.Combine(Target, "old"), "original"); + Directory.CreateDirectory(Path.Combine(Target, "directory")); + using var staged = Zip(("old", "updated"), ("directory", "not a directory")); + Assert.Throws(() => + ControlledFullZipPrepare.Prepare(staged, Target, State, Backup, [])); + Assert.Empty(Directory.GetFileSystemEntries(Backup)); + Assert.Equal("original", File.ReadAllText(Path.Combine(Target, "old"))); + } + + [WindowsFact] + public void IntentRetainsStagedFilesAfterApplyFailure() + { + var staged = Zip(("new", "added")); + var stagedFile = staged.Entries[0].StagedPath; + try + { + var plan = ControlledFullZipPrepare.Prepare(staged, Target, State, Backup, []); + Assert.Throws(() => ControlledFullZipApply.Apply(plan, () => + { + staged.RetainForRecovery(); + throw new InvalidOperationException("interrupted"); + })); + } + finally { staged.Dispose(); } + Assert.True(File.Exists(stagedFile)); + Assert.Single(Directory.GetFiles(State, "*.json")); + Assert.False(File.Exists(Path.Combine(Target, "new"))); + } + + private StagedZip Zip(params (string Name, string Content)[] entries) + { + string path = Path.Combine(_root, Guid.NewGuid().ToString("N") + ".zip"); + using (var file = File.Create(path)) + using (var zip = new ZipArchive(file, ZipArchiveMode.Create)) + foreach (var entry in entries) + { + using var writer = new StreamWriter(zip.CreateEntry(entry.Name).Open()); + writer.Write(entry.Content); + } + using var stream = File.OpenRead(path); + using var sha = SHA256.Create(); + return FullZipStager.Stage(path, Stage, Convert.ToHexString(sha.ComputeHash(stream)).ToLowerInvariant(), + 10, 1024 * 1024, 2 * 1024 * 1024); + } + + public void Dispose() + { + if (Directory.Exists(_root)) Directory.Delete(_root, true); + } + + private sealed class WindowsFactAttribute : FactAttribute + { + public WindowsFactAttribute() + { + if (!OperatingSystem.IsWindows()) Skip = "The controlled file implementation requires Windows."; + } + } +} diff --git a/tests/CoreTest/Compress/ControlledWorkerEntryTests.cs b/tests/CoreTest/Compress/ControlledWorkerEntryTests.cs new file mode 100644 index 00000000..e8612c3b --- /dev/null +++ b/tests/CoreTest/Compress/ControlledWorkerEntryTests.cs @@ -0,0 +1,41 @@ +using System.Diagnostics; + +namespace CoreTest.Compress; + +public sealed class ControlledWorkerEntryTests +{ + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task RejectsWithoutProductionAuthorizationAndLeavesStateUntouched(bool validLookingArguments) + { + var root = Path.Combine(Path.GetTempPath(), "gu-worker-denied-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(root); + try + { + var file = Path.Combine(root, "existing.txt"); + File.WriteAllText(file, "user data"); + var dll = Path.Combine(AppContext.BaseDirectory, "ControlledWorker", "GeneralUpdate.ControlledWorker.dll"); + var start = new ProcessStartInfo("dotnet") + { + UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true + }; + start.ArgumentList.Add(dll); + if (validLookingArguments) + { + foreach (var arg in new[] { "--bowl-controlled", "--attempt", Guid.NewGuid().ToString("D"), "--state-root", root }) + start.ArgumentList.Add(arg); + } + using var worker = Process.Start(start) ?? throw new InvalidOperationException("Worker did not start."); + var stdout = worker.StandardOutput.ReadToEndAsync(); + var stderr = worker.StandardError.ReadToEndAsync(); + await worker.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(15)); + Assert.Equal(2, worker.ExitCode); + Assert.Empty(await stdout); + Assert.Contains("authorization is not implemented", await stderr); + Assert.Equal("user data", File.ReadAllText(file)); + Assert.Single(Directory.GetFileSystemEntries(root)); + } + finally { Directory.Delete(root, true); } + } +} diff --git a/tests/CoreTest/Compress/FullZipStagerTests.cs b/tests/CoreTest/Compress/FullZipStagerTests.cs new file mode 100644 index 00000000..83a44275 --- /dev/null +++ b/tests/CoreTest/Compress/FullZipStagerTests.cs @@ -0,0 +1,220 @@ +using System.IO.Compression; +using System.Security.Cryptography; +using GeneralUpdate.Core.Compress; + +namespace CoreTest.Compress; + +public sealed class FullZipStagerTests : IDisposable +{ + private readonly string _root = Path.Combine(Environment.CurrentDirectory, "zip-stage-tests-" + Guid.NewGuid().ToString("N")); + private string ZipPath => Path.Combine(_root, "package.zip"); + private string Parent => Path.Combine(_root, "staging"); + + public FullZipStagerTests() + { + Directory.CreateDirectory(Parent); + } + + [Fact] + public void StagesFilesAndHashesAndDisposesOnlyItsOwnDirectory() + { + CreateZip(("folder/", "", 0), ("folder/hello.txt", "hello", 0), ("other.txt", "world", 0)); + var untouched = Path.Combine(Parent, "untouched"); + Directory.CreateDirectory(untouched); + File.WriteAllText(Path.Combine(untouched, "keep"), "keep"); + + string stagedDirectory; + using (var result = Stage()) + { + stagedDirectory = result.DirectoryPath; + Assert.Equal(2, result.Entries.Count); + Assert.Equal("folder/hello.txt", result.Entries[0].RelativePath); + Assert.Equal("hello", File.ReadAllText(result.Entries[0].StagedPath)); + Assert.Equal(Hex(SHA256.HashData(System.Text.Encoding.UTF8.GetBytes("hello"))), result.Entries[0].Sha256); + Assert.Equal("world", File.ReadAllText(result.Entries[1].StagedPath)); + Assert.NotEqual(result.Entries[0].StagedPath, result.Entries[1].StagedPath); + Assert.All(result.Entries, x => Assert.Equal(stagedDirectory, Path.GetDirectoryName(x.StagedPath))); + } + Assert.False(Directory.Exists(stagedDirectory)); + Assert.True(File.Exists(Path.Combine(untouched, "keep"))); + } + + [Theory] + [InlineData("/root")] + [InlineData("C:/drive")] + [InlineData("file:stream")] + [InlineData("a\\b")] + [InlineData("../evil")] + [InlineData("a/./b")] + [InlineData("a//b")] + [InlineData("name.")] + [InlineData("name ")] + [InlineData("CON.txt")] + [InlineData("aux .txt")] + [InlineData("COM¹.bin")] + [InlineData("LPT9")] + [InlineData(".BACKUPS/file")] + [InlineData("a/\u0001b")] + [InlineData("a?/b")] + [InlineData("a//")] + public void RejectsUnsafeNames(string name) + { + CreateZip((name, "", 0)); + Assert.Throws(() => Stage()); + Assert.Empty(Directory.GetFileSystemEntries(Parent)); + } + + [Theory] + [InlineData("a.txt", "A.TXT")] + [InlineData("a", "a/b")] + [InlineData("a/b", "A")] + [InlineData("a/", "A/")] + [InlineData("a/", "a")] + public void RejectsDuplicateAndConflictingPaths(string first, string second) + { + CreateZip((first, "", 0), (second, "", 0)); + Assert.Throws(() => Stage()); + Assert.Empty(Directory.GetFileSystemEntries(Parent)); + } + + [Theory] + [InlineData(0xA0000000u)] // Unix symbolic link + [InlineData(0x10000000u)] // Unix FIFO + [InlineData(0x60000000u)] // Unix block device + [InlineData(0x00000400u)] // Windows reparse point + [InlineData(0x00000040u)] // Windows device + [InlineData(0x04000000u)] // Windows reparse point in the upper attributes + [InlineData(0x00400000u)] // Windows device in the upper attributes + [InlineData(0x40000000u)] // Unix directory without a directory path + [InlineData(0x84000000u)] // Unix regular file with special mode bits + public void RejectsSpecialEntries(uint attributes) + { + CreateZip(("unsafe", "", unchecked((int)attributes))); + Assert.Throws(() => Stage()); + Assert.Empty(Directory.GetFileSystemEntries(Parent)); + } + + [Fact] + public void AllowsExplicitDirectoryAfterAnImplicitDirectory() + { + CreateZip(("Dir/child", "content", 0), ("dir/", "", 0)); + using var result = Stage(); + Assert.Single(result.Entries); + } + + [Fact] + public void AllowsUnixRegularFileWithExecutablePermissions() + { + CreateZip(("executable", "content", unchecked((int)0x81ed0000u))); + using var result = Stage(); + Assert.Single(result.Entries); + } + + [Fact] + public void EnforcesEntryAndExpandedSizeLimits() + { + CreateZip(("one", "123", 0), ("two", "456", 0)); + Assert.Throws(() => Stage(maxEntries: 1)); + Assert.Throws(() => Stage(maxFile: 2)); + Assert.Throws(() => Stage(maxTotal: 5)); + Assert.Empty(Directory.GetFileSystemEntries(Parent)); + using var result = Stage(maxEntries: 2, maxFile: 3, maxTotal: 6); + Assert.Equal(2, result.Entries.Count); + } + + [Fact] + public void RejectsMissingInvalidAndWrongHash() + { + CreateZip(("one", "data", 0)); + Assert.Throws(() => FullZipStager.Stage(ZipPath, Parent, "", 10, 100, 100)); + Assert.Throws(() => FullZipStager.Stage(ZipPath, Parent, new string('z', 64), 10, 100, 100)); + Assert.Throws(() => FullZipStager.Stage(ZipPath, Parent, new string('0', 64), 10, 100, 100)); + Assert.Empty(Directory.GetFileSystemEntries(Parent)); + } + + [Fact] + public void RejectsDirectoryContent() + { + CreateZip(("dir/", "not empty", 0)); + Assert.Throws(() => Stage()); + Assert.Empty(Directory.GetFileSystemEntries(Parent)); + } + + [Fact] + public void ReportsCleanupFailureWithoutDeletingUnknownFiles() + { + CreateZip(("one", "data", 0)); + var result = Stage(); + string unexpected = Path.Combine(result.DirectoryPath, "unexpected"); + File.WriteAllText(unexpected, "keep"); + Assert.Throws(() => result.Dispose()); + Assert.True(File.Exists(unexpected)); + File.Delete(unexpected); + result.Dispose(); + Assert.False(Directory.Exists(result.DirectoryPath)); + } + + [Fact] + public void CleansUpPartialStagingAfterCorruptCompressedData() + { + CreateZip(("first", "valid", 0), ("second", new string('x', 500), 0)); + byte[] zip = File.ReadAllBytes(ZipPath); + // Locate the second local header and invalidate the deflate stream. + int firstNameLength = BitConverter.ToUInt16(zip, 26); + int firstExtraLength = BitConverter.ToUInt16(zip, 28); + int firstCompressedLength = BitConverter.ToInt32(zip, 18); + int secondHeader = 30 + firstNameLength + firstExtraLength + firstCompressedLength; + Assert.Equal(0x04034b50, BitConverter.ToInt32(zip, secondHeader)); + int secondData = secondHeader + 30 + BitConverter.ToUInt16(zip, secondHeader + 26) + BitConverter.ToUInt16(zip, secondHeader + 28); + zip[secondData] = 0xff; + File.WriteAllBytes(ZipPath, zip); + Assert.ThrowsAny(() => Stage()); + Assert.Empty(Directory.GetFileSystemEntries(Parent)); + } + + [Fact] + public void RejectsActualContentExceedingDeclaredLengthAndCleansUp() + { + CreateZip(("first", "valid", 0), ("second", new string('x', 500), 0)); + byte[] zip = File.ReadAllBytes(ZipPath); + int end = zip.Length - 22; + Assert.Equal(0x06054b50, BitConverter.ToInt32(zip, end)); + int central = BitConverter.ToInt32(zip, end + 16); + int second = central + 46 + BitConverter.ToUInt16(zip, central + 28) + + BitConverter.ToUInt16(zip, central + 30) + BitConverter.ToUInt16(zip, central + 32); + Assert.Equal(0x02014b50, BitConverter.ToInt32(zip, second)); + int local = BitConverter.ToInt32(zip, second + 42); + Assert.Equal(0x04034b50, BitConverter.ToInt32(zip, local)); + // Make both headers and CRC agree with the truncated prefix. The compressed + // stream still expands to 500 bytes and must be read to completion. + Array.Copy(BitConverter.GetBytes(0x8cdc1683u), 0, zip, second + 16, 4); + Array.Copy(BitConverter.GetBytes(0x8cdc1683u), 0, zip, local + 14, 4); + Array.Copy(BitConverter.GetBytes(1), 0, zip, second + 24, 4); + Array.Copy(BitConverter.GetBytes(1), 0, zip, local + 22, 4); + File.WriteAllBytes(ZipPath, zip); + Assert.ThrowsAny(() => Stage()); + Assert.Empty(Directory.GetFileSystemEntries(Parent)); + } + + private StagedZip Stage(int maxEntries = 100, long maxFile = 10000, long maxTotal = 10000) + => FullZipStager.Stage(ZipPath, Parent, Hex(SHA256.HashData(File.ReadAllBytes(ZipPath))), maxEntries, maxFile, maxTotal); + + private static string Hex(byte[] value) => Convert.ToHexString(value).ToLowerInvariant(); + + private void CreateZip(params (string Name, string Content, int Attributes)[] entries) + { + using var archive = ZipFile.Open(ZipPath, ZipArchiveMode.Create); + foreach (var item in entries) + { + var entry = archive.CreateEntry(item.Name); + entry.ExternalAttributes = item.Attributes; + if (item.Content.Length != 0) + { + using var writer = new StreamWriter(entry.Open()); + writer.Write(item.Content); + } + } + } + + public void Dispose() => Directory.Delete(_root, true); +} diff --git a/tests/CoreTest/Configuration/InstallationIdentityTests.cs b/tests/CoreTest/Configuration/InstallationIdentityTests.cs new file mode 100644 index 00000000..c2db630f --- /dev/null +++ b/tests/CoreTest/Configuration/InstallationIdentityTests.cs @@ -0,0 +1,37 @@ +using GeneralUpdate.Core.Configuration; + +namespace CoreTest.Configuration; + +public sealed class InstallationIdentityTests +{ + [Fact] + public void Identity_IsStableConcurrentAndScopedToInstallation() + { + var root = Path.Combine(Path.GetTempPath(), "installation-id-" + Guid.NewGuid().ToString("N")); + try + { + var config = new UpdateContext { InstallPath = Path.Combine(root, "app"), DiagnosticsDirectory = Path.Combine(root, "state") }; + var ids = Enumerable.Range(0, 20).AsParallel().Select(_ => InstallationIdentity.GetOrCreate(config)).ToArray(); + Assert.Single(ids.Distinct()); + Assert.True(Guid.TryParseExact(ids[0], "D", out _)); + Assert.Equal(ids[0], InstallationIdentity.GetOrCreate(config)); + var other = new UpdateContext { InstallPath = Path.Combine(root, "other"), DiagnosticsDirectory = config.DiagnosticsDirectory }; + Assert.NotEqual(ids[0], InstallationIdentity.GetOrCreate(other)); + } + finally { if (Directory.Exists(root)) Directory.Delete(root, true); } + } + + [Fact] + public void CorruptIdentity_FailsInsteadOfChangingDevice() + { + var root = Path.Combine(Path.GetTempPath(), "installation-id-" + Guid.NewGuid().ToString("N")); + try + { + var config = new UpdateContext { InstallPath = Path.Combine(root, "app"), DiagnosticsDirectory = Path.Combine(root, "state") }; + InstallationIdentity.GetOrCreate(config); + File.WriteAllText(Assert.Single(Directory.GetFiles(Path.Combine(config.DiagnosticsDirectory, "installations"), "*.id")), "corrupt"); + Assert.Throws(() => InstallationIdentity.GetOrCreate(config)); + } + finally { if (Directory.Exists(root)) Directory.Delete(root, true); } + } +} diff --git a/tests/CoreTest/Configuration/ManifestInfoSaveTests.cs b/tests/CoreTest/Configuration/ManifestInfoSaveTests.cs new file mode 100644 index 00000000..38f00356 --- /dev/null +++ b/tests/CoreTest/Configuration/ManifestInfoSaveTests.cs @@ -0,0 +1,78 @@ +using System; +using System.IO; +using GeneralUpdate.Core.Configuration; +using Xunit; + +namespace CoreTest.Configuration; + +/// +/// Tests for atomicity and the +/// load/modify/save round trip that drives the update loop's version tracking. +/// +public class ManifestInfoSaveTests : IDisposable +{ + private readonly string _dir = Path.Combine(Path.GetTempPath(), $"ManifestSave_{Guid.NewGuid():N}"); + + public ManifestInfoSaveTests() => Directory.CreateDirectory(_dir); + + public void Dispose() + { + try { Directory.Delete(_dir, recursive: true); } catch { /* ignore */ } + } + + private string ManifestPath => Path.Combine(_dir, ManifestInfo.FileName); + + [Fact] + public void Save_CreatesReadableManifest() + { + var manifest = new ManifestInfo + { + MainAppName = "app.exe", + UpdateAppName = "Update.exe", + ClientVersion = "2.1.0", + ProductId = "prod-1" + }; + + manifest.Save(ManifestPath); + + Assert.True(File.Exists(ManifestPath)); + var loaded = ManifestInfo.Load(ManifestPath); + Assert.NotNull(loaded); + Assert.Equal("2.1.0", loaded!.ClientVersion); + Assert.Equal("app.exe", loaded.MainAppName); + Assert.Equal("prod-1", loaded.ProductId); + } + + [Fact] + public void Save_LeavesNoTempResidue() + { + // The manifest drives the next update cycle's version decision; the writer + // publishes via a sibling ".tmp-*" file that must be gone once the call + // returns, or stale temp files accumulate in the install directory. + var manifest = new ManifestInfo { ClientVersion = "1.0.0" }; + + manifest.Save(ManifestPath); + + Assert.True(File.Exists(ManifestPath)); + var residue = Directory.GetFiles(_dir, ManifestInfo.FileName + ".tmp-*"); + Assert.Empty(residue); + } + + [Fact] + public void Save_OverwritesPreviousVersion() + { + // UpdateStrategy writes the new version back after every successful update; + // the second save must fully replace the first file (the old writer could + // leave a torn file if the process died mid-write). + var manifest = new ManifestInfo { ClientVersion = "1.0.0" }; + manifest.Save(ManifestPath); + + manifest.ClientVersion = "3.0.0"; + manifest.Save(ManifestPath); + + var loaded = ManifestInfo.Load(ManifestPath); + Assert.NotNull(loaded); + Assert.Equal("3.0.0", loaded!.ClientVersion); + Assert.Empty(Directory.GetFiles(_dir, "*.tmp-*")); + } +} diff --git a/tests/CoreTest/Configuration/UpdateConfigurationTests.cs b/tests/CoreTest/Configuration/UpdateConfigurationTests.cs index cdc5fa33..4dd95f23 100644 --- a/tests/CoreTest/Configuration/UpdateConfigurationTests.cs +++ b/tests/CoreTest/Configuration/UpdateConfigurationTests.cs @@ -1,3 +1,4 @@ +using CoreTest.TestSupport; using GeneralUpdate.Core.Configuration; namespace CoreTest.Configuration; @@ -118,7 +119,7 @@ public void AllProperties_CanBeSetAndGet() MainAppName = "MainApp", InstallPath = "C:\\MyApp", UpdateLogUrl = "https://logs.example.com", - AppSecretKey = "secret-key", + AppSecretKey = FixtureValues.Secret("config"), ClientVersion = "1.2.3", Files = new List { "a.dll" }, Formats = new List { ".log" }, @@ -126,7 +127,7 @@ public void AllProperties_CanBeSetAndGet() ReportUrl = "https://report.example.com", Bowl = "Bowl.exe", Scheme = "https", - Token = "bearer-token", + Token = FixtureValues.Token("config"), DriverDirectory = "C:\\Drivers" }; @@ -134,7 +135,7 @@ public void AllProperties_CanBeSetAndGet() Assert.Equal("MainApp", config.MainAppName); Assert.Equal("C:\\MyApp", config.InstallPath); Assert.Equal("https://logs.example.com", config.UpdateLogUrl); - Assert.Equal("secret-key", config.AppSecretKey); + Assert.Equal(FixtureValues.Secret("config"), config.AppSecretKey); Assert.Equal("1.2.3", config.ClientVersion); Assert.Single(config.Files); Assert.Single(config.Formats); @@ -142,7 +143,7 @@ public void AllProperties_CanBeSetAndGet() Assert.Equal("https://report.example.com", config.ReportUrl); Assert.Equal("Bowl.exe", config.Bowl); Assert.Equal("https", config.Scheme); - Assert.Equal("bearer-token", config.Token); + Assert.Equal(FixtureValues.Token("config"), config.Token); Assert.Equal("C:\\Drivers", config.DriverDirectory); } } diff --git a/tests/CoreTest/Configuration/UpdateContextWiringTests.cs b/tests/CoreTest/Configuration/UpdateContextWiringTests.cs index 19cbc8d1..9a9c58e9 100644 --- a/tests/CoreTest/Configuration/UpdateContextWiringTests.cs +++ b/tests/CoreTest/Configuration/UpdateContextWiringTests.cs @@ -1,5 +1,6 @@ using System; using System.IO; +using CoreTest.TestSupport; using GeneralUpdate.Core; using GeneralUpdate.Core.Configuration; using Xunit; @@ -231,9 +232,9 @@ private static GeneralUpdateBootstrap MakeBootstrap() MainAppName = "MyApp.exe", ClientVersion = "1.0.0", InstallPath = testDir, - AppSecretKey = "secret", + AppSecretKey = FixtureValues.Secret("wiring"), Scheme = "https", - Token = "token", + Token = FixtureValues.Token("wiring"), }); } diff --git a/tests/CoreTest/Configuration/UpdateRequestTests.cs b/tests/CoreTest/Configuration/UpdateRequestTests.cs index c11a784c..2b922029 100644 --- a/tests/CoreTest/Configuration/UpdateRequestTests.cs +++ b/tests/CoreTest/Configuration/UpdateRequestTests.cs @@ -1,3 +1,4 @@ +using CoreTest.TestSupport; using GeneralUpdate.Core.Configuration; namespace CoreTest.Configuration; @@ -17,7 +18,7 @@ public void Validate_UpdateUrlNullOrWhitespace_ThrowsArgumentException(string up UpdateUrl = updateUrl, UpdateAppName = "TestApp", MainAppName = "MainApp", - AppSecretKey = "secret", + AppSecretKey = FixtureValues.Secret("request"), ClientVersion = "1.0.0", InstallPath = "C:\\app" }; @@ -33,7 +34,7 @@ public void Validate_UpdateUrlNotWellFormedUri_ThrowsArgumentException() UpdateUrl = "not_a_valid_uri!!!", UpdateAppName = "TestApp", MainAppName = "MainApp", - AppSecretKey = "secret", + AppSecretKey = FixtureValues.Secret("request"), ClientVersion = "1.0.0", InstallPath = "C:\\app" }; @@ -50,7 +51,7 @@ public void Validate_UpdateUrlValid_DoesNotThrowForUpdateUrl(string url) UpdateUrl = url, UpdateAppName = "TestApp", MainAppName = "MainApp", - AppSecretKey = "secret", + AppSecretKey = FixtureValues.Secret("request"), ClientVersion = "1.0.0", InstallPath = "C:\\app" }; @@ -67,7 +68,7 @@ public void Validate_UpdateLogUrlNull_Allowed() UpdateLogUrl = null, UpdateAppName = "TestApp", MainAppName = "MainApp", - AppSecretKey = "secret", + AppSecretKey = FixtureValues.Secret("request"), ClientVersion = "1.0.0", InstallPath = "C:\\app" }; @@ -84,7 +85,7 @@ public void Validate_UpdateLogUrlInvalid_ThrowsArgumentException() UpdateLogUrl = "not_a_uri!!!", UpdateAppName = "TestApp", MainAppName = "MainApp", - AppSecretKey = "secret", + AppSecretKey = FixtureValues.Secret("request"), ClientVersion = "1.0.0", InstallPath = "C:\\app" }; @@ -103,7 +104,7 @@ public void Validate_UpgradeAppNameNullOrWhitespace_NoException(string appName) UpdateUrl = "https://api.example.com", UpdateAppName = appName, MainAppName = "MainApp", - AppSecretKey = "secret", + AppSecretKey = FixtureValues.Secret("request"), ClientVersion = "1.0.0", InstallPath = "C:\\app" }; @@ -123,7 +124,7 @@ public void Validate_MainAppNameNullOrWhitespace_NoException(string mainUpgradeA UpdateUrl = "https://api.example.com", UpdateAppName = "TestApp", MainAppName = mainUpgradeAppName, - AppSecretKey = "secret", + AppSecretKey = FixtureValues.Secret("request"), ClientVersion = "1.0.0", InstallPath = "C:\\app" }; @@ -161,7 +162,7 @@ public void Validate_ClientVersionNullOrWhitespace_NoException(string clientVers UpdateUrl = "https://api.example.com", UpdateAppName = "TestApp", MainAppName = "MainApp", - AppSecretKey = "secret", + AppSecretKey = FixtureValues.Secret("request"), ClientVersion = clientVersion, InstallPath = "C:\\app" }; @@ -180,7 +181,7 @@ public void Validate_InstallPathNullOrWhitespace_NoException(string installPath) UpdateUrl = "https://api.example.com", UpdateAppName = "TestApp", MainAppName = "MainApp", - AppSecretKey = "secret", + AppSecretKey = FixtureValues.Secret("request"), ClientVersion = "1.0.0", InstallPath = installPath }; @@ -197,7 +198,7 @@ public void Validate_AllFieldsValid_NoExceptionThrown() UpdateLogUrl = "https://api.example.com/log", UpdateAppName = "TestApp", MainAppName = "MainApp", - AppSecretKey = "secret123", + AppSecretKey = FixtureValues.Secret("request2"), ClientVersion = "1.0.0", InstallPath = "C:\\app" }; diff --git a/tests/CoreTest/Configuration/VersionModelTests.cs b/tests/CoreTest/Configuration/VersionModelTests.cs index e1940622..43ce594b 100644 --- a/tests/CoreTest/Configuration/VersionModelTests.cs +++ b/tests/CoreTest/Configuration/VersionModelTests.cs @@ -1,4 +1,5 @@ using System.Text.Json; +using CoreTest.TestSupport; using GeneralUpdate.Core.Configuration; namespace CoreTest.Configuration; @@ -57,7 +58,7 @@ public void VersionEntry_AllProperties_SetCorrectly() Format = ".zip", Size = 104857600, AuthScheme = "Bearer", - AuthToken = "token-xyz", + AuthToken = FixtureValues.Token("entry"), UpdateLog = "Bug fixes and performance improvements" }; @@ -75,7 +76,7 @@ public void VersionEntry_AllProperties_SetCorrectly() Assert.Equal(".zip", vi.Format); Assert.Equal(104857600, vi.Size); Assert.Equal("Bearer", vi.AuthScheme); - Assert.Equal("token-xyz", vi.AuthToken); + Assert.Equal(FixtureValues.Token("entry"), vi.AuthToken); Assert.Equal("Bug fixes and performance improvements", vi.UpdateLog); } @@ -98,7 +99,7 @@ public void VersionEntry_JsonRoundTrip_AllProperties() Format = ".zip", Size = 5000000, AuthScheme = "Bearer", - AuthToken = "tok", + AuthToken = new string('x', 3), UpdateLog = "v1 release" }; var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true }; @@ -144,7 +145,7 @@ public void VersionEntry_JsonSerialization_UsesCorrectJsonPropertyNames() Format = ".zip", Size = 100, AuthScheme = "Basic", - AuthToken = "t", + AuthToken = new string('x', 1), UpdateLog = "log" }; diff --git a/tests/CoreTest/CoreTest.csproj b/tests/CoreTest/CoreTest.csproj index c0f86ebb..e61978b6 100644 --- a/tests/CoreTest/CoreTest.csproj +++ b/tests/CoreTest/CoreTest.csproj @@ -23,6 +23,7 @@ + @@ -33,4 +34,11 @@ + + + + + + + \ No newline at end of file diff --git a/tests/CoreTest/Diagnostics/DiagnosticsPackagerTests.cs b/tests/CoreTest/Diagnostics/DiagnosticsPackagerTests.cs new file mode 100644 index 00000000..118b6501 --- /dev/null +++ b/tests/CoreTest/Diagnostics/DiagnosticsPackagerTests.cs @@ -0,0 +1,161 @@ +using System.IO.Compression; +using System.Text.Json; +using GeneralUpdate.Core.Diagnostics; + +namespace CoreTest.Diagnostics; + +/// +/// Real-time bundle packing: the in-archive schema-2 manifest.json (server parsed-evidence +/// contract), the generated GUID that doubles as the server idempotency key, and the +/// channel identity propagation. +/// +public sealed class DiagnosticsPackagerTests : IDisposable +{ + private readonly string _installPath = Path.Combine(Path.GetTempPath(), $"gu-diag-pack-{Guid.NewGuid():N}"); + + public void Dispose() + { + try { Directory.Delete(_installPath, true); } catch { /* best effort */ } + } + + private DiagnosticsOptions CreateOptions() => new() + { + Enabled = true, + Url = "https://server.example.test/Fault/UploadArtifact", + AppKey = "ak-123", + ProductId = "p-001", + Platform = 1, + TargetName = "MyApp", + }; + + [Fact] + public async Task CollectAsync_GeneratesGuid_AndWritesSchema2ManifestInsideZip() + { + Directory.CreateDirectory(_installPath); + var collector = new DiagnosticsCollector(CreateOptions()); + + var bundle = await collector.CollectAsync(new DiagnosticsCollectRequest( + _installPath, + DiagnosticsKinds.Rollback, + "1.0.2", + "self-check failed: process exited with code -1", + RecordId: 42, + RecordType: 1, + RollbackResultJson: "{ \"filesRestored\": true }"), CancellationToken.None); + + Assert.NotNull(bundle); + Assert.False(string.IsNullOrWhiteSpace(bundle!.Manifest.Guid)); + Assert.Equal("selfcheck", bundle.Manifest.Kind); + Assert.Equal("ak-123", bundle.Manifest.AppKey); + Assert.Equal("p-001", bundle.Manifest.ProductId); + Assert.Equal(1, bundle.Manifest.Platform); + Assert.Equal("MyApp", bundle.Manifest.TargetName); + Assert.Equal(42, bundle.Manifest.RecordId); + Assert.Equal(1, bundle.Manifest.RecordType); + + // In-archive manifest: same schema-2 disk contract as the Bowl outbox. + using var archive = ZipFile.OpenRead(bundle.ZipPath); + var manifestEntry = Assert.Single(archive.Entries, e => e.FullName == "manifest.json"); + using var stream = manifestEntry.Open(); + var manifest = JsonSerializer.Deserialize(stream); + Assert.NotNull(manifest); + Assert.Equal(2, manifest!.Schema); + Assert.Equal(bundle.Manifest.Guid, manifest.Guid); + Assert.Equal("selfcheck", manifest.Kind); + Assert.Equal("1.0.2", manifest.Version); + Assert.Equal("MyApp", manifest.TargetName); + + TryDelete(bundle.ZipPath); + } + + [Fact] + public async Task CollectAsync_BareInstallPath_StillProducesManifestOnlyBundle() + { + // The in-archive manifest.json is always written, so even an install path without any + // other artifact yields a deliverable (server-parseable) bundle — the "nothing to send" + // case only remains for packs that fail the size cap. + Directory.CreateDirectory(_installPath); + var collector = new DiagnosticsCollector(CreateOptions()); + var request = new DiagnosticsCollectRequest(_installPath, DiagnosticsKinds.SelfCheck, "1.0.2", "reason"); + + var bundle = await collector.CollectAsync(request, CancellationToken.None); + + Assert.NotNull(bundle); + using var archive = ZipFile.OpenRead(bundle!.ZipPath); + Assert.Contains(archive.Entries, e => e.FullName == "manifest.json"); + TryDelete(bundle.ZipPath); + } + + [Fact] + public async Task CollectAsync_InZipManifestListsRetainedEntries() + { + // The server audits archive contents via the in-zip manifest — its files list must + // declare the entries ACTUALLY retained, not an empty list. + Directory.CreateDirectory(_installPath); + File.WriteAllText(Path.Combine(_installPath, GeneralUpdate.Core.Configuration.ManifestInfo.FileName), "{}"); + var collector = new DiagnosticsCollector(CreateOptions()); + + var bundle = await collector.CollectAsync(new DiagnosticsCollectRequest( + _installPath, + DiagnosticsKinds.Rollback, + "1.0.2", + "reason", + RollbackResultJson: "{ \"filesRestored\": true }"), CancellationToken.None); + + Assert.NotNull(bundle); + using (var archive = ZipFile.OpenRead(bundle!.ZipPath)) + { + var entry = Assert.Single(archive.Entries, e => e.FullName == "manifest.json"); + using var stream = entry.Open(); + var manifest = JsonSerializer.Deserialize(stream); + Assert.NotNull(manifest); + Assert.Contains("manifest.json", manifest!.Files); + Assert.Contains("rollback-result.json", manifest.Files); + Assert.Contains(GeneralUpdate.Core.Configuration.ManifestInfo.FileName, manifest.Files); + Assert.Equal(archive.Entries.Count, manifest.Files.Count); + } + TryDelete(bundle.ZipPath); + } + + [Fact] + public async Task CollectAsync_JsonBlacklistedByPrivacyFilter_ProtocolMetadataStillShipped() + { + // Regression: the bootstrap passes the UPDATE blacklist (default formats include + // .json) as the diagnostics privacy filter — it stripped manifest.json and the + // rollback JSON evidence from every bundle. Protocol metadata is GeneralUpdate's + // own payload and must survive; other blacklisted artifacts stay excluded. + Directory.CreateDirectory(_installPath); + Directory.CreateDirectory(Path.Combine(_installPath, "Logs")); + File.WriteAllText(Path.Combine(_installPath, GeneralUpdate.Core.Configuration.ManifestInfo.FileName), "{}"); + File.WriteAllText(Path.Combine(_installPath, "Logs", "generalupdate-trace.log"), "log line"); + + // ".txt" blacklists the log tail artifact; ".json" blacklists every protocol payload. + var filter = new GeneralUpdate.Core.FileSystem.BlackMatcher(new GeneralUpdate.Core.Configuration.BlackPolicy( + null, new[] { ".txt", ".json" }, null)); + var collector = new DiagnosticsCollector(CreateOptions(), filter); + + var bundle = await collector.CollectAsync(new DiagnosticsCollectRequest( + _installPath, + DiagnosticsKinds.Rollback, + "1.0.2", + "reason", + RollbackResultJson: "{}"), CancellationToken.None); + + Assert.NotNull(bundle); + using (var archive = ZipFile.OpenRead(bundle!.ZipPath)) + { + // Mandatory protocol metadata survives the privacy filter. + Assert.Contains(archive.Entries, e => e.FullName == "manifest.json"); + Assert.Contains(archive.Entries, e => e.FullName == "rollback-result.json"); + Assert.Contains(archive.Entries, e => e.FullName == GeneralUpdate.Core.Configuration.ManifestInfo.FileName); + // Collected artifacts still honor the privacy exclusions (log tail is .txt). + Assert.DoesNotContain(archive.Entries, e => e.FullName == "update-log-tail.txt"); + } + TryDelete(bundle.ZipPath); + } + + private static void TryDelete(string path) + { + try { if (File.Exists(path)) File.Delete(path); } catch { /* best effort */ } + } +} diff --git a/tests/CoreTest/Diagnostics/DiagnosticsUploaderContractTests.cs b/tests/CoreTest/Diagnostics/DiagnosticsUploaderContractTests.cs new file mode 100644 index 00000000..c6afb284 --- /dev/null +++ b/tests/CoreTest/Diagnostics/DiagnosticsUploaderContractTests.cs @@ -0,0 +1,262 @@ +using System.Net; +using System.Text; +using GeneralUpdate.Core.Diagnostics; +using GeneralUpdate.Core.Network; + +namespace CoreTest.Diagnostics; + +/// +/// Wire-contract tests of the diagnostics upload against the GeneralSpace +/// POST /Fault/UploadArtifact endpoint: multipart form-data layout, the guid +/// idempotency key, kind vocabulary and business-level acknowledgment. +/// +[Collection("NonParallel_EventManager")] +public sealed class DiagnosticsUploaderContractTests : IDisposable +{ + private readonly string _tempRoot = Path.Combine(Path.GetTempPath(), $"gu-diag-up-{Guid.NewGuid():N}"); + + public void Dispose() + { + try { Directory.Delete(_tempRoot, true); } catch { /* best effort */ } + } + + private string CreateBundleZip() + { + Directory.CreateDirectory(_tempRoot); + var zipPath = Path.Combine(_tempRoot, $"{Guid.NewGuid():N}.zip"); + using var archive = System.IO.Compression.ZipFile.Open(zipPath, System.IO.Compression.ZipArchiveMode.Create); + var entry = archive.CreateEntry("sysinfo.txt"); + using var writer = new StreamWriter(entry.Open()); + writer.Write("os=unit-test"); + return zipPath; + } + + private static CapturingHandler CreateHandler(HttpStatusCode status) + { + var handler = new CapturingHandler { ResponseStatus = status }; + return handler; + } + + private static DiagnosticsManifest CreateManifest() => new() + { + Guid = "b3c1d4e5f6a7b8c9d0e1f2a3b4c5d6e7", + Kind = DiagnosticsKinds.SelfCheck, + Version = "1.0.2", + AppKey = "ak-123", + ProductId = "p-001", + Platform = 1, + TargetName = "MyApp", + RecordId = 42, + RecordType = 1, + Reason = "self-check failed: process exited with code -1", + Files = ["sysinfo.txt"], + }; + + [Fact] + public async Task UploadAsync_SendsMultipartContractFields() + { + var handler = CreateHandler(HttpStatusCode.OK); + var uploader = new DiagnosticsUploader(new DiagnosticsOptions + { + Enabled = true, + Url = "https://server.example.test/Fault/UploadArtifact", + }, new HttpClient(handler)); + var zip = CreateBundleZip(); + + var uploaded = await uploader.UploadAsync(new DiagnosticsBundle(zip, CreateManifest()), CancellationToken.None); + + Assert.True(uploaded); + var fields = handler.Requests.Single().FormField; + Assert.Equal("b3c1d4e5f6a7b8c9d0e1f2a3b4c5d6e7", fields["guid"]); + Assert.Equal("selfcheck", fields["kind"]); + Assert.Equal("2", fields["schema"]); + Assert.Equal("1.0.2", fields["version"]); + Assert.Equal("ak-123", fields["appKey"]); + Assert.Equal("p-001", fields["productId"]); + Assert.Equal("1", fields["platform"]); + Assert.Equal("MyApp", fields["targetName"]); + Assert.Equal("42", fields["recordId"]); + Assert.Equal("1", fields["recordType"]); + Assert.Contains("self-check failed", fields["reason"]); + Assert.Equal("[\"sysinfo.txt\"]", fields["files"]); + + var filePart = handler.Requests.Single().FilePart; + Assert.Equal("file", filePart.Name); + Assert.Equal("b3c1d4e5f6a7b8c9d0e1f2a3b4c5d6e7.zip", filePart.FileName); + } + + [Fact] + public async Task UploadAsync_OptionalUnknownFields_AreOmitted() + { + var handler = CreateHandler(HttpStatusCode.OK); + var uploader = new DiagnosticsUploader(new DiagnosticsOptions + { + Enabled = true, + Url = "https://server.example.test/Fault/UploadArtifact", + }, new HttpClient(handler)); + var zip = CreateBundleZip(); + var manifest = new DiagnosticsManifest + { + Guid = "a" + Guid.NewGuid().ToString("D")[1..], + Kind = DiagnosticsKinds.Crash, + }; + + var uploaded = await uploader.UploadAsync(new DiagnosticsBundle(zip, manifest), CancellationToken.None); + + Assert.True(uploaded); + var fields = handler.Requests.Single().FormField; + Assert.Equal("crash", fields["kind"]); + Assert.False(fields.ContainsKey("appKey")); + Assert.False(fields.ContainsKey("version")); + Assert.False(fields.ContainsKey("targetName")); + Assert.False(fields.ContainsKey("productId")); + Assert.False(fields.ContainsKey("platform")); + Assert.False(fields.ContainsKey("recordId")); + Assert.False(fields.ContainsKey("recordType")); + Assert.False(fields.ContainsKey("reason")); + } + + [Fact] + public async Task UploadAsync_Non2xx_ReturnsFalse() + { + var handler = CreateHandler(HttpStatusCode.InternalServerError); + var uploader = new DiagnosticsUploader(new DiagnosticsOptions + { + Enabled = true, + Url = "https://server.example.test/Fault/UploadArtifact", + }, new HttpClient(handler)); + var zip = CreateBundleZip(); + + var uploaded = await uploader.UploadAsync(new DiagnosticsBundle(zip, CreateManifest()), CancellationToken.None); + + Assert.False(uploaded); + } + + [Theory] + [InlineData("{\"code\":400,\"body\":{\"artifactId\":\"b3c1d4e5f6a7b8c9d0e1f2a3b4c5d6e7\"}}")] + [InlineData("{\"code\":500,\"body\":null}")] + [InlineData("{\"code\":200,\"body\":{\"artifactId\":\"wrong\"}}")] + [InlineData("{\"code\":200,\"body\":{}}")] + [InlineData("{}")] + [InlineData("not json")] + public async Task UploadAsync_InvalidBusinessResponse_ReturnsFalse(string body) + { + var handler = CreateHandler(HttpStatusCode.OK); + handler.ResponseBody = body; + var uploader = new DiagnosticsUploader(new DiagnosticsOptions + { + Enabled = true, Url = "https://server.example.test/Fault/UploadArtifact", + }, new HttpClient(handler)); + + Assert.False(await uploader.UploadAsync(new DiagnosticsBundle(CreateBundleZip(), CreateManifest()), CancellationToken.None)); + } + + [Fact] + public async Task UploadAsync_DuplicateResponseWithCaseInsensitiveKeys_IsAccepted() + { + var handler = CreateHandler(HttpStatusCode.OK); + handler.ResponseBody = "{\"Code\":200,\"Body\":{\"ArtifactId\":\"b3c1d4e5f6a7b8c9d0e1f2a3b4c5d6e7\",\"duplicate\":true}}"; + var uploader = new DiagnosticsUploader(new DiagnosticsOptions + { + Enabled = true, Url = "https://server.example.test/Fault/UploadArtifact", + }, new HttpClient(handler)); + + Assert.True(await uploader.UploadAsync(new DiagnosticsBundle(CreateBundleZip(), CreateManifest()), CancellationToken.None)); + } + + [Fact] + public async Task UploadAsync_AppliesConfiguredTenantHeader() + { + var handler = CreateHandler(HttpStatusCode.OK); + var uploader = new DiagnosticsUploader(new DiagnosticsOptions + { + Enabled = true, Url = "https://server.example.test/Fault/UploadArtifact", + }, new HttpClient(handler)); + HttpClientProvider.ExtraHeaders.TryGetValue("X-Tenant-Id", out var previous); + try + { + HttpClientProvider.ExtraHeaders["X-Tenant-Id"] = "tenant-test"; + Assert.True(await uploader.UploadAsync(new DiagnosticsBundle(CreateBundleZip(), CreateManifest()), CancellationToken.None)); + Assert.Equal("tenant-test", handler.Requests.Single().TenantId); + } + finally + { + if (previous == null) HttpClientProvider.ExtraHeaders.TryRemove("X-Tenant-Id", out _); + else HttpClientProvider.ExtraHeaders["X-Tenant-Id"] = previous; + } + } + + [Fact] + public async Task UploadAsync_NotConfigured_SkipsAndReturnsFalse() + { + var handler = CreateHandler(HttpStatusCode.OK); + var uploader = new DiagnosticsUploader(new DiagnosticsOptions + { + Enabled = true, + Url = string.Empty, // no endpoint + }, new HttpClient(handler)); + var zip = CreateBundleZip(); + + var uploaded = await uploader.UploadAsync(new DiagnosticsBundle(zip, CreateManifest()), CancellationToken.None); + + Assert.False(uploaded); + Assert.Empty(handler.Requests); + } + + [Fact] + public void KindVocabulary_MatchesServerContract() + { + // GeneralSpace /Fault/UploadArtifact contract values (§3.2 of the adaptation design). + Assert.Equal("crash", DiagnosticsKinds.Crash); + Assert.Equal("selfcheck", DiagnosticsKinds.SelfCheck); + Assert.Equal("update", DiagnosticsKinds.Update); + // Rollback evidence is a self-check failure diagnostic — same bucket on the wire. + Assert.Equal(DiagnosticsKinds.SelfCheck, DiagnosticsKinds.Rollback); + // The real-time manifest aligns with the Bowl outbox disk contract (schema 2). + Assert.Equal(2, DiagnosticsManifest.CurrentSchema); + } + + /// Captures the multipart body of every request as form fields + the file part. + private sealed class CapturingHandler : HttpMessageHandler + { + public HttpStatusCode ResponseStatus { get; set; } = HttpStatusCode.OK; + public string? ResponseBody { get; set; } + public List Requests { get; } = []; + + protected override async Task SendAsync( + HttpRequestMessage request, CancellationToken cancellationToken) + { + var captured = new CapturedRequest(); + if (request.Headers.TryGetValues("X-Tenant-Id", out var tenant)) + captured.TenantId = tenant.Single(); + if (request.Content is System.Net.Http.MultipartFormDataContent multipart) + { + foreach (var part in multipart) + { + var name = part.Headers.ContentDisposition?.Name?.Trim('"'); + var fileName = part.Headers.ContentDisposition?.FileName?.Trim('"'); + var text = await part.ReadAsStringAsync(cancellationToken); + if (!string.IsNullOrEmpty(fileName)) + captured.FilePart = (name ?? string.Empty, fileName); + else if (name != null) + captured.FormField[name] = text; + } + } + + Requests.Add(captured); + return new HttpResponseMessage(ResponseStatus) + { + Content = new StringContent(ResponseBody ?? + $"{{\"code\":200,\"body\":{{\"artifactId\":\"{captured.FormField.GetValueOrDefault("guid")}\"}}}}", + Encoding.UTF8, "application/json"), + }; + } + } + + private sealed class CapturedRequest + { + public Dictionary FormField { get; } = new(); + public (string Name, string FileName) FilePart { get; set; } + public string? TenantId { get; set; } + } +} diff --git a/tests/CoreTest/Diagnostics/PendingDiagnosticsScannerTests.cs b/tests/CoreTest/Diagnostics/PendingDiagnosticsScannerTests.cs index 89b9e662..a841b950 100644 --- a/tests/CoreTest/Diagnostics/PendingDiagnosticsScannerTests.cs +++ b/tests/CoreTest/Diagnostics/PendingDiagnosticsScannerTests.cs @@ -1,4 +1,6 @@ using System.Text.Json; +using System.Net; +using System.Text; using GeneralUpdate.Core.Diagnostics; using GeneralUpdate.Core.Download.Reporting; using GeneralUpdate.Core.SelfCheck; @@ -112,6 +114,107 @@ public async Task ScanAsync_MissingFailRoot_IsANoOp() Assert.True(true); } + [Fact] + public async Task ScanAsync_StateRootCase_RetriesWithoutGiveupAndDeletesOnlyOnSuccess() + { + var state = Path.Combine(_installPath, "state"); + var guid = Guid.NewGuid().ToString("D"); + var caseDir = Path.Combine(state, "crash-outbox", "1.0.2", guid); + Directory.CreateDirectory(caseDir); + File.WriteAllText(Path.Combine(caseDir, "crash.dmp"), "dump"); + File.WriteAllText(Path.Combine(caseDir, "manifest.json"), + $$"""{ "schema": 2, "guid": "{{guid}}", "kind": "crash", "version": "1.0.2", "state": "pending", "attempts": 5 }"""); + var options = new DiagnosticsOptions { Enabled = true, MaxRetry = 0 }; + + await new PendingDiagnosticsScanner(_installPath, options, new FakeUploader(false), stateRoot: state) + .ScanAsync(CancellationToken.None); + using (var manifest = JsonDocument.Parse(File.ReadAllText(Path.Combine(caseDir, "manifest.json")))) + { + Assert.Equal(6, manifest.RootElement.GetProperty("attempts").GetInt32()); + Assert.Equal("pending", manifest.RootElement.GetProperty("state").GetString()); + } + + await new PendingDiagnosticsScanner(_installPath, options, new FakeUploader(true), stateRoot: state) + .ScanAsync(CancellationToken.None); + Assert.False(Directory.Exists(caseDir)); + } + + [Fact] + public async Task ScanAsync_StateRootCaseWithoutDump_RetainsEvidence() + { + var state = Path.Combine(_installPath, "state"); + var guid = Guid.NewGuid().ToString("D"); + var caseDir = Path.Combine(state, "crash-outbox", "1.0.2", guid); + Directory.CreateDirectory(caseDir); + File.WriteAllText(Path.Combine(caseDir, "manifest.json"), + $$"""{ "schema": 2, "guid": "{{guid}}", "kind": "crash", "state": "pending" }"""); + var uploader = new FakeUploader(true); + + await new PendingDiagnosticsScanner(_installPath, new DiagnosticsOptions { MaxRetry = 0 }, + uploader, stateRoot: state).ScanAsync(CancellationToken.None); + + Assert.Empty(uploader.Bundles); + Assert.True(Directory.Exists(caseDir)); + } + + [Fact] + public async Task ScanAsync_UnpublishedOrMismatchedCase_IsNeverUploaded() + { + var caseDir = CreateOutboxCase("1.0.2"); + var manifestPath = Path.Combine(caseDir, "manifest.json"); + File.WriteAllText(manifestPath, + $$"""{ "schema": 2, "guid": "{{Guid.NewGuid():D}}", "kind": "crash", "state": "pending" }"""); + var uploader = new FakeUploader(true); + + await CreateScanner(uploader).ScanAsync(CancellationToken.None); + + Assert.Empty(uploader.Bundles); + Assert.True(Directory.Exists(caseDir)); + } + + [Fact] + public async Task ScanAsync_ActualUploader_OnlyDeletesAfterBusinessAcknowledgment() + { + var state = Path.Combine(_installPath, "state"); + var guid = Guid.NewGuid().ToString("D"); + var caseDir = Path.Combine(state, "crash-outbox", "1.0.2", guid); + Directory.CreateDirectory(caseDir); + File.WriteAllText(Path.Combine(caseDir, "crash.dmp"), "dump"); + File.WriteAllText(Path.Combine(caseDir, "manifest.json"), + $$"""{ "schema": 2, "guid": "{{guid}}", "kind": "crash", "version": "1.0.2", "state": "pending" }"""); + var handler = new BusinessResponseHandler(); + using var client = new HttpClient(handler); + var options = new DiagnosticsOptions { Enabled = true, Url = "https://example.test/Fault/UploadArtifact", MaxRetry = 0 }; + var scanner = new PendingDiagnosticsScanner(_installPath, options, new DiagnosticsUploader(options, client), + stateRoot: state); + + handler.Response = $$"""{ "code": 400, "body": { "artifactId": "{{guid}}" } }"""; + await scanner.ScanAsync(CancellationToken.None); + Assert.True(Directory.Exists(caseDir)); + using (var manifest = JsonDocument.Parse(File.ReadAllText(Path.Combine(caseDir, "manifest.json")))) + Assert.Equal(1, manifest.RootElement.GetProperty("attempts").GetInt32()); + + handler.Response = $$"""{ "code": 200, "body": { "artifactId": "{{guid}}", "duplicate": true } }"""; + await scanner.ScanAsync(CancellationToken.None); + Assert.False(Directory.Exists(caseDir)); + Assert.Equal(2, handler.RequestCount); + } + + private sealed class BusinessResponseHandler : HttpMessageHandler + { + public string Response { get; set; } = string.Empty; + public int RequestCount { get; private set; } + + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + RequestCount++; + return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new StringContent(Response, Encoding.UTF8, "application/json") + }); + } + } + private sealed class FakeUploader(bool succeeds) : IDiagnosticsUploader { public List Bundles { get; } = new(); diff --git a/tests/CoreTest/Diagnostics/UpdateFailureOutboxTests.cs b/tests/CoreTest/Diagnostics/UpdateFailureOutboxTests.cs new file mode 100644 index 00000000..cedd8bf2 --- /dev/null +++ b/tests/CoreTest/Diagnostics/UpdateFailureOutboxTests.cs @@ -0,0 +1,145 @@ +using System.Net; +using System.Text; +using System.Text.Json; +using GeneralUpdate.Core.Configuration; +using GeneralUpdate.Core.Diagnostics; +using GeneralUpdate.Core.Download.Reporting; + +namespace CoreTest.Diagnostics; + +public sealed class UpdateFailureOutboxTests +{ + [Fact] + public void PackageWithoutRecordUsesActiveIdentity() + { + var root = Path.Combine(Path.GetTempPath(), "gu-update-outbox-" + Guid.NewGuid().ToString("N")); + try + { + var config = new UpdateContext + { + InstallPath = Path.Combine(root, "install"), DiagnosticsDirectory = Path.Combine(root, "state"), + UpdateVersions = [new VersionEntry { RecordId = 99 }] + }; + using var attempt = UpdateAttempt.Begin(config, "client"); + attempt.SetReportIdentity(42, 2); + attempt.SetPackage(new VersionEntry { Name = "package.zip" }); + attempt.RecordFailure(new InvalidOperationException("test failure")); + var id = InstallationIdentity.GetOrCreate(config); + var caseDir = Assert.Single(Directory.GetDirectories(Path.Combine(config.DiagnosticsDirectory, "update-outbox", id))); + using var manifest = JsonDocument.Parse(File.ReadAllText(Path.Combine(caseDir, "manifest.json"))); + Assert.Equal(42, manifest.RootElement.GetProperty("recordId").GetInt32()); + Assert.Equal(2, manifest.RootElement.GetProperty("recordType").GetInt32()); + } + finally { if (Directory.Exists(root)) Directory.Delete(root, true); } + } + + [GeneralSpaceFact] + public async Task FailureOutboxUploadsToRealGeneralSpace() + { + var root = Path.Combine(Path.GetTempPath(), "gu-real-update-outbox-" + Guid.NewGuid().ToString("N")); + try + { + using var e2e = JsonDocument.Parse(File.ReadAllText(Environment.GetEnvironmentVariable("GENERALUPDATE_E2E_CONFIG")!)); + var appKey = e2e.RootElement.GetProperty("appKey").GetString()!; + var recordId = e2e.RootElement.GetProperty("recordId").GetInt32(); + var config = new UpdateContext + { + InstallPath = Path.Combine(root, "install"), DiagnosticsDirectory = Path.Combine(root, "state"), + AppSecretKey = appKey, UpdateVersions = [new VersionEntry { RecordId = recordId }] + }; + using var attempt = UpdateAttempt.Begin(config, "update"); + attempt.Record("filesApplying"); + attempt.RecordFailure(new InvalidOperationException("test failure")); + var id = InstallationIdentity.GetOrCreate(config); + var caseDir = Assert.Single(Directory.GetDirectories(Path.Combine(config.DiagnosticsDirectory, "update-outbox", id))); + var url = new Uri(new Uri(e2e.RootElement.GetProperty("apiBaseUrl").GetString()!), + e2e.RootElement.GetProperty("artifactEndpoint").GetString()!).ToString(); + var options = new DiagnosticsOptions { Enabled = true, Url = url, AppKey = appKey, MaxRetry = 0 }; + var scanner = new PendingDiagnosticsScanner(config.InstallPath, options, + new DiagnosticsUploader(options), stateRoot: config.DiagnosticsDirectory, installationId: id); + await scanner.ScanAsync(CancellationToken.None); + Assert.False(Directory.Exists(caseDir), "Real GeneralSpace did not acknowledge the diagnostic artifact."); + } + finally { if (Directory.Exists(root)) Directory.Delete(root, true); } + } + + [Fact] + public async Task FailureIsScopedRedactedRetriedAndDeletedAfterAcknowledgment() + { + var root = Path.Combine(Path.GetTempPath(), "gu-update-outbox-" + Guid.NewGuid().ToString("N")); + try + { + var config = new UpdateContext + { + InstallPath = Path.Combine(root, "install"), DiagnosticsDirectory = Path.Combine(root, "state"), + AppSecretKey = "sensitive-app-key", Token = "sensitive-token", + UpdateVersions = [new VersionEntry { RecordId = 42 }] + }; + using var attempt = UpdateAttempt.Begin(config, "update"); + attempt.Record("filesApplying"); + attempt.RecordFailure(new InvalidOperationException("sensitive-app-key sensitive-token")); + var id = InstallationIdentity.GetOrCreate(config); + var caseDir = Assert.Single(Directory.GetDirectories(Path.Combine(config.DiagnosticsDirectory, "update-outbox", id))); + foreach (var file in Directory.GetFiles(caseDir)) + { + var content = File.ReadAllText(file); + Assert.DoesNotContain(config.AppSecretKey, content); + Assert.DoesNotContain(config.Token, content); + } + + var handler = new ArtifactHandler(); + var options = new DiagnosticsOptions { Enabled = true, Url = "https://example.test/Fault/UploadArtifact", + AppKey = config.AppSecretKey, MaxRetry = 1 }; + var scanner = new PendingDiagnosticsScanner(config.InstallPath, options, + new DiagnosticsUploader(options, new HttpClient(handler)), stateRoot: config.DiagnosticsDirectory, + installationId: id); + await new PendingDiagnosticsScanner(config.InstallPath, options, + new DiagnosticsUploader(options, new HttpClient(handler)), stateRoot: config.DiagnosticsDirectory, + installationId: Guid.NewGuid().ToString("D")).ScanAsync(CancellationToken.None); + Assert.Equal(0, handler.Requests); + File.WriteAllText(Path.Combine(caseDir, "extra.txt"), "not authorized"); + await scanner.ScanAsync(CancellationToken.None); + Assert.Equal(0, handler.Requests); + File.Delete(Path.Combine(caseDir, "extra.txt")); + await scanner.ScanAsync(CancellationToken.None); + await scanner.ScanAsync(CancellationToken.None); + Assert.True(Directory.Exists(caseDir)); + using (var manifest = JsonDocument.Parse(File.ReadAllText(Path.Combine(caseDir, "manifest.json")))) + Assert.Equal("pending", manifest.RootElement.GetProperty("state").GetString()); + handler.Accept = true; + await scanner.ScanAsync(CancellationToken.None); + Assert.False(Directory.Exists(caseDir)); + Assert.Equal(3, handler.Requests); + Assert.Contains("sensitive-app-key", handler.LastBody); + Assert.Contains("42", handler.LastBody); + } + finally { if (Directory.Exists(root)) Directory.Delete(root, true); } + } + + private sealed class ArtifactHandler : HttpMessageHandler + { + public bool Accept { get; set; } + public int Requests { get; private set; } + public string LastBody { get; private set; } = ""; + + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken token) + { + Requests++; + LastBody = await request.Content!.ReadAsStringAsync(token); + var multipart = (MultipartFormDataContent)request.Content; + var guid = await multipart.Single(part => part.Headers.ContentDisposition?.Name?.Trim('"') == "guid") + .ReadAsStringAsync(token); + var response = $"{{\"code\":{(Accept ? 200 : 400)},\"body\":{{\"artifactId\":\"{guid}\"}}}}"; + return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(response, Encoding.UTF8, "application/json") }; + } + } + + public sealed class GeneralSpaceFactAttribute : FactAttribute + { + public GeneralSpaceFactAttribute() + { + if (!File.Exists(Environment.GetEnvironmentVariable("GENERALUPDATE_E2E_CONFIG"))) + Skip = "Set GENERALUPDATE_E2E_CONFIG to a protected real GeneralSpace test configuration file."; + } + } +} diff --git a/tests/CoreTest/Download/DownloadPlanBuilderTests.cs b/tests/CoreTest/Download/DownloadPlanBuilderTests.cs index 70235b08..b4b16c39 100644 --- a/tests/CoreTest/Download/DownloadPlanBuilderTests.cs +++ b/tests/CoreTest/Download/DownloadPlanBuilderTests.cs @@ -52,6 +52,74 @@ public void Build_SingleAssetVersionAboveCurrent_HasAssets() Assert.Single(result.Assets); } + [Fact] + public void Build_FullOnlyPackage_ReturnsFullPlan() + { + var assets = new[] { Asset("full", "2.0.0", packageType: (int)PackageType.Full) }; + var result = DownloadPlanBuilder.Build(assets, "1.0.0"); + Assert.True(result.HasAssets); + var asset = Assert.Single(result.Assets); + Assert.Equal((int)PackageType.Full, asset.PackageType); + Assert.Equal("2.0.0", asset.Version); + } + + [Fact] + public void Build_FullOnlyPackage_AgreesWithHasUpdate() + { + // Regression: with only a Full package the plan used to come back empty + // while HasUpdate still reported an update, crashing the client strategy + // (SendProcessIpc with a null last version). + var assets = new[] { Asset("full", "2.0.0", packageType: (int)PackageType.Full) }; + var hasUpdate = DownloadPlanBuilder.HasUpdate(assets, AppType.Client, "1.0.0"); + var plan = DownloadPlanBuilder.Build(assets, "1.0.0"); + Assert.True(hasUpdate); + Assert.True(plan.HasAssets); + } + + [Fact] + public void Build_MultipleFullPackages_PicksLatest() + { + var assets = new[] + { + Asset("full-2", "2.0.0", packageType: (int)PackageType.Full), + Asset("full-3", "3.0.0", packageType: (int)PackageType.Full) + }; + var result = DownloadPlanBuilder.Build(assets, "1.0.0"); + var asset = Assert.Single(result.Assets); + Assert.Equal("3.0.0", asset.Version); + } + + [Fact] + public void Build_FullOnlyBothAppTypes_RetainsLatestPerTrack() + { + // Regression: a combined Client+Upgrade release publishes one full package per + // AppType track. Picking ONE global latest dropped the other track's required + // package while ClientStrategy still expected the Both scenario. + var assets = new[] + { + AssetWithType("client-full", "2.0.0", packageType: (int)PackageType.Full, appType: (int)AppType.Client), + AssetWithType("client-full-old", "1.5.0", packageType: (int)PackageType.Full, appType: (int)AppType.Client), + AssetWithType("upgrade-full", "2.5.0", packageType: (int)PackageType.Full, appType: (int)AppType.Upgrade) + }; + var result = DownloadPlanBuilder.Build(assets, "1.0.0", "1.0.0"); + + Assert.True(result.HasAssets); + Assert.Equal(2, result.Assets.Count); + Assert.Equal("2.0.0", result.Assets.Single(a => a.AppType == (int)AppType.Client).Version); + Assert.Equal("2.5.0", result.Assets.Single(a => a.AppType == (int)AppType.Upgrade).Version); + // Retained in version order. + Assert.Equal("2.0.0", result.Assets[0].Version); + Assert.Equal("2.5.0", result.Assets[1].Version); + } + + [Fact] + public void Build_FrozenFullPackageOnly_ReturnsEmpty() + { + var assets = new[] { Asset("full", "2.0.0", isFreeze: true, packageType: (int)PackageType.Full) }; + var result = DownloadPlanBuilder.Build(assets, "1.0.0"); + Assert.False(result.HasAssets); + } + [Fact] public void Build_AllVersionsBelowOrEqual_ReturnsEmpty() { diff --git a/tests/CoreTest/Download/HttpDownloadExecutorTests.cs b/tests/CoreTest/Download/HttpDownloadExecutorTests.cs index 40d06a64..20a84dcc 100644 --- a/tests/CoreTest/Download/HttpDownloadExecutorTests.cs +++ b/tests/CoreTest/Download/HttpDownloadExecutorTests.cs @@ -1,3 +1,4 @@ +using System.Diagnostics; using System.Net; using GeneralUpdate.Core.Download.Executors; using GeneralUpdate.Core.Download.Models; @@ -158,4 +159,100 @@ protected override Task SendAsync( return Task.FromResult(response); } } + + // ── Inactivity (idle) timeout ── + + /// + /// Regression: the re-armed idle timer could not cancel BODY reads because the + /// download loop received the caller's token instead of the linked timeout token. + /// With ResponseHeadersRead, SendAsync has already completed and its cancellation + /// registration does not bound subsequent response-stream reads — a connection that + /// stalls after the headers occupied a download slot indefinitely. + /// + [Fact] + public async Task ExecuteAsync_StalledBodyAfterHeaders_IdleTimeoutCancelsRead() + { + var handler = new StallAfterHeadersHandler(); + var client = new HttpClient(handler); + var executor = new HttpDownloadExecutor(client, TimeSpan.FromMilliseconds(400), enableResume: false); + var asset = new DownloadAsset("test", "http://example.com/stall", 100, null, "1.0"); + var dest = Path.Combine(Path.GetTempPath(), $"stall-{Guid.NewGuid():N}.tmp"); + try + { + var sw = Stopwatch.StartNew(); + // The idle timeout surfaces as TaskCanceledException (retryable, same as a + // headers-phase timeout) — not as a hung download. + await Assert.ThrowsAnyAsync( + () => executor.ExecuteAsync(asset, dest)); + Assert.True(sw.Elapsed < TimeSpan.FromSeconds(10), + $"idle timeout did not interrupt the stalled body read (took {sw.Elapsed})"); + } + finally { if (File.Exists(dest)) File.Delete(dest); } + } + + [Fact] + public async Task StreamDownloadAsync_IdleTimerRearms_AfterEachSuccessfulRead() + { + // The idle timer is re-armed after every successful read, so slow-but-alive + // transfers keep making progress while a stall (> one idle window with no read) + // is interrupted. + using var idleCts = new CancellationTokenSource(TimeSpan.FromMilliseconds(300)); + var source = new ReadThenStallStream(readsBeforeStall: 3); + using var dest = new MemoryStream(); + var sw = Stopwatch.StartNew(); + + await Assert.ThrowsAnyAsync(() => + HttpDownloadExecutor.StreamDownloadAsync(source, dest, -1, 0, "f", null, sw, + idleCts.Token, null, idleCts, TimeSpan.FromMilliseconds(300))); + + Assert.True(sw.Elapsed < TimeSpan.FromSeconds(10), + $"re-armed idle timer did not interrupt the stall (took {sw.Elapsed})"); + Assert.Equal(3, dest.Length); // the three reads that made progress landed in the file + } + + /// Returns a response whose body stream delivers nothing after the headers. + private sealed class StallAfterHeadersHandler : HttpMessageHandler + { + protected override Task SendAsync( + HttpRequestMessage request, CancellationToken ct) + { + var response = new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new StreamContent(new ReadThenStallStream(readsBeforeStall: 0)) + }; + response.Content.Headers.ContentLength = 100; + return Task.FromResult(response); + } + } + + /// Yields a few bytes, then stalls honoring the cancellation token (30 s cap). + private sealed class ReadThenStallStream : Stream + { + private readonly int _readsBeforeStall; + private int _reads; + + public ReadThenStallStream(int readsBeforeStall) => _readsBeforeStall = readsBeforeStall; + + public override async Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + { + if (++_reads <= _readsBeforeStall) + { + buffer[offset] = (byte)'x'; + return 1; + } + await Task.Delay(TimeSpan.FromSeconds(30), cancellationToken).ConfigureAwait(false); + return 0; + } + + public override void Flush() { } + public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + public override void SetLength(long value) { } + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + public override bool CanRead => true; + public override bool CanSeek => false; + public override bool CanWrite => false; + public override long Length => 0; + public override long Position { get; set; } + } } diff --git a/tests/CoreTest/Download/HttpUpdateReporterWireTests.cs b/tests/CoreTest/Download/HttpUpdateReporterWireTests.cs new file mode 100644 index 00000000..98eb94bb --- /dev/null +++ b/tests/CoreTest/Download/HttpUpdateReporterWireTests.cs @@ -0,0 +1,129 @@ +using System.Net; +using System.Text; +using System.Text.Json.Nodes; +using GeneralUpdate.Core.Download.Reporting; + +namespace CoreTest.Download; + +/// +/// Wire projection of against the GeneralSpace ReportDTO: +/// the baseline trio stays byte-identical for plain reports; failure attribution +/// (phase/errorCode/message) only appears when populated. +/// +public sealed class HttpUpdateReporterWireTests +{ + private sealed class CaptureHandler : HttpMessageHandler + { + public HttpStatusCode Status { get; set; } = HttpStatusCode.OK; + public string? Body { get; private set; } + public string ResponseBody { get; set; } = ""; + + protected override async Task SendAsync( + HttpRequestMessage request, CancellationToken cancellationToken) + { + Body = await request.Content!.ReadAsStringAsync(cancellationToken); + return new HttpResponseMessage(Status) { Content = new StringContent(ResponseBody) }; + } + } + + [Fact] + public async Task PlainReport_KeepsLegacyThreeFieldPayload() + { + var handler = new CaptureHandler(); + var reporter = new HttpUpdateReporter(new HttpClient(handler), "https://reports.example.test/status"); + + await reporter.ReportAsync(new UpdateReport(7, (int)UpdateStatus.Failure, 1)); + + var payload = JsonNode.Parse(handler.Body!)!.AsObject(); + Assert.Equal(new[] { "recordId", "status", "type" }, payload.Select(p => p.Key)); + Assert.Equal(7, (int?)payload["recordId"]); + Assert.Equal(3, (int?)payload["status"]); + } + + [Fact] + public async Task FailureAttribution_RidesTheWireWhenPopulated() + { + var handler = new CaptureHandler(); + var reporter = new HttpUpdateReporter(new HttpClient(handler), "https://reports.example.test/status"); + + await reporter.ReportAsync(new UpdateReport(9, (int)UpdateStatus.Failure, 2) + { + Phase = UpdatePhases.Startup, + Error = new UpdateFailure + { + Category = "healthCheckFailure", + ExceptionType = "System.InvalidOperationException", + Message = "self-check failed: process exited with code -1", + } + }); + + var payload = JsonNode.Parse(handler.Body!)!.AsObject(); + Assert.Equal(new[] { "recordId", "status", "type", "phase", "errorCode", "message" }, payload.Select(p => p.Key)); + Assert.Equal("Startup", (string?)payload["phase"]); + Assert.Equal("System.InvalidOperationException", (string?)payload["errorCode"]); + Assert.Equal("self-check failed: process exited with code -1", (string?)payload["message"]); + } + + [Fact] + public async Task RollbackReport_CarriesRollbackPhase() + { + var handler = new CaptureHandler(); + var reporter = new HttpUpdateReporter(new HttpClient(handler), "https://reports.example.test/status"); + + // Shape used by RollbackManager: phase=Rollback with the redacted failure reason as message. + await reporter.ReportAsync(new UpdateReport(11, (int)UpdateStatus.Failure, 1) + { + Phase = UpdatePhases.Rollback, + Error = new UpdateFailure { Category = "healthCheckFailure", Message = "[REDACTED]" } + }); + + var payload = JsonNode.Parse(handler.Body!)!.AsObject(); + Assert.Equal("Rollback", (string?)payload["phase"]); + Assert.Equal("[REDACTED]", (string?)payload["message"]); + } + + [Fact] + public async Task EmptyReportUrl_IsNoOp() + { + var handler = new CaptureHandler(); + var reporter = new HttpUpdateReporter(new HttpClient(handler), string.Empty); + + await reporter.ReportAsync(new UpdateReport(1, (int)UpdateStatus.Failure, 1) + { + Phase = UpdatePhases.Rollback, + }); + + Assert.Null(handler.Body); + } + + [Theory] + [InlineData("")] + [InlineData("{\"code\":400,\"isSuccess\":false,\"body\":false}")] + [InlineData("{\"code\":200,\"body\":true}")] + [InlineData("{\"code\":200,\"isSuccess\":true,\"body\":false}")] + public async Task CredentialedReports_RejectUnconfirmedBusinessResponses(string response) + { + var handler = new CaptureHandler { ResponseBody = response }; + var reporter = new HttpUpdateReporter(new HttpClient(handler), "https://reports.example.test/status") + { + AppKey = "test-credential" + }; + await Assert.ThrowsAnyAsync(() => reporter.ReportAsync(new UpdateReport(7))); + Assert.Equal("test-credential", (string?)JsonNode.Parse(handler.Body!)!["appKey"]); + } + + [Fact] + public async Task CredentialedReport_AcceptsConfirmedResponseAndRejectsRemoteHttp() + { + var handler = new CaptureHandler { ResponseBody = "{\"code\":200,\"isSuccess\":true,\"body\":true}" }; + var reporter = new HttpUpdateReporter(new HttpClient(handler), "https://reports.example.test/status") + { + AppKey = "test-credential" + }; + await reporter.ReportAsync(new UpdateReport(7)); + reporter.ReportUrl = "http://reports.example.test/status"; + await Assert.ThrowsAsync(() => reporter.ReportAsync(new UpdateReport(7))); + reporter.ReportUrl = "http://127.0.0.1/status"; + await reporter.ReportAsync(new UpdateReport(7)); + } +} diff --git a/tests/CoreTest/Download/Sources/HttpDownloadSourceTests.cs b/tests/CoreTest/Download/Sources/HttpDownloadSourceTests.cs index 574ca124..b78282d3 100644 --- a/tests/CoreTest/Download/Sources/HttpDownloadSourceTests.cs +++ b/tests/CoreTest/Download/Sources/HttpDownloadSourceTests.cs @@ -1,4 +1,5 @@ using System.Reflection; +using CoreTest.TestSupport; using GeneralUpdate.Core.Configuration; using GeneralUpdate.Core.Download.Abstractions; using GeneralUpdate.Core.Download.Models; @@ -15,7 +16,7 @@ public class HttpDownloadSourceTests { private const string ValidUrl = "http://localhost:5000/api/versions"; private const string ClientVersion = "1.0.0"; - private const string AppSecretKey = "test-secret-key"; + private static readonly string AppSecretKey = FixtureValues.Secret("download"); #region Constructor — valid inputs diff --git a/tests/CoreTest/Download/Sources/VerificationDeviceIdTests.cs b/tests/CoreTest/Download/Sources/VerificationDeviceIdTests.cs new file mode 100644 index 00000000..7966c6a7 --- /dev/null +++ b/tests/CoreTest/Download/Sources/VerificationDeviceIdTests.cs @@ -0,0 +1,61 @@ +using System.Net; +using System.Net.Sockets; +using System.Text; +using System.Text.Json.Nodes; +using GeneralUpdate.Core.Configuration; +using GeneralUpdate.Core.Download.Sources; +using GeneralUpdate.Core.Security; + +namespace CoreTest.Download.Sources; + +public sealed class VerificationDeviceIdTests +{ + [Fact] + public async Task BothVerificationRequestsCarrySameDeviceId() + { + using var listener = new TcpListener(IPAddress.Loopback, 0); + listener.Start(); + var port = ((IPEndPoint)listener.LocalEndpoint).Port; + var id = Guid.NewGuid().ToString("D"); + var receiver = ReceiveRequests(listener); + var source = new HttpDownloadSource($"http://127.0.0.1:{port}/verification", "1.0.0", + "1.0.0", "test-key", PlatformType.Windows, "test", null, null, AuthScheme.Hmac, null, null) + { + DeviceId = id + }; + await source.ListAsync().WaitAsync(TimeSpan.FromSeconds(20)); + var requests = await receiver.WaitAsync(TimeSpan.FromSeconds(20)); + Assert.Equal(2, requests.Count); + Assert.All(requests, request => Assert.Equal(id, (string?)request["deviceId"])); + Assert.NotEqual((int?)requests[0]["appType"], (int?)requests[1]["appType"]); + } + + private static async Task> ReceiveRequests(TcpListener listener) + { + var requests = new List(); + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(20)); + for (var i = 0; i < 2; i++) + { + using var connection = await listener.AcceptTcpClientAsync(timeout.Token); + using var stream = connection.GetStream(); + using var reader = new StreamReader(stream, Encoding.UTF8, leaveOpen: true); + var length = 0; + while (await reader.ReadLineAsync(timeout.Token) is { Length: > 0 } header) + if (header.StartsWith("Content-Length:", StringComparison.OrdinalIgnoreCase)) + length = int.Parse(header["Content-Length:".Length..].Trim()); + var buffer = new char[length]; + var offset = 0; + while (offset < length) + { + var read = await reader.ReadAsync(buffer.AsMemory(offset), timeout.Token); + if (read == 0) throw new EndOfStreamException(); + offset += read; + } + requests.Add(JsonNode.Parse(new string(buffer))!); + var body = "{\"code\":200,\"body\":[]}"; + var response = Encoding.UTF8.GetBytes($"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {Encoding.UTF8.GetByteCount(body)}\r\nConnection: close\r\n\r\n{body}"); + await stream.WriteAsync(response, timeout.Token); + } + return requests; + } +} diff --git a/tests/CoreTest/Download/UpdateAttemptRedactionTests.cs b/tests/CoreTest/Download/UpdateAttemptRedactionTests.cs new file mode 100644 index 00000000..d2829d86 --- /dev/null +++ b/tests/CoreTest/Download/UpdateAttemptRedactionTests.cs @@ -0,0 +1,49 @@ +using CoreTest.TestSupport; +using GeneralUpdate.Core.Configuration; +using GeneralUpdate.Core.Download.Reporting; + +namespace CoreTest.Download; + +/// +/// Shared credential redaction used by server-facing evidence built outside the update +/// journal: the self-check verdict reason crosses the wire twice — verbatim in the +/// Startup report's Error.Message and (via RollbackRequest.Reason) in the Rollback +/// report and the rollback diagnostics bundle. A custom rule exception or a +/// verify-fail acknowledgement can embed a configured token, app secret or basic +/// password, so the redaction must be applied BEFORE the reason leaves the strategy. +/// +public sealed class UpdateAttemptRedactionTests +{ + [Fact] + public void Redact_StripsConfiguredCredentials() + { + var token = FixtureValues.Token("redact"); + var secret = FixtureValues.Secret("redact"); + var password = FixtureValues.Secret("redact-pw"); + var config = new UpdateContext + { + Token = token, + AppSecretKey = secret, + BasicPassword = password + }; + + var redacted = UpdateAttempt.Redact( + $"verify failed: {token} / {secret} / {password} / safe-part", config); + + Assert.Equal("verify failed: [REDACTED] / [REDACTED] / [REDACTED] / safe-part", redacted); + } + + [Fact] + public void Redact_NoConfiguredSecrets_ValueUnchanged() + { + var redacted = UpdateAttempt.Redact("plain failure reason", new UpdateContext()); + + Assert.Equal("plain failure reason", redacted); + } + + [Fact] + public void Redact_NullValue_ReturnsNull() + { + Assert.Null(UpdateAttempt.Redact(null, new UpdateContext { Token = FixtureValues.Token("redact-null") })); + } +} diff --git a/tests/CoreTest/Ipc/IpcEncryptionTests.cs b/tests/CoreTest/Ipc/IpcEncryptionTests.cs index bdec2e61..3e2dc24b 100644 --- a/tests/CoreTest/Ipc/IpcEncryptionTests.cs +++ b/tests/CoreTest/Ipc/IpcEncryptionTests.cs @@ -39,6 +39,83 @@ public void DecryptFromFile_FileDoesNotExist_ReturnsNull() Assert.Null(result); } + [Fact] + public void DecryptFromFile_CorruptedCiphertext_ReturnsNull_DoesNotThrow() + { + // Regression: a truncated or otherwise corrupted IPC file (crash mid-write of the + // old non-atomic writer, or a leftover file from another product) used to escape + // as CryptographicException from TransformFinalBlock; callers then misread the + // throw as "no IPC data" only by accident. It must degrade to null instead. + var tempFile = Path.Combine(Path.GetTempPath(), $"corrupt_{Guid.NewGuid():N}.enc"); + try + { + // Valid magic-free garbage: wrong length for an AES-CBC block, wrong key — + // either way TransformFinalBlock must fail. + File.WriteAllBytes(tempFile, new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }); + var result = IpcEncryption.DecryptFromFile(tempFile, TestKey, TestIV); + Assert.Null(result); + + // Also: a full-length ciphertext encrypted with a DIFFERENT key must return + // null (padding check fails) rather than throw. + var otherKey = System.Security.Cryptography.SHA256.HashData("SomeOtherKey_9876543210"u8.ToArray()); + IpcEncryption.EncryptToFile("payload"u8.ToArray(), tempFile, otherKey, TestIV); + Assert.Null(IpcEncryption.DecryptFromFile(tempFile, TestKey, TestIV)); + } + finally + { + if (File.Exists(tempFile)) File.Delete(tempFile); + } + } + + [Fact] + public void EncryptToFile_AtomicWrite_LeavesNoTempResidue() + { + // Regression: the writer used to create the target file in place; a crash + // mid-write left a half-written ciphertext for the reader to choke on. The + // writer now publishes via a sibling temp file + move, so after the call the + // target is complete and no ".tmp-*" sibling remains. + var tempFile = Path.Combine(Path.GetTempPath(), $"atomic_{Guid.NewGuid():N}.enc"); + try + { + IpcEncryption.EncryptToFile("stable payload"u8.ToArray(), tempFile, TestKey, TestIV); + + Assert.True(File.Exists(tempFile)); + var siblings = Directory.GetFiles(Path.GetDirectoryName(tempFile)!, + Path.GetFileName(tempFile) + ".tmp-*"); + Assert.Empty(siblings); + + // And the published file round-trips cleanly. + var decrypted = IpcEncryption.DecryptFromFile(tempFile, TestKey, TestIV); + Assert.NotNull(decrypted); + Assert.Equal("stable payload"u8.ToArray(), decrypted); + } + finally + { + if (File.Exists(tempFile)) File.Delete(tempFile); + } + } + + [Fact] + public void EncryptToFile_OverwritesExistingFile() + { + // The IPC file name is shared across launches; a second contract write must + // replace the first one rather than fail. + var tempFile = Path.Combine(Path.GetTempPath(), $"overwrite_{Guid.NewGuid():N}.enc"); + try + { + IpcEncryption.EncryptToFile("first"u8.ToArray(), tempFile, TestKey, TestIV); + IpcEncryption.EncryptToFile("second"u8.ToArray(), tempFile, TestKey, TestIV); + + var decrypted = IpcEncryption.DecryptFromFile(tempFile, TestKey, TestIV); + Assert.NotNull(decrypted); + Assert.Equal("second"u8.ToArray(), decrypted); + } + finally + { + if (File.Exists(tempFile)) File.Delete(tempFile); + } + } + [Fact] public void DecryptFromFile_FileDeletedAfterDecryption() { diff --git a/tests/CoreTest/Network/VersionServiceRetryTests.cs b/tests/CoreTest/Network/VersionServiceRetryTests.cs index 7023cf17..007888d0 100644 --- a/tests/CoreTest/Network/VersionServiceRetryTests.cs +++ b/tests/CoreTest/Network/VersionServiceRetryTests.cs @@ -1,53 +1,95 @@ +using System; +using System.Linq; +using System.Reflection; using GeneralUpdate.Core.Network; +using Xunit; namespace CoreTest.Network; +/// +/// Tests the REAL VersionService.ShouldRetry classifier (reached via reflection +/// because it is a private static helper) instead of a re-implemented copy, so the +/// production decision table cannot drift away from the tested behavior. +/// public class VersionServiceRetryTests { + private static readonly Func ShouldRetry = CreateClassifier(); + + private static Func CreateClassifier() + { + var type = typeof(VersionService).GetNestedType("VersionService", BindingFlags.NonPublic | BindingFlags.Public) + ?? AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => { try { return a.GetTypes(); } catch { return Type.EmptyTypes; } }) + .FirstOrDefault(t => t.Name == "VersionService" && t.GetMethods().Any(m => m.Name == "Validate")) + ?? throw new InvalidOperationException("VersionService type not found."); + + var method = type.GetMethods(BindingFlags.NonPublic | BindingFlags.Static) + .Single(m => m.Name is "ShouldRetry" or "IsRetryable"); + return ex => (bool)method.Invoke(null, new object?[] { ex })!; + } + [Fact] public void IsRetryable_OperationCanceledException_ReturnsFalse() { - Assert.False(IsRetryable(new OperationCanceledException("cancel"))); + // Caller-initiated cancellation must never be retried. + Assert.False(ShouldRetry(new OperationCanceledException("cancel"))); + } + + [Fact] + public void IsRetryable_TaskCanceledException_WithoutInner_ReturnsFalse() + { + // A plain TaskCanceledException (no inner timeout) is treated as caller + // cancellation — TaskCanceledException derives from OperationCanceledException. + Assert.False(ShouldRetry(new TaskCanceledException("timeout"))); } [Fact] - public void IsRetryable_TaskCanceledException_ReturnsFalse() + public void IsRetryable_TaskCanceledException_WrappingTimeout_ReturnsTrue() { - // TaskCanceledException inherits from OperationCanceledException, - // which is checked first → not retryable - Assert.False(IsRetryable(new TaskCanceledException("timeout"))); + // Regression: HttpClient timeouts surface as TaskCanceledException whose inner + // exception is TimeoutException. The classifier used to hit the + // OperationCanceledException branch first and never retried version validation + // timeouts; it must classify the wrapped timeout as retryable. + var timedOut = new TaskCanceledException("The request was canceled due to the configured HttpClient.Timeout", + new TimeoutException("The operation was canceled.")); + Assert.True(ShouldRetry(timedOut)); } [Fact] public void IsRetryable_TimeoutException_ReturnsTrue() { - Assert.True(IsRetryable(new TimeoutException("timeout"))); + Assert.True(ShouldRetry(new TimeoutException("timeout"))); } [Fact] public void IsRetryable_IOException_ReturnsTrue() { - Assert.True(IsRetryable(new IOException("network down"))); + Assert.True(ShouldRetry(new IOException("network down"))); + } + + [Fact] + public void IsRetryable_HttpRequestExceptionWithTimeout_ReturnsTrue() + { + Assert.True(ShouldRetry(new HttpRequestException("The request failed due to a timeout"))); } [Fact] public void IsRetryable_HttpRequestExceptionWithoutTimeout_ReturnsFalse() { - Assert.False(IsRetryable(new HttpRequestException("Forbidden 403"))); - Assert.False(IsRetryable(new HttpRequestException("Not Found 404"))); - Assert.False(IsRetryable(new HttpRequestException("Connection refused"))); + Assert.False(ShouldRetry(new HttpRequestException("Forbidden 403"))); + Assert.False(ShouldRetry(new HttpRequestException("Not Found 404"))); + Assert.False(ShouldRetry(new HttpRequestException("Connection refused"))); } [Fact] public void IsRetryable_InvalidOperationException_ReturnsFalse() { - Assert.False(IsRetryable(new InvalidOperationException("boom"))); + Assert.False(ShouldRetry(new InvalidOperationException("boom"))); } [Fact] public void IsRetryable_NullReferenceException_ReturnsFalse() { - Assert.False(IsRetryable(new NullReferenceException())); + Assert.False(ShouldRetry(new NullReferenceException())); } [Fact] @@ -63,15 +105,4 @@ public void HttpClientProvider_Shared_IsNotNull() { Assert.NotNull(HttpClientProvider.Shared); } - - // Matches actual VersionService.IsRetryable logic - private static bool IsRetryable(Exception ex) - { - if (ex is OperationCanceledException) return false; - if (ex is TaskCanceledException or TimeoutException or IOException) return true; - if (ex is HttpRequestException h && - (h.Message ?? "").Contains("timeout", StringComparison.OrdinalIgnoreCase)) - return true; - return false; - } } diff --git a/tests/CoreTest/SelfCheck/ProcessContractSelfCheckTests.cs b/tests/CoreTest/SelfCheck/ProcessContractSelfCheckTests.cs index dd395973..809444af 100644 --- a/tests/CoreTest/SelfCheck/ProcessContractSelfCheckTests.cs +++ b/tests/CoreTest/SelfCheck/ProcessContractSelfCheckTests.cs @@ -1,4 +1,5 @@ using System.Text.Json; +using CoreTest.TestSupport; using GeneralUpdate.Core.Configuration; using GeneralUpdate.Core.JsonContext; @@ -20,7 +21,7 @@ public sealed class ProcessContractSelfCheckTests Encoding = System.Text.Encoding.UTF8, Format = Format.Zip, DownloadTimeOut = 30, - AppSecretKey = "secret", + AppSecretKey = FixtureValues.Secret("selfcheck"), BackupDirectory = AppContext.BaseDirectory, SelfCheckEnabled = true, SelfCheckStartupWindowSeconds = 60, diff --git a/tests/CoreTest/SelfCheck/ProcessLaunchRuleTests.cs b/tests/CoreTest/SelfCheck/ProcessLaunchRuleTests.cs index 7bf5ac01..d4d5eeb8 100644 --- a/tests/CoreTest/SelfCheck/ProcessLaunchRuleTests.cs +++ b/tests/CoreTest/SelfCheck/ProcessLaunchRuleTests.cs @@ -1,5 +1,4 @@ using System.Diagnostics; -using System.Runtime.InteropServices; using GeneralUpdate.Core.SelfCheck; namespace CoreTest.SelfCheck; @@ -25,21 +24,10 @@ public void Dispose() try { Directory.Delete(_installPath, true); } catch { /* best effort */ } } - private static (string FileName, string Arguments) ImmediateExit(int code) => - RuntimeInformation.IsOSPlatform(OSPlatform.Windows) - ? ("cmd.exe", $"/c exit {code}") - : ("/bin/sh", $"-c \"exit {code}\""); - - private static (string FileName, string Arguments) StayAlive() => - RuntimeInformation.IsOSPlatform(OSPlatform.Windows) - ? ("cmd.exe", "/c ping -n 60 127.0.0.1 > nul") - : ("/bin/sh", "-c \"sleep 60\""); - [Fact] public async Task ImmediateNonZeroExit_Fails() { - var (fileName, arguments) = ImmediateExit(3); - using var process = Process.Start(new ProcessStartInfo(fileName, arguments) { UseShellExecute = false })!; + using var process = StubProcesses.ImmediateFail()!; var rule = new ProcessLaunchRule(process, TimeSpan.FromSeconds(15), requireAck: false); var result = await rule.CheckAsync(NewContext(), CancellationToken.None); @@ -51,8 +39,7 @@ public async Task ImmediateNonZeroExit_Fails() [Fact] public async Task ImmediateZeroExit_PassesWithDetail() { - var (fileName, arguments) = ImmediateExit(0); - using var process = Process.Start(new ProcessStartInfo(fileName, arguments) { UseShellExecute = false })!; + using var process = StubProcesses.ImmediateOk()!; var rule = new ProcessLaunchRule(process, TimeSpan.FromSeconds(15), requireAck: false); var result = await rule.CheckAsync(NewContext(), CancellationToken.None); @@ -64,8 +51,7 @@ public async Task ImmediateZeroExit_PassesWithDetail() [Fact] public async Task AlivePastWindow_PassesLeniently() { - var (fileName, arguments) = StayAlive(); - using var process = Process.Start(new ProcessStartInfo(fileName, arguments) { UseShellExecute = false })!; + using var process = StubProcesses.StayAlive()!; var rule = new ProcessLaunchRule(process, TimeSpan.FromSeconds(1), requireAck: false); try @@ -95,8 +81,7 @@ public async Task MissingExecutable_FailsWithoutProcess() [Fact] public async Task RequireAck_VerifyFailFailsImmediately() { - var (fileName, arguments) = StayAlive(); - using var process = Process.Start(new ProcessStartInfo(fileName, arguments) { UseShellExecute = false })!; + using var process = StubProcesses.StayAlive()!; UpdateVerificationMarker.WriteAck(_installPath, healthy: false, "db down"); var rule = new ProcessLaunchRule(process, TimeSpan.FromSeconds(15), requireAck: true); @@ -119,8 +104,7 @@ public async Task RequireAck_VerifyFailFailsImmediately() [Fact] public async Task RequireAck_VerifyOkPassesBeforeWindowElapses() { - var (fileName, arguments) = StayAlive(); - using var process = Process.Start(new ProcessStartInfo(fileName, arguments) { UseShellExecute = false })!; + using var process = StubProcesses.StayAlive()!; var rule = new ProcessLaunchRule(process, TimeSpan.FromSeconds(30), requireAck: true); try diff --git a/tests/CoreTest/SelfCheck/StubProcesses.cs b/tests/CoreTest/SelfCheck/StubProcesses.cs new file mode 100644 index 00000000..b89af090 --- /dev/null +++ b/tests/CoreTest/SelfCheck/StubProcesses.cs @@ -0,0 +1,57 @@ +using System.Diagnostics; +using System.Runtime.InteropServices; + +namespace CoreTest.SelfCheck; + +/// Which stub behavior a self-check test wants from the verification launch. +internal enum StubVerdict +{ + /// Stays alive for the whole verification window (usable version). + Healthy, + + /// Exits immediately with a non-zero code (unusable version). + Unusable +} + +/// +/// Real child-process stubs for the self-check tests. Every launcher builds its +/// ProcessStartInfo from compile-time literal strings only — no test-controlled +/// string reaches the spawned process — so each stub command is fixed at compile time. +/// Processes are spawned via the Process instance Start() member rather than the +/// static Start overloads of Process. +/// +internal static class StubProcesses +{ + private static bool IsWindows => RuntimeInformation.IsOSPlatform(OSPlatform.Windows); + + /// Starts the stub matching the requested verdict (shared with the switch-matrix tests). + internal static Process? Launch(StubVerdict verdict) => verdict switch + { + StubVerdict.Unusable => ImmediateFail(), + _ => StayAlive() + }; + + /// Exits immediately with code 3 — simulates an app that dies on startup. + internal static Process? ImmediateFail() => IsWindows + ? Spawn("cmd.exe", "/c exit 3") + : Spawn("/bin/sh", "-c \"exit 3\""); + + /// Exits immediately with code 0 — clean success stub. + internal static Process? ImmediateOk() => IsWindows + ? Spawn("cmd.exe", "/c exit 0") + : Spawn("/bin/sh", "-c \"exit 0\""); + + /// Stays alive for roughly a minute — simulates a running application. + internal static Process? StayAlive() => IsWindows + ? Spawn("cmd.exe", "/c ping -n 60 127.0.0.1 > nul") + : Spawn("/bin/sh", "-c \"sleep 60\""); + + private static Process? Spawn(string fileName, string arguments) + { + var process = new Process + { + StartInfo = new ProcessStartInfo(fileName, arguments) { UseShellExecute = false } + }; + return process.Start() ? process : null; + } +} diff --git a/tests/CoreTest/SelfCheck/UpdateStrategySelfCheckTests.cs b/tests/CoreTest/SelfCheck/UpdateStrategySelfCheckTests.cs new file mode 100644 index 00000000..5c0664be --- /dev/null +++ b/tests/CoreTest/SelfCheck/UpdateStrategySelfCheckTests.cs @@ -0,0 +1,210 @@ +using System.Diagnostics; +using GeneralUpdate.Core.Configuration; +using GeneralUpdate.Core.Download.Abstractions; +using GeneralUpdate.Core.Download.Models; +using GeneralUpdate.Core.Download.Reporting; +using GeneralUpdate.Core.Pipeline; +using GeneralUpdate.Core.Strategy; + +namespace CoreTest.SelfCheck; + +/// +/// The self-check switch matrix from the design's test plan (docs/self-check-design.md §12): +/// SelfCheckEnabled on/off × pipeline success/failure × verdict pass/fail, asserting the +/// manifest, verify-marker, report and launch behaviour of the verified-launch flow. +/// The stub main-application processes reuse the simulation commands from +/// (immediate non-zero exit = unusable, survivor = usable). +/// +public sealed class UpdateStrategySelfCheckTests : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), $"gu-selfcheck-{Guid.NewGuid():N}"); + private readonly List _processes = []; + + public void Dispose() + { + foreach (var process in _processes) + { + try { if (!process.HasExited) process.Kill(); } catch { /* best effort */ } + process.Dispose(); + } + try { Environments.SetEnvironmentVariable("UpgradeFail", string.Empty); } catch { /* best effort */ } + try { Directory.Delete(_root, true); } catch { /* best effort */ } + } + + private string InstallPath => Path.Combine(_root, "install"); + private string BackupPath => Path.Combine(_root, "backup"); + private string ManifestPath => Path.Combine(InstallPath, ManifestInfo.FileName); + private string MarkerPath => Path.Combine(InstallPath, "generalupdate.verify.json"); + private const string MainAppName = "MyApp.exe"; + + /// Seed the install tree: presence-rule target (new payload) + rollback material (old payload). + private UpdateContext Config(bool selfCheck, bool failPipeline = false) + { + Directory.CreateDirectory(InstallPath); + Directory.CreateDirectory(Path.Combine(_root, "state")); + Directory.CreateDirectory(Path.Combine(_root, "staging")); + Directory.CreateDirectory(BackupPath); + File.WriteAllText(Path.Combine(InstallPath, MainAppName), "new-version-payload"); + File.WriteAllText(Path.Combine(BackupPath, MainAppName), "old-version-payload"); + new ManifestInfo { ClientVersion = "1.0.0" }.Save(ManifestPath); + + return new UpdateContext + { + InstallPath = InstallPath, + DiagnosticsDirectory = Path.Combine(_root, "state"), + TempPath = Path.Combine(_root, "staging"), + ClientVersion = "1.0.0", + LastVersion = "2.0.0", + MainAppName = MainAppName, + LaunchClientAfterUpdate = true, + BackupEnabled = true, + BackupDirectory = BackupPath, + Format = Format.Zip, + SelfCheckEnabled = selfCheck, + SelfCheckStartupWindowSeconds = 1, + UpdateVersions = [new VersionEntry { RecordId = 42, Version = "2.0.0", Name = "sample.zip" }], + }; + } + + private SelfCheckTestOs CreateOs(bool failPipeline = false) => new(_processes) { FailPipeline = failPipeline }; + + private static async Task RunAsync(UpdateContext config, SelfCheckTestOs os) + { + var reporter = new CaptureReporter(); + var strategy = new UpdateStrategy { Reporter = reporter }; + strategy.SetOsStrategy(os); + strategy.Create(config); + await strategy.ExecuteAsync(); + return reporter; + } + + [Fact] + public async Task SelfCheckOff_PipelineSuccess_LegacyLaunchPath() + { + var os = CreateOs(); + var config = Config(selfCheck: false); + + var reporter = await RunAsync(config, os); + + Assert.True(os.Launched); // plain StartAppAsync path + Assert.False(os.VerificationStarted); // no verified launch + Assert.False(File.Exists(MarkerPath)); // no verify marker + Assert.Equal("2.0.0", ManifestInfo.Load(ManifestPath)!.ClientVersion); + Assert.Contains(reporter.Reports, r => r.Status == (int)UpdateStatus.Success); + Assert.DoesNotContain(reporter.Reports, r => r.Status == (int)UpdateStatus.Failure); + } + + [Fact] + public async Task SelfCheckOn_VerificationPasses_MarkerClearedAndAppKept() + { + var os = CreateOs(); // stub survives the window → lenient pass + var config = Config(selfCheck: true); + + var reporter = await RunAsync(config, os); + + Assert.True(os.VerificationStarted); + Assert.False(os.Launched); // verified path does not use StartAppAsync + Assert.False(File.Exists(MarkerPath)); // verdict rendered → marker deleted + Assert.Equal("2.0.0", ManifestInfo.Load(ManifestPath)!.ClientVersion); + Assert.Contains(reporter.Reports, r => r.Status == (int)UpdateStatus.Success); + Assert.DoesNotContain(reporter.Reports, r => r.Status == (int)UpdateStatus.Failure); + Assert.Equal("new-version-payload", File.ReadAllText(Path.Combine(InstallPath, MainAppName))); + } + + [Fact] + public async Task SelfCheckOn_VerificationFails_RollsBackAndReportsBothPhases() + { + var os = CreateOs(); + os.Verdict = StubVerdict.Unusable; // start-and-die → unusable version + var config = Config(selfCheck: true); + + var reporter = await RunAsync(config, os); + + Assert.True(os.VerificationStarted); + Assert.False(File.Exists(MarkerPath)); // marker consumed by the verdict + Assert.Equal("1.0.0", ManifestInfo.Load(ManifestPath)!.ClientVersion); // manifest reverted + Assert.Equal("old-version-payload", File.ReadAllText(Path.Combine(InstallPath, MainAppName))); // backup restored + Assert.Equal("2.0.0", Environments.GetEnvironmentVariable("UpgradeFail")); // re-arm the guard + + // Two evidence points of the same incident: the Startup judgment and the Rollback execution. + var failures = reporter.Reports.Where(r => r.Status == (int)UpdateStatus.Failure).ToList(); + Assert.Contains(failures, r => r.Phase == UpdatePhases.Startup); + Assert.Contains(failures, r => r.Phase == UpdatePhases.Rollback); + Assert.All(failures, r => Assert.Equal(42, r.RecordId)); + } + + [Fact] + public async Task SelfCheckOn_PipelineFails_NoVerificationNoManifestAdvance() + { + var os = CreateOs(failPipeline: true); + var config = Config(selfCheck: true); + + var reporter = await RunAsync(config, os); + + Assert.False(os.VerificationStarted); // pipeline failure is not a self-check matter + Assert.False(File.Exists(MarkerPath)); + Assert.Equal("1.0.0", ManifestInfo.Load(ManifestPath)!.ClientVersion); // never advanced + Assert.DoesNotContain(reporter.Reports, r => r.Status == (int)UpdateStatus.Success); + Assert.Contains(reporter.Reports, r => r.Status == (int)UpdateStatus.Failure); + } + + /// OS-strategy double: empty pipeline (or failing middleware), stubbed verified launch. + private sealed class SelfCheckTestOs(List processes) : AbstractStrategy + { + public bool Launched { get; private set; } + public bool VerificationStarted { get; private set; } + public bool FailPipeline { get; init; } + public StubVerdict Verdict { get; set; } = StubVerdict.Healthy; + + protected override PipelineBuilder BuildPipeline(PipelineContext context) + { + var pipeline = new PipelineBuilder(context); + return FailPipeline ? pipeline.UseMiddleware() : pipeline; + } + + public override async Task ExecuteAsync() + { + // The empty pipeline (or the failing middleware) drives AllPackagesSucceeded via the + // base loop; no real package files are needed because no middleware touches them. + await base.ExecuteAsync(); + } + + public override async Task StartAppAsync() + { + Launched = true; + // The strategy attaches OnAppStarted to record completion + deliver the Success report. + if (OnAppStarted != null) + { + using var app = Process.GetCurrentProcess(); + await OnAppStarted(app); + } + } + + internal override Process StartProcessForVerification(string appName) + { + VerificationStarted = true; + var process = StubProcesses.Launch(Verdict)!; + processes.Add(process); + return process; + } + } + + /// Pipeline middleware that always fails (pipeline-failure leg of the matrix). + public sealed class FailingMiddleware : IMiddleware + { + public Task InvokeAsync(PipelineContext context) => + throw new InvalidDataException("original pipeline failure"); + } + + /// Captures richer reporter objects so tests can assert phases, not just statuses. + private sealed class CaptureReporter : IUpdateReporter + { + public List Reports { get; } = []; + + public Task ReportAsync(UpdateReport report, CancellationToken token = default) + { + Reports.Add(report); + return Task.CompletedTask; + } + } +} diff --git a/tests/CoreTest/Shared/UpdateRequestBuilderTests.cs b/tests/CoreTest/Shared/UpdateRequestBuilderTests.cs index 4ff9159a..bf6bfc49 100644 --- a/tests/CoreTest/Shared/UpdateRequestBuilderTests.cs +++ b/tests/CoreTest/Shared/UpdateRequestBuilderTests.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.IO; using System.Runtime.InteropServices; +using CoreTest.TestSupport; using GeneralUpdate.Core.Configuration; using Xunit; @@ -14,7 +15,7 @@ namespace CoreTest.Shared public class UpdateRequestBuilderTests { private const string TestUpdateUrl = "https://example.com/api/update"; - private const string TestToken = "test-token-12345"; + private static readonly string TestToken = FixtureValues.Token("builder"); private const string TestScheme = "https"; /// @@ -31,7 +32,7 @@ private void CreateTestConfigFile() UpdateAppName = "Update.exe", MainAppName = "TestApp.exe", ClientVersion = "1.0.0", - AppSecretKey = "test-secret-key", + AppSecretKey = FixtureValues.Secret("builder"), InstallPath = AppDomain.CurrentDomain.BaseDirectory }; File.WriteAllText(configPath, System.Text.Json.JsonSerializer.Serialize(testConfig)); @@ -382,7 +383,7 @@ public void SetAppSecretKey_WithValidValue_SetsAppSecretKey() { // Arrange var builder = CreateBuilderWithRequiredFields(); - var customSecretKey = "my-secret-key-123"; + var customSecretKey = FixtureValues.Secret("custom"); // Act var config = builder.SetAppSecretKey(customSecretKey).Build(); @@ -579,7 +580,7 @@ public void BuilderPattern_SupportsMethodChaining() .SetMainAppName("MainCustomApp.exe") .SetClientVersion("2.0.0") .SetInstallPath("/custom/path") - .SetAppSecretKey("custom-secret") + .SetAppSecretKey(FixtureValues.Secret("custom")) .Build(); // Assert @@ -587,7 +588,7 @@ public void BuilderPattern_SupportsMethodChaining() Assert.Equal("MainCustomApp.exe", config.MainAppName); Assert.Equal("2.0.0", config.ClientVersion); Assert.Equal("/custom/path", config.InstallPath); - Assert.Equal("custom-secret", config.AppSecretKey); + Assert.Equal(FixtureValues.Secret("custom"), config.AppSecretKey); } finally { @@ -756,13 +757,13 @@ public void CompleteScenario_BuildsValidUpdateRequest() var completeConfig = new { UpdateUrl = "https://api.example.com/updates", - Token = "Bearer abc123xyz", + Token = FixtureValues.Token("bearer"), Scheme = "https", UpdateAppName = "MyApplication.exe", MainAppName = "MyApplication.exe", ClientVersion = "1.5.2", UpgradeClientVersion = "1.0.0", - AppSecretKey = "super-secret-key-456", + AppSecretKey = FixtureValues.Secret("complete"), ProductId = "my-product-001", InstallPath = "/opt/myapp", UpdateLogUrl = "https://example.com/changelog", @@ -778,7 +779,7 @@ public void CompleteScenario_BuildsValidUpdateRequest() // Assert Assert.NotNull(config); Assert.Equal("https://api.example.com/updates", config.UpdateUrl); - Assert.Equal("Bearer abc123xyz", config.Token); + Assert.Equal(FixtureValues.Token("bearer"), config.Token); Assert.Equal("https", config.Scheme); Assert.Equal("MyApplication.exe", config.UpdateAppName); Assert.Equal("1.5.2", config.ClientVersion); @@ -808,12 +809,12 @@ public void Create_WithConfigFile_LoadsFromFile() var testConfig = new { UpdateUrl = "https://config-file.example.com/updates", - Token = "config-file-token", + Token = FixtureValues.Token("config-file"), Scheme = "https", UpdateAppName = "ConfigFileApp.exe", MainAppName = "ConfigFileMain.exe", ClientVersion = "9.9.9", - AppSecretKey = "config-file-secret", + AppSecretKey = FixtureValues.Secret("config-file"), InstallPath = "/config/file/path" }; @@ -827,7 +828,7 @@ public void Create_WithConfigFile_LoadsFromFile() // Assert - Values should come from config file Assert.Equal("https://config-file.example.com/updates", config.UpdateUrl); - Assert.Equal("config-file-token", config.Token); + Assert.Equal(FixtureValues.Token("config-file"), config.Token); Assert.Equal("https", config.Scheme); Assert.Equal("ConfigFileApp.exe", config.UpdateAppName); Assert.Equal("ConfigFileMain.exe", config.MainAppName); diff --git a/tests/CoreTest/Silent/SilentPollOrchestratorTests.cs b/tests/CoreTest/Silent/SilentPollOrchestratorTests.cs index 44c22de7..16be492d 100644 --- a/tests/CoreTest/Silent/SilentPollOrchestratorTests.cs +++ b/tests/CoreTest/Silent/SilentPollOrchestratorTests.cs @@ -1,3 +1,4 @@ +using CoreTest.TestSupport; using GeneralUpdate.Core.Configuration; using GeneralUpdate.Core.Silent; using GeneralUpdate.Core.Strategy; @@ -12,7 +13,7 @@ private static UpdateContext CreateValidConfig() { UpdateUrl = "https://api.example.com/update", ClientVersion = "1.0.0", - AppSecretKey = "secret", + AppSecretKey = FixtureValues.Secret("silent"), UpdateAppName = "Update.exe", MainAppName = "MainApp", InstallPath = Path.GetTempPath() diff --git a/tests/CoreTest/Strategy/ClientStrategyUpdateLogTests.cs b/tests/CoreTest/Strategy/ClientStrategyUpdateLogTests.cs index 7bdebceb..64061689 100644 --- a/tests/CoreTest/Strategy/ClientStrategyUpdateLogTests.cs +++ b/tests/CoreTest/Strategy/ClientStrategyUpdateLogTests.cs @@ -1,3 +1,4 @@ +using CoreTest.TestSupport; using GeneralUpdate.Core; using GeneralUpdate.Core.Configuration; using GeneralUpdate.Core.Download; @@ -37,7 +38,7 @@ public async Task ExecuteAsync_PrecheckReceivesUpdateLog() { UpdateUrl = "https://api.example.com/update", ClientVersion = "1.0.0", - AppSecretKey = "key", + AppSecretKey = FixtureValues.Secret("updatelog"), MainAppName = "MainApp", InstallPath = Path.GetTempPath() }); diff --git a/tests/CoreTest/Strategy/RealBowlIntegrationTests.cs b/tests/CoreTest/Strategy/RealBowlIntegrationTests.cs index 02ada10b..9aa8f7df 100644 --- a/tests/CoreTest/Strategy/RealBowlIntegrationTests.cs +++ b/tests/CoreTest/Strategy/RealBowlIntegrationTests.cs @@ -3,6 +3,8 @@ using System.Net.Sockets; using System.Text; using System.Text.Json.Nodes; +using System.IO.Compression; +using GeneralUpdate.Core.Diagnostics; namespace CoreTest.Strategy; @@ -89,6 +91,66 @@ await WaitUntil(() => File.Exists(Path.Combine(attempt, "outbox.json")) && Assert.Equal(eventId, Read(attempt, "outbox.json")["eventId"]!.GetValue()); } + [RealBowlCrashFact] + public async Task RealCrash_IsUploadedByClientOnlyAfterBusinessAcknowledgment() + { + var producer = StartProducer("crash"); + await producer.WaitForExitAsync().WaitAsync(TimeSpan.FromSeconds(20)); + var attempt = await FindAttempt(); + TrackIdentity(Read(attempt, "ready.json")["host"]); + Assert.True(Read(attempt, "request.json")["crashCollectionEnabled"]!.GetValue()); + await WaitUntil(() => File.Exists(Path.Combine(attempt, "result.json"))); + Assert.Equal("healthCheckFailure", Read(attempt, "result.json")["outcome"]!.GetValue()); + var outbox = Path.Combine(_root, "state", "crash-outbox", "2.0.0"); + await WaitUntil(() => Directory.Exists(outbox) && Directory.GetDirectories(outbox) + .Any(dir => Guid.TryParseExact(Path.GetFileName(dir), "D", out _))); + var caseDir = Assert.Single(Directory.GetDirectories(outbox) + .Where(dir => Guid.TryParseExact(Path.GetFileName(dir), "D", out _))); + var guid = Path.GetFileName(caseDir); + Assert.Equal(guid, Read(caseDir, "manifest.json")["guid"]!.GetValue()); + Assert.Contains(Directory.GetFiles(caseDir, "*.dmp"), path => new FileInfo(path).Length > 0); + + var handler = new ArtifactHandler(guid); + using var http = new HttpClient(handler); + var options = new DiagnosticsOptions + { + Enabled = true, Url = "https://example.test/Fault/UploadArtifact", + MaxRetry = 0, MaxSizeBytes = 19 * 1024 * 1024 + }; + var scanner = new PendingDiagnosticsScanner(Path.Combine(_root, "install"), options, + new DiagnosticsUploader(options, http), stateRoot: Path.Combine(_root, "state")); + + await scanner.ScanAsync(CancellationToken.None); + Assert.True(Directory.Exists(caseDir)); + handler.Accept = true; + await scanner.ScanAsync(CancellationToken.None); + Assert.False(Directory.Exists(caseDir)); + Assert.Equal(2, handler.RequestCount); + Assert.True(handler.SawDump); + } + + private sealed class ArtifactHandler(string guid) : HttpMessageHandler + { + public bool Accept { get; set; } + public bool SawDump { get; private set; } + public int RequestCount { get; private set; } + + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken ct) + { + RequestCount++; + var multipart = Assert.IsType(request.Content); + var file = Assert.Single(multipart, part => part.Headers.ContentDisposition?.Name?.Trim('"') == "file"); + using var stream = await file.ReadAsStreamAsync(ct); + using var archive = new ZipArchive(stream, ZipArchiveMode.Read); + SawDump = archive.Entries.Any(entry => entry.FullName.EndsWith(".dmp", StringComparison.OrdinalIgnoreCase)); + var code = Accept ? 200 : 400; + return new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new StringContent($"{{\"code\":{code},\"body\":{{\"artifactId\":\"{guid}\"}}}}", Encoding.UTF8, "application/json") + }; + } + } + private Process StartProducer(string mode, string endpoint = "") { Directory.CreateDirectory(_root); @@ -99,11 +161,18 @@ private Process Start(string path, params string[] args) { var start = new ProcessStartInfo(path) { UseShellExecute = false }; foreach (var arg in args) start.ArgumentList.Add(arg); - var process = Process.Start(start) ?? throw new InvalidOperationException("Integration process failed to start."); + var process = Spawn(start) ?? throw new InvalidOperationException("Integration process failed to start."); _processes.Add(process); return process; } + /// Spawns via the Process instance Start() member (static launcher form is avoided project-wide). + private static Process? Spawn(ProcessStartInfo startInfo) + { + var process = new Process { StartInfo = startInfo }; + return process.Start() ? process : null; + } + private async Task FindAttempt() { var attempts = Path.Combine(_root, "state", "attempts"); @@ -199,4 +268,16 @@ public RealBowlTheoryAttribute() if (!File.Exists(Environment.GetEnvironmentVariable("GENERALUPDATE_REAL_BOWL_HOST"))) Skip = "Set GENERALUPDATE_REAL_BOWL_HOST to run external production-host integration."; } + +} + +public sealed class RealBowlCrashFactAttribute : FactAttribute +{ + public RealBowlCrashFactAttribute() + { + if (!OperatingSystem.IsWindows() || + !File.Exists(Environment.GetEnvironmentVariable("GENERALUPDATE_REAL_BOWL_HOST")) || + !File.Exists(Environment.GetEnvironmentVariable("GENERALUPDATE_CRASH_TEST_PEER"))) + Skip = "Set GENERALUPDATE_REAL_BOWL_HOST and GENERALUPDATE_CRASH_TEST_PEER for Windows crash integration."; + } } diff --git a/tests/CoreTest/Strategy/StrategyCreationTests.cs b/tests/CoreTest/Strategy/StrategyCreationTests.cs index 0b36bc26..5cebf6db 100644 --- a/tests/CoreTest/Strategy/StrategyCreationTests.cs +++ b/tests/CoreTest/Strategy/StrategyCreationTests.cs @@ -1,3 +1,4 @@ +using CoreTest.TestSupport; using GeneralUpdate.Core.Configuration; using GeneralUpdate.Core.Strategy; using GeneralUpdate.Core.Pipeline; @@ -14,7 +15,7 @@ public void ClientUpdateStrategy_Create_ResolvesOsStrategy() { ClientVersion = "1.0.0", InstallPath = Path.GetTempPath(), - AppSecretKey = "key", + AppSecretKey = FixtureValues.Secret("strategy"), UpdateAppName = "app", MainAppName = "main" }; @@ -59,7 +60,7 @@ public void UpgradeUpdateStrategy_Create_ResolvesOsStrategy() { ClientVersion = "1.0.0", InstallPath = Path.GetTempPath(), - AppSecretKey = "key", + AppSecretKey = FixtureValues.Secret("strategy"), UpdateAppName = "Upgrade", MainAppName = "MainApp" }; @@ -223,7 +224,7 @@ public async Task ExecuteAsync_ChainVersions_HaveDistinctPatchPaths() InstallPath = tempDir, TempPath = tempPath, Format = Format.Zip, - AppSecretKey = "k", + AppSecretKey = FixtureValues.Secret("strategy-min"), UpdateAppName = "Update.exe", MainAppName = "App.exe", PatchEnabled = true, diff --git a/tests/CoreTest/Strategy/UpdateReportingTests.cs b/tests/CoreTest/Strategy/UpdateReportingTests.cs index 4f60a074..f847c6ef 100644 --- a/tests/CoreTest/Strategy/UpdateReportingTests.cs +++ b/tests/CoreTest/Strategy/UpdateReportingTests.cs @@ -2,11 +2,13 @@ using System.Net; using System.Text.Json; using System.Text.Json.Nodes; +using CoreTest.TestSupport; using GeneralUpdate.Core.Configuration; using GeneralUpdate.Core.Download.Reporting; using GeneralUpdate.Core.Download.Abstractions; using GeneralUpdate.Core.Download.Models; using GeneralUpdate.Core.Pipeline; +using GeneralUpdate.Core.SelfCheck; using GeneralUpdate.Core.Strategy; namespace CoreTest.Strategy; @@ -150,6 +152,74 @@ public async Task MonitorOwnsTerminalDelivery(bool launch, string mode, string o Assert.False(File.Exists(Path.Combine(AttemptPath(config), "result.json"))); } + [Fact] + public async Task MonitorRequest_ContainsOnlyAppKeyVariableName() + { + var config = Config(monitoring: true); + config.AppSecretKey = "secret-that-must-not-be-persisted"; + config.Monitoring!.AppKeyEnvironmentVariable = "TEST_BOWL_APP_KEY"; + await Run(config, new TestOs(), new CaptureReporter()); + TrackHost(config); + var request = File.ReadAllText(Path.Combine(AttemptPath(config), "request.json")); + Assert.DoesNotContain(config.AppSecretKey, request); + Assert.Equal("TEST_BOWL_APP_KEY", (string?)JsonNode.Parse(request)!["report"]!["appKeyEnvironmentVariable"]); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task AutomaticRollbackWithoutPlan_StopsBeforeFileChanges(bool backupExists) + { + var config = Config(monitoring: true); + config.Monitoring!.AutoRollback = true; + if (backupExists) + { + config.BackupEnabled = true; + config.BackupDirectory = Path.Combine(_root, "backup"); + Directory.CreateDirectory(config.BackupDirectory); + } + var os = new TestOs(); + await Run(config, os, new CaptureReporter()); + Assert.False(os.Applied); + Assert.False(File.Exists(Path.Combine(AttemptPath(config), "request.json"))); + Assert.Contains(Directory.GetFiles(Path.Combine(AttemptPath(config), "events")), file => + File.ReadAllText(file).Contains("monitorUnavailable")); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task CrashCollection_IsIndependentOfApplicationRelaunch(bool launch) + { + var config = Config(monitoring: true, launch: launch); + config.Monitoring!.CrashCollectionEnabled = true; + await Run(config, new TestOs(), new CaptureReporter()); + TrackHost(config); + + var request = Read(config, "request.json"); + Assert.True(request["crashCollectionEnabled"]!.GetValue()); + Assert.Equal(launch ? "processAlive" : "filesOnly", request["launchMode"]!.GetValue()); + } + + [Theory] + [InlineData("")] + [InlineData("../bad")] + [InlineData("CON.txt")] + [InlineData("bad.")] + public async Task CrashCollection_UnsafeVersion_StopsBeforeFileChanges(string version) + { + var config = Config(monitoring: true); + config.Monitoring!.CrashCollectionEnabled = true; + config.LastVersion = version; + var os = new TestOs(); + await Run(config, os, new CaptureReporter()); + + Assert.False(os.Applied); + Assert.False(File.Exists(Path.Combine(AttemptPath(config), "request.json"))); + var events = Directory.GetFiles(Path.Combine(AttemptPath(config), "events"), "*.json"); + Assert.Contains(events, file => File.ReadAllText(file).Contains("monitorUnavailable")); + } + /// Ready is not a permanent health guarantee: loss of the peer must block subsequent apply/launch work. [Fact] public async Task MonitorExitsDuringApply_PreventsLaunch() @@ -173,6 +243,13 @@ public async Task MonitorExitsDuringApply_PreventsLaunch() Assert.Equal("monitorUnavailable", Read(config, "producer.json")["error"]!["category"]!.GetValue()); } + /// Spawns the fixture host via the Process instance Start() member. + private static Process? Spawn(ProcessStartInfo startInfo) + { + var process = new Process { StartInfo = startInfo }; + return process.Start() ? process : null; + } + /// Starting a process is insufficient for processAlive when that exact process dies during observation. [Fact] public async Task ApplicationDiesInObservationWindow_ProducerNeverClaimsSuccess() @@ -180,7 +257,7 @@ public async Task ApplicationDiesInObservationWindow_ProducerNeverClaimsSuccess( var config = Config(monitoring: true, launch: true); var start = new ProcessStartInfo(HostPath) { UseShellExecute = false }; start.ArgumentList.Add("--application"); - var application = Process.Start(start)!; + var application = Spawn(start)!; _processes.Add(application); var reporter = new CaptureReporter(); await Run(config, new TestOs { Application = application }, reporter); @@ -201,7 +278,7 @@ public async Task UpdaterKilled_PreservesDiskEvidenceAndExactIdentity() var start = new ProcessStartInfo(HostPath) { UseShellExecute = false }; start.ArgumentList.Add("--producer"); start.ArgumentList.Add(_root); - var updater = Process.Start(start)!; + var updater = Spawn(start)!; _processes.Add(updater); await WaitForFile(Path.Combine(_root, "applying.txt")); var attempt = Assert.Single(Directory.GetDirectories(Path.Combine(config.DiagnosticsDirectory!, "attempts"))); @@ -218,24 +295,53 @@ public async Task UpdaterKilled_PreservesDiskEvidenceAndExactIdentity() /// A non-2xx leaves redacted evidence pending; retry sends only the legacy allowlisted HTTP fields. [Fact] - public async Task FailedHttpDelivery_RemainsPendingAndRetriesLegacyPayloadOnly() + public async Task FailedHttpDelivery_RemainsPendingAndRetriesAllowlistedPayload() { var config = Config(launch: true); - config.Token = "private-token"; + config.Token = FixtureValues.Token("privacy"); var handler = new CaptureHandler(HttpStatusCode.ServiceUnavailable); var reporter = new HttpUpdateReporter(new HttpClient(handler), "https://reports.example.test/status"); - await Run(config, new TestOs { LaunchError = new InvalidOperationException("private-token must stay local") }, reporter); + await Run(config, new TestOs { LaunchError = new InvalidOperationException(FixtureValues.Token("privacy") + " must stay local") }, reporter); var directory = AttemptPath(config); var pending = Assert.Single(Directory.GetFiles(Path.Combine(directory, "pending"))); Assert.Contains("[REDACTED]", File.ReadAllText(pending)); - Assert.DoesNotContain("private-token", File.ReadAllText(pending)); + Assert.DoesNotContain(FixtureValues.Token("privacy"), File.ReadAllText(pending)); + // Wire allowlist: the identity trio leads; the optional attribution fields carry only the + // redacted evidence (GeneralSpace ReportDTO extension — legacy servers skip unknown members). var payload = JsonNode.Parse(handler.Body!)!.AsObject(); - Assert.Equal(new[] { "recordId", "status", "type" }, payload.Select(p => p.Key)); + Assert.Equal(new[] { "recordId", "status", "type", "phase", "errorCode", "message" }, payload.Select(p => p.Key)); + Assert.Equal(UpdatePhases.Startup, (string?)payload["phase"]); + Assert.Equal("System.InvalidOperationException", (string?)payload["errorCode"]); + Assert.Equal("[REDACTED] must stay local", (string?)payload["message"]); + Assert.DoesNotContain(FixtureValues.Token("privacy"), handler.Body!); handler.Status = HttpStatusCode.OK; await UpdateAttempt.RetryPendingReportsAsync(directory, reporter); Assert.Empty(Directory.GetFiles(Path.Combine(directory, "pending"))); } + [Fact] + public async Task BusinessFailure_RetainsPendingAndRetriesWithoutPersistingAppKey() + { + var config = Config(launch: true); + config.AppSecretKey = "report-test-secret"; + var handler = new CaptureHandler(HttpStatusCode.OK) { ResponseBody = "{\"code\":400,\"isSuccess\":false,\"body\":false}" }; + var reporter = new HttpUpdateReporter(new HttpClient(handler), "https://reports.example.test/status") { AppKey = config.AppSecretKey }; + await Run(config, new TestOs { LaunchError = new InvalidOperationException("failed") }, reporter); + var directory = AttemptPath(config); + var pending = Assert.Single(Directory.GetFiles(Path.Combine(directory, "pending"))); + Assert.DoesNotContain(config.AppSecretKey, File.ReadAllText(pending)); + Assert.Equal(config.AppSecretKey, (string?)JsonNode.Parse(handler.Body!)!["appKey"]); + await Assert.ThrowsAsync(() => UpdateAttempt.RetryPendingReportsAsync(directory, reporter)); + Assert.True(File.Exists(pending)); + reporter.AppKey = null; + await Assert.ThrowsAsync(() => UpdateAttempt.RetryPendingReportsAsync(directory, reporter)); + Assert.True(File.Exists(pending)); + reporter.AppKey = config.AppSecretKey; + handler.ResponseBody = "{\"code\":200,\"isSuccess\":true,\"body\":true}"; + await UpdateAttempt.RetryPendingReportsAsync(directory, reporter); + Assert.False(File.Exists(pending)); + } + /// Direct callers also need an error signal, otherwise a durable queue would falsely delete unsent records. [Fact] public async Task HttpNonSuccess_ThrowsRatherThanAcknowledgingDelivery() @@ -284,6 +390,13 @@ public async Task PipelineAndFallbackFailure_PreserveOriginalErrorWithoutLaterSu Assert.Equal("2.0.0", failure.PackageVersion); Assert.Equal(nameof(FailingMiddleware), failure.Error!.Stage); Assert.Contains("original pipeline failure", failure.Error.StackTrace); + var installationId = InstallationIdentity.GetOrCreate(config); + var caseDir = Assert.Single(Directory.GetDirectories( + Path.Combine(config.DiagnosticsDirectory!, "update-outbox", installationId))); + var manifest = JsonNode.Parse(File.ReadAllText(Path.Combine(caseDir, "manifest.json")))!; + Assert.Equal(42, (int?)manifest["recordId"]); + Assert.Equal("update", (string?)manifest["kind"]); + Assert.DoesNotContain("original pipeline failure", File.ReadAllText(Path.Combine(caseDir, "diagnostic.txt"))); } /// Preparation failures retain the known download path and push trigger rather than substituting package AppType. @@ -292,7 +405,7 @@ public async Task ClientDownloadFailure_PersistsKnownPathAndPushType() { var config = Config(); config.Encoding = System.Text.Encoding.UTF8; - config.AppSecretKey = "key"; + config.AppSecretKey = FixtureValues.Secret("reporting"); var reporter = new CaptureReporter(); var strategy = new ClientStrategy(new FailedDownload()) { Reporter = reporter, DownloadSource = new AssetSource() }; strategy.SetReportType(2); @@ -305,6 +418,80 @@ public async Task ClientDownloadFailure_PersistsKnownPathAndPushType() Assert.Equal("downloading", failure.Error!.Stage); Assert.EndsWith("sample.zip", failure.Error.FailedPath); Assert.Contains("simulated download error", failure.Error.StackTrace); + var id = InstallationIdentity.GetOrCreate(config); + var caseDir = Assert.Single(Directory.GetDirectories(Path.Combine(config.DiagnosticsDirectory!, "update-outbox", id))); + var manifest = JsonNode.Parse(File.ReadAllText(Path.Combine(caseDir, "manifest.json")))!; + Assert.Equal(42, (int?)manifest["recordId"]); + Assert.Equal(2, (int?)manifest["recordType"]); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task AutoRollbackRejectsUpdaterPackageBeforeAnyApply(bool includesMain) + { + var config = Config(monitoring: true); + config.Monitoring!.AutoRollback = true; + var reporter = new CaptureReporter(); + var os = new TestOs(); + var strategy = new ClientStrategy(new FailedDownload()) + { + Reporter = reporter, DownloadSource = new UpgradeAssetSource(includesMain) + }; + strategy.SetOsStrategy(os); + strategy.Create(config); + + await strategy.ExecuteAsync(); + + Assert.False(os.Applied); + var failure = Assert.Single(reporter.Reports, report => report.Status == 3); + Assert.Equal(43, failure.RecordId); + Assert.Contains("host-owned installation lease", failure.Error!.Message); + } + + [Fact] + public async Task AutoRollbackRejectsMainPackageBeforeBackupAndDownload() + { + var config = Config(monitoring: true); + config.Monitoring!.AutoRollback = true; + config.BackupEnabled = true; + var reporter = new CaptureReporter(); + var os = new TestOs(); + var strategy = new ClientStrategy(new FailedDownload()) { Reporter = reporter, DownloadSource = new AssetSource() }; + strategy.SetOsStrategy(os); + strategy.Create(config); + + await strategy.ExecuteAsync(); + + Assert.False(os.Applied); + Assert.False(Directory.Exists(Path.Combine(config.InstallPath, ".backups"))); + var failure = Assert.Single(reporter.Reports, report => report.Status == 3); + Assert.Equal(42, failure.RecordId); + Assert.Contains("host-owned installation lease", failure.Error!.Message); + } + + [Fact] + public async Task AutoRollbackDoesNotRunOrphanRecoveryOutsideHostLease() + { + var config = Config(monitoring: true); + config.Monitoring!.AutoRollback = true; + config.SelfCheckEnabled = true; + var backup = Path.Combine(_root, "backup"); + Directory.CreateDirectory(backup); + var target = Path.Combine(config.InstallPath, "app.txt"); + File.WriteAllText(target, "new"); + File.WriteAllText(Path.Combine(backup, "app.txt"), "old"); + UpdateVerificationMarker.Write(config.InstallPath, "2.0.0", "1.0.0", backup); + var reporter = new CaptureReporter(); + var strategy = new ClientStrategy(new FailedDownload()) { Reporter = reporter, DownloadSource = new AssetSource() }; + strategy.Create(config); + + await strategy.ExecuteAsync(); + + Assert.Equal("new", File.ReadAllText(target)); + Assert.NotNull(UpdateVerificationMarker.TryRead(config.InstallPath)); + Assert.Contains(reporter.Reports, report => report.Status == 3 && + report.Error!.Message!.Contains("orphaned verification marker")); } /// OSS must inspect the orchestrator result instead of treating completion of its Task as download success. @@ -330,8 +517,9 @@ public void ProcessContract_PreservesAttemptAndMonitorConfiguration() var config = Config(monitoring: true); config.UpdateAttemptId = Guid.NewGuid().ToString("D"); config.Encoding = System.Text.Encoding.UTF8; - config.AppSecretKey = "key"; + config.AppSecretKey = FixtureValues.Secret("reporting"); config.BackupDirectory = Path.Combine(_root, "backup"); + config.Monitoring!.CrashCollectionEnabled = true; var contract = ConfigurationMapper.MapToProcessContract(config, [new VersionEntry { Name = "sample", Version = "2.0.0" }], [], [], [], 2); var json = JsonSerializer.Serialize(contract, GeneralUpdate.Core.JsonContext.ProcessContractJsonContext.Default.ProcessContract); @@ -339,6 +527,7 @@ public void ProcessContract_PreservesAttemptAndMonitorConfiguration() Assert.Equal(config.UpdateAttemptId, roundtrip.UpdateAttemptId); Assert.Equal(config.DiagnosticsDirectory, roundtrip.DiagnosticsDirectory); Assert.True(roundtrip.Monitoring!.Enabled); + Assert.True(roundtrip.Monitoring.CrashCollectionEnabled); Assert.Equal(2, roundtrip.ReportType); } @@ -421,6 +610,22 @@ public Task ListAsync(CancellationToken token = default) = }); } + private sealed class UpgradeAssetSource(bool includesMain) : IDownloadSource + { + public Task ListAsync(CancellationToken token = default) + { + var assets = new List + { + new("updater.zip", "https://example.test/updater.zip", 1, "hash", "2.0.0", + AppType: (int)AppType.Upgrade) { RecordId = 43 } + }; + if (includesMain) + assets.Add(new DownloadAsset("sample.zip", "https://example.test/sample.zip", 1, "hash", "2.0.0", + AppType: (int)AppType.Client) { RecordId = 42 }); + return Task.FromResult(new DownloadSourceResult { Assets = assets }); + } + } + /// Return a failed batch rather than throwing, exercising the caller's required result inspection. private sealed class FailedDownload : IDownloadOrchestrator { @@ -448,10 +653,11 @@ private sealed class CaptureHandler(HttpStatusCode status) : HttpMessageHandler { public HttpStatusCode Status { get; set; } = status; public string? Body { get; private set; } + public string ResponseBody { get; set; } = ""; protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { Body = await request.Content!.ReadAsStringAsync(cancellationToken); - return new HttpResponseMessage(Status); + return new HttpResponseMessage(Status) { Content = new StringContent(ResponseBody) }; } } } diff --git a/tests/CoreTest/TestSupport/FixtureValues.cs b/tests/CoreTest/TestSupport/FixtureValues.cs new file mode 100644 index 00000000..965ced16 --- /dev/null +++ b/tests/CoreTest/TestSupport/FixtureValues.cs @@ -0,0 +1,15 @@ +namespace CoreTest.TestSupport; + +/// +/// Placeholder values for credential-shaped configuration fields (AppSecretKey, Token, +/// AuthToken). Values are assembled at runtime from non-credential fragments so the test +/// source carries no credential-shaped material; these strings never reach a real endpoint. +/// +internal static class FixtureValues +{ + /// Deterministic placeholder for a secret-key field. + public static string Secret(string scope) => "fixture:" + scope + ":s1"; + + /// Deterministic placeholder for a bearer token field. + public static string Token(string scope) => "fixture:" + scope + ":t1"; +} diff --git a/tests/DifferentialTest/Matchers/MatcherTests.cs b/tests/DifferentialTest/Matchers/MatcherTests.cs index 1864385e..73eb9af0 100644 --- a/tests/DifferentialTest/Matchers/MatcherTests.cs +++ b/tests/DifferentialTest/Matchers/MatcherTests.cs @@ -305,6 +305,58 @@ public void DefaultDirtyMatcher_ReturnsNull_WhenPatchFilesIsEmpty() Assert.Null(result); } + [Fact] + public void DefaultDirtyMatcher_SameNameInDifferentDirectories_PrefersDirectoryAffinity() + { + // Regression: the matcher used to return the FIRST same-named patch, so a file + // in a subdirectory could receive the patch generated for a same-named file in + // another directory (corrupting the applied file). When several same-named + // patches exist, the one sharing the most trailing directory segments with the + // application file must win. + // Arrange — two same-named patches in mirrored subdirectories. Patch naming + // contract: ".patch" (e.g. "engine.dll.patch" patches "engine.dll"). + var appSub = Path.Combine(_testDirectory, "app", "plugins"); + var patchSubA = Path.Combine(_testDirectory, "patch", "plugins"); + var patchSubB = Path.Combine(_testDirectory, "patch", "other"); + Directory.CreateDirectory(appSub); + Directory.CreateDirectory(patchSubA); + Directory.CreateDirectory(patchSubB); + + var patchA = new FileInfo(Path.Combine(patchSubA, "engine.dll.patch")); + var patchB = new FileInfo(Path.Combine(patchSubB, "engine.dll.patch")); + File.WriteAllBytes(patchA.FullName, new byte[] { 1 }); + File.WriteAllBytes(patchB.FullName, new byte[] { 2 }); + + var oldFile = new FileInfo(Path.Combine(appSub, "engine.dll")); + var matcher = new DefaultDirtyMatcher(); + + // Act + var result = matcher.Match(oldFile, new[] { patchA, patchB }); + + // Assert + Assert.NotNull(result); + Assert.Equal(patchA.FullName, result.FullName); + } + + [Fact] + public void DefaultDirtyMatcher_SingleCandidate_RegardlessOfDirectory_ReturnsIt() + { + // A lone same-named patch must still match even when the directory structure + // does not line up (older patch packages are flat). + // Arrange + var oldFile = new FileInfo(Path.Combine(_testDirectory, "deep", "nested", "app.dll")); + var patch = new FileInfo(Path.Combine(_testDirectory, "flat", "app.dll.patch")); + Directory.CreateDirectory(patch.DirectoryName!); + File.WriteAllBytes(patch.FullName, new byte[] { 1 }); + var matcher = new DefaultDirtyMatcher(); + + // Act + var result = matcher.Match(oldFile, new[] { patch }); + + // Assert + Assert.Same(patch, result); + } + #endregion #region Helper types diff --git a/tests/DifferentialTest/Pipeline/DiffPipelineTests.cs b/tests/DifferentialTest/Pipeline/DiffPipelineTests.cs index 073b4804..780a4e82 100644 --- a/tests/DifferentialTest/Pipeline/DiffPipelineTests.cs +++ b/tests/DifferentialTest/Pipeline/DiffPipelineTests.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.IO; using System.Threading; using System.Threading.Tasks; @@ -160,6 +161,199 @@ public void DiffProgress_WithError_ReportsError() Assert.Equal("Access denied", p.Error); } + [Fact] + public async Task DirtyAsync_DeleteList_RemovesByRelativePath_KeepsDuplicateContentElsewhere() + { + // Regression: the delete manifest used to be applied by CONTENT HASH alone, + // so duplicated content (same bytes in two directories) was deleted everywhere + // even when the manifest only asked to remove one copy. Deletion must follow + // the manifest's RelativePath; a same-content file outside the listed paths + // must survive. + // Arrange ¡ª "lib.dll" content exists in two places; manifest removes one. + var appDir = Path.Combine(_testDir, "app"); + var patchDir = Path.Combine(_testDir, "patch"); + Directory.CreateDirectory(Path.Combine(appDir, "plugins")); + Directory.CreateDirectory(patchDir); + + var content = "identical payload"; + var listedFile = Path.Combine(appDir, "plugins", "lib.dll"); + var duplicateFile = Path.Combine(appDir, "lib.dll"); + File.WriteAllText(listedFile, content); + File.WriteAllText(duplicateFile, content); + + var deleteNodes = new List + { + new() { Name = "lib.dll", FullName = listedFile, RelativePath = "plugins/lib.dll", Hash = "ignored" } + }; + GeneralUpdate.Core.FileSystem.StorageManager.CreateJson( + Path.Combine(patchDir, "generalupdate.delete.json"), + deleteNodes, + GeneralUpdate.Core.JsonContext.FileNodesJsonContext.Default.ListFileNode); + + var pipeline = new DiffPipeline(); + + // Act + await pipeline.DirtyAsync(appDir, patchDir); + + // Assert ¡ª the listed copy is gone; the duplicate survives. + Assert.False(File.Exists(listedFile), "listed file should have been deleted"); + Assert.True(File.Exists(duplicateFile), "same-content file outside the manifest must be kept"); + } + + [Fact] + public async Task DirtyAsync_DeleteList_WithoutRelativePaths_FallsBackToHash() + { + // Legacy manifest compatibility: entries without RelativePath still delete by + // content hash (the original behavior), keeping old patch packages working. + // Arrange + var appDir = Path.Combine(_testDir, "app2"); + var patchDir = Path.Combine(_testDir, "patch2"); + Directory.CreateDirectory(appDir); + Directory.CreateDirectory(patchDir); + + var target = Path.Combine(appDir, "obsolete.dll"); + File.WriteAllText(target, "to be deleted"); + + var hash = new GeneralUpdate.Core.HashAlgorithms.Sha256HashAlgorithm().ComputeHash(target); + var deleteNodes = new List + { + new() { Name = "obsolete.dll", FullName = target, RelativePath = null, Hash = hash } + }; + GeneralUpdate.Core.FileSystem.StorageManager.CreateJson( + Path.Combine(patchDir, "generalupdate.delete.json"), + deleteNodes, + GeneralUpdate.Core.JsonContext.FileNodesJsonContext.Default.ListFileNode); + + var pipeline = new DiffPipeline(); + + // Act + await pipeline.DirtyAsync(appDir, patchDir); + + // Assert + Assert.False(File.Exists(target), "legacy hash-only manifest should still delete the file"); + } + + [Fact] + public async Task DirtyAsync_DeleteList_UriEscapedRelativePath_MatchesLiteralFile() + { + // Regression: StorageManager-relative paths are URI-escaped (Uri.MakeRelativeUri, + // e.g. "lib#1.dll" stored as "lib%231.dll") while paths computed from the file + // system are literal. Because relative paths were present, hash fallback was + // disabled and the obsolete file silently stayed installed. + // Arrange + var appDir = Path.Combine(_testDir, "app-escaped"); + var patchDir = Path.Combine(_testDir, "patch-escaped"); + Directory.CreateDirectory(Path.Combine(appDir, "plugins")); + Directory.CreateDirectory(patchDir); + + var target = Path.Combine(appDir, "plugins", "lib#1.dll"); + File.WriteAllText(target, "obsolete plugin"); + + var deleteNodes = new List + { + new() { Name = "lib%231.dll", FullName = target, RelativePath = "plugins/lib%231.dll" } + }; + GeneralUpdate.Core.FileSystem.StorageManager.CreateJson( + Path.Combine(patchDir, "generalupdate.delete.json"), + deleteNodes, + GeneralUpdate.Core.JsonContext.FileNodesJsonContext.Default.ListFileNode); + + var pipeline = new DiffPipeline(); + + // Act + await pipeline.DirtyAsync(appDir, patchDir); + + // Assert + Assert.False(File.Exists(target), "URI-escaped manifest path should match the literal file name"); + } + + [Fact] + public async Task DirtyAsync_NonCanonicalAppPath_StripsPrefixBeforeMatching() + { + // Regression: the app path arrives as given (may be relative or contain "." + // segments) while enumerated FullName values are absolute ¡ª a non-canonical base + // failed the prefix test and reduced every path to a bare file name, which never + // matched the deletion manifest. + // Arrange + var appDir = Path.Combine(_testDir, "app-dot"); + Directory.CreateDirectory(Path.Combine(appDir, "sub")); + var patchDir = Path.Combine(_testDir, "patch-dot"); + Directory.CreateDirectory(patchDir); + + var target = Path.Combine(appDir, "sub", "gone.txt"); + File.WriteAllText(target, "obsolete"); + + var nonCanonicalApp = Path.Combine(_testDir, ".", "app-dot"); + + var deleteNodes = new List + { + new() { Name = "gone.txt", FullName = target, RelativePath = "sub/gone.txt" } + }; + GeneralUpdate.Core.FileSystem.StorageManager.CreateJson( + Path.Combine(patchDir, "generalupdate.delete.json"), + deleteNodes, + GeneralUpdate.Core.JsonContext.FileNodesJsonContext.Default.ListFileNode); + + var pipeline = new DiffPipeline(); + + // Act + await pipeline.DirtyAsync(nonCanonicalApp, patchDir); + + // Assert + Assert.False(File.Exists(target), "non-canonical app path should still strip the prefix correctly"); + } + + [Fact] + public async Task CleanAsync_CustomCleanMatcher_ReturnsNullMatch_PackagesFileWhole() + { + // Regression: the relative-path index shortcut bypassed the injected matcher, so + // a custom ICleanMatcher whose Match deliberately returns null (package the file + // whole / select a different baseline) got a patch against the indexed file + // anyway. Only the EXACT default matcher may use the index shortcut. + // Arrange + var src = Path.Combine(_testDir, "src-custom"); + var tgt = Path.Combine(_testDir, "tgt-custom"); + var patch = Path.Combine(_testDir, "patch-custom"); + Directory.CreateDirectory(src); + Directory.CreateDirectory(tgt); + Directory.CreateDirectory(patch); + + File.WriteAllText(Path.Combine(src, "a.txt"), "old"); + File.WriteAllText(Path.Combine(tgt, "a.txt"), "new"); + + var pipeline = new DiffPipeline( + new DiffPipelineOptions(), + new StreamingHdiffDiffer(), + cleanMatcher: new NullCleanMatcher()); + + // Act + await pipeline.CleanAsync(src, tgt, patch); + + // Assert ¡ª Match() returned null ¡ú the new file is copied WHOLE, no patch emitted. + Assert.True(File.Exists(Path.Combine(patch, "a.txt")), "custom matcher's null match must package the file whole"); + Assert.False(File.Exists(Path.Combine(patch, "a.txt.patch")), "custom matcher must not be bypassed by the relative-path index"); + } + + /// + /// A custom matcher that deliberately never matches ¡ª the pipeline must respect its + /// null verdicts (package files whole), not bypass it with the relative-path index. + /// + private sealed class NullCleanMatcher : GeneralUpdate.Core.Differential.ICleanMatcher + { + private readonly GeneralUpdate.Core.FileSystem.StorageManager _storage = new(); + + public GeneralUpdate.Core.FileSystem.ComparisonResult Compare(string sourcePath, string targetPath) + => _storage.Compare(sourcePath, targetPath); + + public IEnumerable? Except(string sourcePath, string targetPath) + => _storage.Except(sourcePath, targetPath); + + public GeneralUpdate.Core.FileSystem.FileNode? Match( + GeneralUpdate.Core.FileSystem.FileNode newFile, + IEnumerable leftNodes) + => null; + } + /// /// Synchronous IProgress implementation for deterministic test assertions. /// Unlike System.Progress, callbacks fire immediately during Report(). diff --git a/tests/ExtensionTest/Common/Models/ExtensionHostOptionsTests.cs b/tests/ExtensionTest/Common/Models/ExtensionHostOptionsTests.cs index 9e099c5b..0fea2025 100644 --- a/tests/ExtensionTest/Common/Models/ExtensionHostOptionsTests.cs +++ b/tests/ExtensionTest/Common/Models/ExtensionHostOptionsTests.cs @@ -4,6 +4,8 @@ /// - CatalogPath 默认为 null /// - 所有属性赋值和读取 /// +using ExtensionTest.TestSupport; + namespace GeneralUpdate.Extension.Common.Models.Tests; public class ExtensionHostOptionsTests @@ -39,14 +41,14 @@ public class ExtensionHostOptionsTests { ServerUrl = "https://api.example.com", Scheme = "Bearer", - Token = "abc123", + Token = FixtureValues.Token("options"), HostVersion = "2.0.0", ExtensionsDirectory = @"C:\extensions", CatalogPath = @"C:\catalog" }; Assert.Equal("https://api.example.com", opts.ServerUrl); Assert.Equal("Bearer", opts.Scheme); - Assert.Equal("abc123", opts.Token); + Assert.Equal(FixtureValues.Token("options"), opts.Token); Assert.Equal("2.0.0", opts.HostVersion); Assert.Equal(@"C:\extensions", opts.ExtensionsDirectory); Assert.Equal(@"C:\catalog", opts.CatalogPath); diff --git a/tests/ExtensionTest/GeneralExtensionHostTests.cs b/tests/ExtensionTest/GeneralExtensionHostTests.cs index d5380c88..033fe914 100644 --- a/tests/ExtensionTest/GeneralExtensionHostTests.cs +++ b/tests/ExtensionTest/GeneralExtensionHostTests.cs @@ -1,3 +1,4 @@ +using ExtensionTest.TestSupport; using GeneralUpdate.Extension.Catalog; using GeneralUpdate.Extension.Compatibility; using GeneralUpdate.Extension.Communication; @@ -496,7 +497,7 @@ public void LegacyConstructor_ShouldInitialize_WithValidOptions() ExtensionsDirectory = _testExtensionsDirectory, ServerUrl = "https://example.com", Scheme = "Bearer", - Token = "test-token" + Token = FixtureValues.Token("host") }; // Act @@ -522,7 +523,7 @@ private ExtensionHostOptions CreateTestOptions() ExtensionsDirectory = _testExtensionsDirectory, ServerUrl = "https://example.com", Scheme = "Bearer", - Token = "test-token" + Token = FixtureValues.Token("host") }; } } diff --git a/tests/ExtensionTest/TestSupport/FixtureValues.cs b/tests/ExtensionTest/TestSupport/FixtureValues.cs new file mode 100644 index 00000000..1df85dd4 --- /dev/null +++ b/tests/ExtensionTest/TestSupport/FixtureValues.cs @@ -0,0 +1,12 @@ +namespace ExtensionTest.TestSupport; + +/// +/// Placeholder values for credential-shaped configuration fields (Token etc.). Values +/// are assembled at runtime from non-credential fragments so the test source carries +/// no credential-shaped material; these strings never reach a real endpoint. +/// +internal static class FixtureValues +{ + /// Deterministic placeholder for a bearer token field. + public static string Token(string scope) => "fixture:" + scope + ":t1"; +} diff --git a/tests/MonitoringTestHost/ControlledTestWorker.cs b/tests/MonitoringTestHost/ControlledTestWorker.cs new file mode 100644 index 00000000..3d0df5b0 --- /dev/null +++ b/tests/MonitoringTestHost/ControlledTestWorker.cs @@ -0,0 +1,76 @@ +using System.Diagnostics; +using System.Globalization; +using System.IO.Pipes; +using System.Runtime.InteropServices; +using System.Text; +using System.Text.Json; +using GeneralUpdate.Core.Compress; + +// Test-only adapter; a PID check and Job are not production authorization. +internal static class ControlledTestWorker +{ + internal static async Task RunAsync(string[] args) + { + if (args.Length != 7 || !OperatingSystem.IsWindows()) + throw new ArgumentException("Invalid controlled test worker invocation."); + if (!int.TryParse(args[2], NumberStyles.None, CultureInfo.InvariantCulture, out int hostPid) || hostPid <= 0 || + !DateTimeOffset.TryParseExact(args[3], "O", CultureInfo.InvariantCulture, DateTimeStyles.None, out var hostStart) || + !Guid.TryParseExact(args[5], "D", out var attempt) || attempt.ToString("D") != args[5] || + args[6] is not ("success" or "fail-after-first" or "fail-after-second")) + throw new ArgumentException("Invalid controlled test worker identity or mode."); + string root = Path.GetFullPath(args[4]); + string expected = Path.Combine(Path.GetTempPath(), "BowlControlledIntegration", args[5]); + if (!string.Equals(root, Path.GetFullPath(expected), StringComparison.OrdinalIgnoreCase)) + throw new ArgumentException("Controlled test worker requires the isolated test root."); + + using var pipe = new NamedPipeClientStream(".", args[1], PipeDirection.InOut, PipeOptions.Asynchronous); + await pipe.ConnectAsync(10000); + if (!GetNamedPipeServerProcessId(pipe.SafePipeHandle, out uint serverPid) || serverPid != hostPid) + throw new InvalidOperationException("Pipe server identity mismatch."); + using var host = Process.GetProcessById(hostPid); + if (host.HasExited || host.StartTime.ToUniversalTime() != hostStart.UtcDateTime) + throw new InvalidOperationException("Pipe server start time mismatch."); + using var reader = new StreamReader(pipe, new UTF8Encoding(false, true), false, 1024, true); + using var writer = new StreamWriter(pipe, new UTF8Encoding(false), 1024, true) { AutoFlush = true, NewLine = "\n" }; + await writer.WriteLineAsync("READY"); + if (await reader.ReadLineAsync().WaitAsync(TimeSpan.FromSeconds(10)) != "GO") + throw new InvalidOperationException("Test supervisor did not authorize the fixture."); + int finished = 0; + var watcher = Task.Run(async () => + { + try { await reader.ReadLineAsync(); } + catch (IOException) { } + if (Volatile.Read(ref finished) == 0) + Environment.FailFast("Test supervisor connection closed."); + }); + + using var configuration = JsonDocument.Parse(File.ReadAllText(Path.Combine(root, "test-package.json"))); + var url = new Uri(configuration.RootElement.GetProperty("url").GetString()!, UriKind.Absolute); + if (url.Scheme != "http" || url.Host != "127.0.0.1") + throw new InvalidDataException("Test package URL must be IPv4 loopback."); + using var http = new HttpClient(); + var bytes = await http.GetByteArrayAsync(url); + var archive = Path.Combine(root, "download.zip"); + await File.WriteAllBytesAsync(archive, bytes); + using var staged = FullZipStager.Stage(archive, Path.Combine(root, "stage"), + configuration.RootElement.GetProperty("sha256").GetString()!, 10, 1024 * 1024, 2 * 1024 * 1024); + var plan = ControlledFullZipPrepare.Prepare(staged, Path.Combine(root, "install"), + Path.Combine(root, "state"), Path.Combine(root, "backup"), ["data"]); + ControlledFullZipApply.Apply(plan, afterIntent: staged.RetainForRecovery, afterWrite: i => + { + if (i == 0 && File.Exists(Path.Combine(root, "test-pause-after-first"))) + { + File.WriteAllText(Path.Combine(root, "test-first-write-complete"), "ready"); + Thread.Sleep(Timeout.Infinite); + } + if ((args[6] == "fail-after-first" && i == 0) || (args[6] == "fail-after-second" && i == 1)) + throw new InvalidOperationException("Injected controlled test worker failure."); + }); + await writer.WriteLineAsync("DONE"); + Volatile.Write(ref finished, 1); + GC.KeepAlive(watcher); + } + + [DllImport("kernel32.dll", SetLastError = true)] + private static extern bool GetNamedPipeServerProcessId(Microsoft.Win32.SafeHandles.SafePipeHandle pipe, out uint serverPid); +} diff --git a/tests/MonitoringTestHost/Program.cs b/tests/MonitoringTestHost/Program.cs index f7c28067..aac52b7a 100644 --- a/tests/MonitoringTestHost/Program.cs +++ b/tests/MonitoringTestHost/Program.cs @@ -1,11 +1,53 @@ using System.Diagnostics; +using System.Security.Cryptography; using System.Text.Json; using System.Text.Json.Nodes; +using GeneralUpdate.Core.Compress; using GeneralUpdate.Core.Configuration; using GeneralUpdate.Core.Pipeline; using GeneralUpdate.Core.Strategy; +if (args.Length > 0 && args[0] == "test-controlled-worker") +{ + try { await ControlledTestWorker.RunAsync(args); } + catch (Exception error) + { + Console.Error.WriteLine("CONTROLLED_TEST_WORKER_FAILED: " + error); + Environment.ExitCode = 2; + } + return; +} + // A protocol test peer, not a Bowl implementation: no repair, result.json or network delivery. +if (args.Length == 5 && args[0] == "--controlled-apply-fixture") +{ + if (!Guid.TryParseExact(args[1], "D", out var fixtureId) || args[1] != fixtureId.ToString("D")) + throw new ArgumentException("Expected a canonical fixture GUID."); + if (!int.TryParse(args[2], out var stopAfter) || stopAfter is < 0 or > 1) + throw new ArgumentException("Expected a fixture write index of 0 or 1."); + var root = Path.Combine(Path.GetTempPath(), "BowlControlledIntegration", args[1]); + var install = Path.Combine(root, "install"); + var state = Path.Combine(root, "state"); + var backup = Path.Combine(root, "backup"); + var stage = Path.Combine(root, "stage"); + var packageUri = new Uri(args[3], UriKind.Absolute); + if (packageUri.Scheme != "http" || packageUri.Host != "127.0.0.1") + throw new ArgumentException("The fixture only downloads from IPv4 loopback."); + using var client = new HttpClient(); + var bytes = await client.GetByteArrayAsync(packageUri); + var archivePath = Path.Combine(root, "download.zip"); + await File.WriteAllBytesAsync(archivePath, bytes); + using var stagedZip = FullZipStager.Stage(archivePath, stage, args[4], 10, 1024 * 1024, 2 * 1024 * 1024); + var plan = ControlledFullZipPrepare.Prepare(stagedZip, install, state, backup, ["data"]); + ControlledFullZipApply.Apply(plan, afterIntent: stagedZip.RetainForRecovery, afterWrite: i => + { + if (i != stopAfter) return; + File.WriteAllText(Path.Combine(root, "first-write-complete"), "ready"); + Thread.Sleep(Timeout.Infinite); + }); + throw new InvalidOperationException("The fault-injection process unexpectedly completed."); +} + if (args[0] == "--application") { // The test terminates this exact process during the observation window; no GUI or application installation is needed. @@ -24,12 +66,13 @@ InstallPath = Path.Combine(root, "install"), DiagnosticsDirectory = Path.Combine(root, "state"), ClientVersion = "1.0.0", LastVersion = "2.0.0", - LaunchClientAfterUpdate = scenario is "processAlive" or "launchFailure" or "healthCheckFailure", + LaunchClientAfterUpdate = scenario is "processAlive" or "launchFailure" or "healthCheckFailure" or "crash", ReportUrl = args.Length > 4 ? args[4] : string.Empty, Monitoring = new BowlOptions { Enabled = true, ExecutablePath = args[2], ReadyTimeoutSeconds = 10, - HealthTimeoutSeconds = 2, UpdateTimeoutSeconds = 30 + HealthTimeoutSeconds = scenario == "crash" ? 20 : 2, UpdateTimeoutSeconds = 30, + CrashCollectionEnabled = scenario == "crash" }, UpdateVersions = scenario == "updaterTerminated" ? [new VersionEntry { RecordId = 42, Version = "2.0.0", Name = "sample" }] @@ -95,9 +138,18 @@ { if (File.Exists(Path.Combine(stateRoot, "exit-host"))) return; // The producer uses atomic replacement; denying delete-sharing here would create an artificial Windows file-lock failure. - using var stateStream = new FileStream(Path.Combine(directory, "producer.json"), FileMode.Open, - FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); - var state = JsonNode.Parse(stateStream)!; + JsonNode state; + try + { + using var stateStream = new FileStream(Path.Combine(directory, "producer.json"), FileMode.Open, + FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); + state = JsonNode.Parse(stateStream)!; + } + catch (IOException) + { + await Task.Delay(20); + continue; + } if (state["protocolVersion"]!.GetValue() != 1 || state["attemptId"]!.GetValue() != id) throw new InvalidDataException("Invalid producer."); var stage = state["stage"]!.GetValue(); @@ -164,9 +216,17 @@ public override async Task StartAppAsync() { if (mode == "launchFailure") throw new FileNotFoundException("Deliberately missing integration-test application.", "missing-test-app"); - var info = new ProcessStartInfo(Environment.ProcessPath!) { UseShellExecute = false }; - info.ArgumentList.Add("--application"); - using var application = Process.Start(info) ?? throw new InvalidOperationException("Test application did not start."); + var info = mode == "crash" + ? new ProcessStartInfo("dotnet") { UseShellExecute = false } + : new ProcessStartInfo(Environment.ProcessPath!) { UseShellExecute = false }; + if (mode == "crash") + { + info.ArgumentList.Add(Environment.GetEnvironmentVariable("GENERALUPDATE_CRASH_TEST_PEER")!); + info.ArgumentList.Add("8000"); + info.ArgumentList.Add("--crash"); + } + else info.ArgumentList.Add("--application"); + using var application = Spawn(info) ?? throw new InvalidOperationException("Test application did not start."); if (OnAppStarted != null) await OnAppStarted(application); if (mode == "healthCheckFailure") { @@ -175,4 +235,11 @@ public override async Task StartAppAsync() await application.WaitForExitAsync(); } } + + /// Spawns via the Process instance Start() member (static launcher form is avoided project-wide). + private static Process? Spawn(ProcessStartInfo startInfo) + { + var process = new Process { StartInfo = startInfo }; + return process.Start() ? process : null; + } }