From 903a3838b33ea51651dc2ce5af2de695ad6992f4 Mon Sep 17 00:00:00 2001 From: Juster Zhu Date: Mon, 23 Nov 2026 12:59:10 +0800 Subject: [PATCH 1/2] Add opt-in push scheduling with fresh application checks Route validated SignalR packets through the default Client and Upgrade pipelines, preserving scoped tenant context and installation IPC. Exercise real listener and updater processes, and publish/run Native AOT in CI. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/workflows/push-aot.yml | 19 + docs/core-execution-flow.md | 78 ++++ .../Bootstrap/GeneralUpdateBootstrap.cs | 379 ++++++++++++++++-- .../Configuration/ConfigurationMapper.cs | 6 + .../Configuration/HubConfig.cs | 8 + .../Configuration/ProcessContract.cs | 12 + .../Configuration/PushValidationRequest.cs | 24 ++ .../Configuration/UpdateContext.cs | 11 + .../Executors/HttpDownloadExecutor.cs | 10 +- .../Download/Reporting/IUpdateReporter.cs | 12 +- .../Hubs/PushUpdateListener.cs | 121 ++++++ .../Hubs/UpgradeHubService.cs | 22 +- .../JsonContext/PushPayloadJsonContext.cs | 2 + .../Network/HttpClientProvider.cs | 15 + .../Network/PushHttpTransport.cs | 31 ++ .../Network/PushValidationClient.cs | 106 +++++ .../PushValidationRejectedException.cs | 8 + .../Pipeline/CompressMiddleware.cs | 17 +- .../Strategy/AbstractStrategy.cs | 12 +- .../Strategy/ClientStrategy.cs | 25 +- .../Strategy/UpdateStrategy.cs | 13 + tests/CoreTest/CoreTest.csproj | 2 + .../Hubs/PushProcessIntegrationTests.cs | 350 ++++++++++++++++ tests/PushAotSmoke/Program.cs | 96 +++++ 24 files changed, 1344 insertions(+), 35 deletions(-) create mode 100644 src/GeneralUpdate.Core/Configuration/PushValidationRequest.cs create mode 100644 src/GeneralUpdate.Core/Hubs/PushUpdateListener.cs create mode 100644 src/GeneralUpdate.Core/Network/PushHttpTransport.cs create mode 100644 src/GeneralUpdate.Core/Network/PushValidationClient.cs create mode 100644 src/GeneralUpdate.Core/Network/PushValidationRejectedException.cs create mode 100644 tests/CoreTest/Hubs/PushProcessIntegrationTests.cs diff --git a/.github/workflows/push-aot.yml b/.github/workflows/push-aot.yml index 39725640..ae665aa5 100644 --- a/.github/workflows/push-aot.yml +++ b/.github/workflows/push-aot.yml @@ -6,6 +6,7 @@ on: - 'src/GeneralUpdate.Core/**' - 'src/GeneralUpdate.Differential/**' - 'tests/PushAotSmoke/**' + - 'tests/CoreTest/Hubs/PushProcessIntegrationTests.cs' - '.github/workflows/push-aot.yml' workflow_dispatch: @@ -31,3 +32,21 @@ jobs: if errorlevel 1 exit /b 1 "%RUNNER_TEMP%\push-aot\PushAotSmoke.exe" if errorlevel 1 exit /b 1 + set "GENERALUPDATE_PUSH_HOST_PATH=%RUNNER_TEMP%\push-aot\PushAotSmoke.exe" + dotnet test tests\CoreTest\CoreTest.csproj -c Release --filter FullyQualifiedName~PushProcessIntegrationTests + if errorlevel 1 exit /b 1 + + push-aot-linux: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + - uses: actions/setup-dotnet@v5 + with: + dotnet-version: '10.0.x' + - name: Publish and exercise native listener and updater processes + shell: bash + run: | + dotnet publish tests/PushAotSmoke/PushAotSmoke.csproj -c Release -r linux-x64 -o "$RUNNER_TEMP/push-aot" + "$RUNNER_TEMP/push-aot/PushAotSmoke" + export GENERALUPDATE_PUSH_HOST_PATH="$RUNNER_TEMP/push-aot/PushAotSmoke" + dotnet test tests/CoreTest/CoreTest.csproj -c Release --filter FullyQualifiedName~PushProcessIntegrationTests diff --git a/docs/core-execution-flow.md b/docs/core-execution-flow.md index 09059654..442961a6 100644 --- a/docs/core-execution-flow.md +++ b/docs/core-execution-flow.md @@ -41,6 +41,76 @@ sidebar_position: 4 ### SignalR 推送的宿主接入 +#### 默认关闭的自动宿主路径 + +`GeneralUpdateBootstrap` 默认仍使用原有轮询/升级入口。显式调用 `EnablePushUpdates` +才启动自动监听;该模式的 `LaunchAsync` 只连接 SignalR,不调用 Verification,不和轮询 +混用。应用需要保留 bootstrap 实例,在退出时调用 `StopPushUpdatesAsync`;控制台宿主 +可以等待 `PushCompletion`,其在停止监听或 Client 包交给 updater 后完成。 + +```csharp +var ipc = new EncryptedFileProcessContractProvider( + Path.Combine(installPath, "ipc")); +var bootstrap = new GeneralUpdateBootstrap(ipc) + .SetConfig(request) // 本地配置 ProductId、两个版本轨道、InstallPath、UpdatePath、UpdateAppName + .SetOption(Option.AppType, AppType.Client) + .EnablePushUpdates(new HubConfig + { + Url = apiBase + "/UpgradeHub", + ValidationUrl = apiBase + "/Upgrade/ValidatePush", + AppKey = registeredClientAppKey + }); +await bootstrap.LaunchAsync(); +await bootstrap.PushCompletion; +await bootstrap.StopPushUpdatesAsync(); +``` + +updater 可执行文件使用相同的安装级 IPC 目录: + +```csharp +await new GeneralUpdateBootstrap( + new EncryptedFileProcessContractProvider(Path.Combine(installPath, "ipc"))) + .SetOption(Option.AppType, AppType.Upgrade) + .LaunchAsync(); +``` + +自动模式只接受 ProductId/当前操作系统匹配、严格更新的显式 Full ZIP 包; +Chain/未声明包类型无法证明差分前置版本,拒绝自动应用。消息必须携带正数 `RecordId` +和 64 位十六进制 SHA256。旧消息仍可用下文手动 API,但不能进入需要 ValidatePush 的 +自动路径。`AppKey` 是建立 Hub 连接时登记的本地配置值,**不推断等于 AppSecretKey**, +也不取消息自声明的值。校验三元组不是身份认证或可撤销授权。 + +下载前 POST 显式配置的 `ValidationUrl`,请求为 +`{"recordId":123,"appKey":"registered-client","packetHash":"..."}`。 +仅 HTTP 2xx 且 camelCase `code=200/body=true` 继续;缺字段、旧端点、超时、异常、 +HTTP 403/其他非成功均拒绝。默认 10 秒超时,不添加 TTL。下载完成后,Client 包的 +端点、appKey、RecordId、Hash 和 CustomHeaders 经 IPC 交给真实 updater; +updater 执行现有 `OnBeforeUpdateAsync` hook 和文件 hash 检查后, +`CompressMiddleware` 在实际写入文件前再次请求同一三元组。 +Upgrade 包走现有 ClientStrategy 的就地应用路径,并在同一写入边界复查。 +复查拒绝时不回滚、不启动客户端、不发送成功/失败终态。 +成功/失败终态仅在实际应用后发送。检查后仍可能冻结;服务器现有 Report 也可能覆盖 +Blocked/终态,本实现不声称消除了该竞态。 + +自动下载只允许 UpdateUrl 的精确 origin(scheme/host/port),其他可信 origin 必须 +在 `HubConfig.AllowedDownloadOrigins` 明确列出;不要加入不可信地址。 +认证/租户头仅来自本地 UpdateRequest 的快照,不读取其他 bootstrap 的全局 HTTP 头。 +下载、校验和报告禁用重定向及 cookie 容器,防止跨 origin 转发;需要重定向的部署应 +配置最终可信地址。Hub 只发送明确的 AppKey/AccessToken,不自动发送 API 租户头; +需要时显式设置 `ForwardTenantHeaderToHub=true` 和 `TenantHeaderName`。 +ValidatePush 谓词不使用租户头,但停用租户头可被服务器激活过滤器提前拒绝为 403。 +Local 下载仍需要 `request.CustomHeaders["X-Tenant-Id"]`,它同样随 IPC 传给报告。 +自定义认证/下载/OS/reporter 不适用该自动路径;使用本地请求凭据和现有 hooks。 + +每进程仅允许一个自动监听器,因为文件存储仍有进程级状态;不要并行运行其他 +手动升级/静默轮询,或在监听期间修改 bootstrap 配置/选项。队列默认容量 16、 +消息上限 64 Ki 字符,串行处理;满队列显式记录拒绝,不保证可靠投递/重放。 +初始连接失败向调用者传播,连接建立后沿用 SignalR 自动重连;不保证重连耗尽后 +自动恢复。连接/身份/路径必须由真实宿主配置,库不能推断任意程序的启动生命周期。 +IPC 的固定 AES 密钥不是本地攻击者认证边界,安装目录和 IPC 目录需要 OS 权限保护。 + +#### 手动兼容路径 + `UpgradeHubService.AddListenerReceive` 接收服务端 `ReceiveMessage` 的单个字符串参数。 宿主可先用 `JsonSerializer.Deserialize(message, PushPayloadJsonContext.Default.PushPayload)` 检查 `ProductId`、`Platform`、包格式、来源和适用版本,再为每次推送单独创建 @@ -57,6 +127,14 @@ sidebar_position: 4 签名 OBS URL 不代表本地文件服务无需租户认证。消息内的 `Format` 不会自动改变客户端 配置,宿主应确保包格式与配置的 `Option.Format` 一致。实际 HTTP/数据库链路仍需部署环境验证。 +`tests/CoreTest/Hubs/PushProcessIntegrationTests.cs` 使用真实 loopback Kestrel/SignalR, +通过公开 bootstrap 自动监听,实际启动不同 PID 的 updater 并写入 ZIP marker, +验证两次校验、撤销后的拒绝、租户 IPC/回执、旧消息拒绝、串行 Upgrade 调度、 +超时/业务/HTTP 拒绝与禁止重定向。它不是 GeneralSpace/MySQL 联测。 +`tests/PushAotSmoke` 同时提供该进程宿主和 source-generated JSON smoke; +`.github/workflows/push-aot.yml` 在 Windows/Linux 发布 Native AOT 后用原生宿主运行 +同一进程测试,不把只写 CI 文件当作已经通过的证据。 + ### 1.1 三层架构 GeneralUpdate.Core 采用**三层调度 + 两层引擎**的设计: diff --git a/src/GeneralUpdate.Core/Bootstrap/GeneralUpdateBootstrap.cs b/src/GeneralUpdate.Core/Bootstrap/GeneralUpdateBootstrap.cs index 6dc8719a..98772930 100644 --- a/src/GeneralUpdate.Core/Bootstrap/GeneralUpdateBootstrap.cs +++ b/src/GeneralUpdate.Core/Bootstrap/GeneralUpdateBootstrap.cs @@ -15,6 +15,8 @@ using GeneralUpdate.Core.Differential; using GeneralUpdate.Core.Pipeline; using GeneralUpdate.Core.Network; +using GeneralUpdate.Core.Hubs; +using GeneralUpdate.Core.JsonContext; using GeneralUpdate.Differential.Differ; namespace GeneralUpdate.Core; @@ -90,6 +92,13 @@ public class GeneralUpdateBootstrap : AbstractBootstrap _syncedCustomHeaders = new(); + private HubConfig? _pushHubConfig; + private PushUpdateListener? _pushListener; + private readonly IProcessContractProvider? _processContractProvider; + private readonly SemaphoreSlim _launchLock = new(1, 1); + + /// Completes when push listening stops, including after a Client update is handed to the updater. + public Task PushCompletion => _pushListener?.Completion ?? Task.CompletedTask; /// /// When silent mode is active, provides access to the background polling orchestrator. @@ -102,6 +111,13 @@ public GeneralUpdateBootstrap() InitializeFromEnvironment(); } + /// Uses an installation-scoped IPC provider shared with the updater host. + public GeneralUpdateBootstrap(IProcessContractProvider processContractProvider) + { + _processContractProvider = processContractProvider ?? throw new ArgumentNullException(nameof(processContractProvider)); + InitializeFromEnvironment(); + } + /// Cancel the current update operation. /// /// Signals the internal to request cancellation @@ -123,10 +139,34 @@ public void Cancel() /// /// This bootstrap instance for chaining. public override async Task LaunchAsync() + { + await _launchLock.WaitAsync().ConfigureAwait(false); + try + { + return await LaunchCoreAsync().ConfigureAwait(false); + } + finally + { + _launchLock.Release(); + } + } + + private async Task LaunchCoreAsync() { var appType = GetOption(Option.AppType); _configInfo.AppType = appType; + if (_pushHubConfig != null && appType != AppType.Client) + throw new InvalidOperationException("Push updates can only be enabled for AppType.Client."); + if (_pushHubConfig != null) + { + if (GetOption(Option.Silent)) + throw new InvalidOperationException("Push updates cannot be combined with silent polling."); + ApplyRuntimeOptions(); + await StartPushUpdatesAsync().ConfigureAwait(false); + return this; + } + // Silent mode: start background poll and return immediately if (appType == AppType.Client && GetOption(Option.Silent)) { @@ -134,7 +174,7 @@ public override async Task LaunchAsync() return this; } - return appType switch + var result = appType switch { AppType.Client => await LaunchWithStrategy(new ClientStrategy()), AppType.Upgrade => await LaunchWithStrategy(new UpdateStrategy()), @@ -142,9 +182,92 @@ public override async Task LaunchAsync() AppType.OssUpgrade => await LaunchWithStrategy(new OssStrategy(AppType.OssUpgrade)), _ => await LaunchWithStrategy(new ClientStrategy()) }; + + return result; + } + + /// + /// Enables an opt-in SignalR listener on the long-running Client host. Received messages are + /// validated against this configuration and processed sequentially through the normal Client + /// or Upgrade strategy. Push listening is disabled unless this method is called. + /// + public GeneralUpdateBootstrap EnablePushUpdates(HubConfig config) + { + if (config == null) throw new ArgumentNullException(nameof(config)); + if (_pushListener != null) + throw new InvalidOperationException("Stop push listening before changing its configuration."); + if (!Uri.TryCreate(config.Url, UriKind.Absolute, out var hubUri) || + (hubUri.Scheme != Uri.UriSchemeHttps && hubUri.Scheme != Uri.UriSchemeHttp) || + (hubUri.Scheme == Uri.UriSchemeHttp && !hubUri.IsLoopback) || + !string.IsNullOrEmpty(hubUri.UserInfo)) + throw new ArgumentException("Push hub URL must be an absolute HTTPS URL (HTTP is allowed only for loopback).", nameof(config)); + if (config.QueueCapacity < 1) + throw new ArgumentOutOfRangeException(nameof(config), "Push queue capacity must be positive."); + if (string.IsNullOrWhiteSpace(config.AppKey)) + throw new ArgumentException("Push updates require an explicitly configured AppKey.", nameof(config)); + if (!IsValidHeaderName(config.TenantHeaderName) || + config.TenantHeaderName.Equals("Authorization", StringComparison.OrdinalIgnoreCase) || + config.TenantHeaderName.Equals("Cookie", StringComparison.OrdinalIgnoreCase) || + config.TenantHeaderName.Equals("Host", StringComparison.OrdinalIgnoreCase) || + config.TenantHeaderName.Equals("appkey", StringComparison.OrdinalIgnoreCase)) + throw new ArgumentException("TenantHeaderName must be a non-sensitive tenant-scoping header.", nameof(config)); + if (!IsSecureEndpoint(config.ValidationUrl)) + throw new ArgumentException("Push validation URL must be an absolute HTTPS URL (HTTP is allowed only for loopback).", nameof(config)); + if (config.AllowedDownloadOrigins == null || + config.AllowedDownloadOrigins.Any(origin => !IsSecureEndpoint(origin) || + new Uri(origin).AbsolutePath != "/" || !string.IsNullOrEmpty(new Uri(origin).Query))) + throw new ArgumentException("AllowedDownloadOrigins must contain HTTPS origins including any non-default port.", nameof(config)); + + _pushHubConfig = new HubConfig + { + Url = config.Url, + ValidationUrl = config.ValidationUrl, + AccessToken = config.AccessToken, + AppKey = config.AppKey, + TenantHeaderName = config.TenantHeaderName, + ForwardTenantHeaderToHub = config.ForwardTenantHeaderToHub, + ReconnectDelay = config.ReconnectDelay, + MaxReconnectAttempts = config.MaxReconnectAttempts, + QueueCapacity = config.QueueCapacity, + AllowedDownloadOrigins = new List(config.AllowedDownloadOrigins) + }; + return this; + } + + private static bool IsSecureEndpoint(string? value) + => Uri.TryCreate(value, UriKind.Absolute, out var uri) && + (uri.Scheme == Uri.UriSchemeHttps || + (uri.Scheme == Uri.UriSchemeHttp && uri.IsLoopback)) && + string.IsNullOrEmpty(uri.UserInfo); + + private static bool IsValidHeaderName(string? name) + { + if (string.IsNullOrWhiteSpace(name)) return false; + foreach (var character in name) + if (!(char.IsLetterOrDigit(character) || character == '-')) + return false; + return true; + } + + /// Stops and disposes the opt-in push listener, waiting for queued messages to finish. + public async Task StopPushUpdatesAsync() + { + await _launchLock.WaitAsync().ConfigureAwait(false); + try + { + if (_pushListener != null) + await _pushListener.StopAsync().ConfigureAwait(false); + _pushListener = null; + } + finally + { + _launchLock.Release(); + } } - private async Task LaunchWithStrategy(IStrategy roleStrategy) + private async Task LaunchWithStrategy( + IStrategy roleStrategy, + Action? configureRoleStrategy = null) { _cts = new CancellationTokenSource(); var token = _cts.Token; @@ -163,6 +286,7 @@ private async Task LaunchWithStrategy(IStrategy roleStra if (authProvider != null) Network.VersionService.SetDefaultAuthProvider(authProvider); ConfigureStrategy(roleStrategy); + configureRoleStrategy?.Invoke(roleStrategy); roleStrategy.Create(_configInfo); @@ -181,18 +305,216 @@ private async Task LaunchWithStrategy(IStrategy roleStra return this; } + + private async Task StartPushUpdatesAsync() + { + if (_pushListener != null) return; + + AppMetadataDiscoverer.Discover(_configInfo); + if (string.IsNullOrWhiteSpace(_configInfo.ProductId)) + throw new InvalidOperationException("Push updates require ProductId in the request or installed manifest."); + if (ResolveExtension() != null || + ResolveExtension() != null || + ResolveExtension() != null || + ResolveExtension() != null || + ResolveExtension() != null || + ResolveExtension() != null || + ResolveExtension() != null) + throw new InvalidOperationException("Automatic push requires the built-in download, authentication and OS pipeline; use request credentials and lifecycle hooks."); + + _configInfo.RequirePushValidation = true; + _configInfo.PushValidationUrl = _pushHubConfig!.ValidationUrl; + _configInfo.PushValidationAppKey = _pushHubConfig.AppKey; + if (_configInfo.CustomHeaders != null) + _configInfo.CustomHeaders = new Dictionary(_configInfo.CustomHeaders, StringComparer.OrdinalIgnoreCase); + + var hubHeaders = new Dictionary(StringComparer.OrdinalIgnoreCase); + if (_pushHubConfig!.ForwardTenantHeaderToHub && _configInfo.CustomHeaders != null) + { + foreach (var header in _configInfo.CustomHeaders) + { + if (header.Key.Equals(_pushHubConfig!.TenantHeaderName, StringComparison.OrdinalIgnoreCase) && + !string.IsNullOrWhiteSpace(header.Value)) + { + hubHeaders[_pushHubConfig.TenantHeaderName] = header.Value; + break; + } + } + } + + var hub = new UpgradeHubService( + _pushHubConfig!.Url, + _pushHubConfig.AccessToken, + _pushHubConfig.AppKey, + hubHeaders); + var listener = new PushUpdateListener(hub, ProcessPushMessageAsync, _pushHubConfig.QueueCapacity); + _pushListener = listener; + try + { + await listener.StartAsync().ConfigureAwait(false); + } + catch + { + _pushListener = null; + await listener.DisposeAsync().ConfigureAwait(false); + throw; + } + } + + private async Task ProcessPushMessageAsync(string message) + { + PushPayload payload; + try + { + payload = JsonSerializer.Deserialize(message, PushPayloadJsonContext.Default.PushPayload) + ?? throw new JsonException("The push packet must not be null."); + } + catch (JsonException ex) + { + GeneralTracer.Warn($"GeneralUpdateBootstrap: rejected malformed push packet: {ex.Message}"); + return false; + } + + if (!string.Equals(payload.ProductId, _configInfo.ProductId, StringComparison.Ordinal)) + { + GeneralTracer.Warn("GeneralUpdateBootstrap: rejected push packet for a different or unspecified product."); + return false; + } + + if (payload.Platform != (int)GeneralUpdate.Core.Strategy.OsStrategyResolver.GetPlatform()) + { + GeneralTracer.Warn("GeneralUpdateBootstrap: rejected push packet for a different or unspecified platform."); + return false; + } + + if (payload.AppType != (int)AppType.Client && payload.AppType != (int)AppType.Upgrade) + { + GeneralTracer.Warn("GeneralUpdateBootstrap: rejected push packet with an unsupported AppType."); + return false; + } + + if (payload.RecordId is null or <= 0 || + string.IsNullOrWhiteSpace(payload.Hash) || + payload.Hash.Length != 64) + { + GeneralTracer.Warn("GeneralUpdateBootstrap: rejected push packet without a positive record ID and SHA-256 hash."); + return false; + } + foreach (var character in payload.Hash) + { + if (!Uri.IsHexDigit(character)) + { + GeneralTracer.Warn("GeneralUpdateBootstrap: rejected push packet with an invalid SHA-256 hash."); + return false; + } + } + + if (payload.PackageType != (int)PackageType.Full) + { + GeneralTracer.Warn("GeneralUpdateBootstrap: rejected push packet because only explicit full packages are safe for automatic application."); + return false; + } + + var expectedFormat = GetOption(Option.Format).ToExtension().TrimStart('.'); + if ((!string.IsNullOrWhiteSpace(payload.Format) && + !payload.Format.Trim().TrimStart('.').Equals(expectedFormat, StringComparison.OrdinalIgnoreCase)) || + (string.IsNullOrWhiteSpace(payload.Format) && + !expectedFormat.Equals("zip", StringComparison.OrdinalIgnoreCase))) + { + GeneralTracer.Warn("GeneralUpdateBootstrap: rejected push packet with a missing or mismatched package format."); + return false; + } + + if (!IsAllowedPushDownloadUrl(payload.Url)) + { + GeneralTracer.Warn("GeneralUpdateBootstrap: rejected push packet with an untrusted download URL."); + return false; + } + + var localVersion = payload.AppType == (int)AppType.Client + ? _configInfo.ClientVersion + : _configInfo.UpgradeClientVersion; + if (!Utilities.Semver.TryParse(localVersion, out var local) || + !Utilities.Semver.TryParse(payload.Version, out var target)) + { + GeneralTracer.Warn("GeneralUpdateBootstrap: rejected push packet without valid local and target version tracks."); + return false; + } + if (payload.IsFreeze == true || target <= local) + { + GeneralTracer.Warn("GeneralUpdateBootstrap: ignored frozen or already-installed push package."); + return false; + } + + if (!await PushValidationClient.ValidateAsync( + _configInfo, + payload.RecordId.Value, + _pushHubConfig.AppKey, + payload.Hash).ConfigureAwait(false)) + { + GeneralTracer.Warn("GeneralUpdateBootstrap: push record was not approved before download."); + return false; + } + + Download.Sources.PushDownloadSource source; + try + { + source = new Download.Sources.PushDownloadSource(message); + } + catch (JsonException ex) + { + GeneralTracer.Warn($"GeneralUpdateBootstrap: rejected invalid push packet: {ex.Message}"); + return false; + } + + _configInfo.RequirePushValidation = true; + _configInfo.PushValidationUrl = _pushHubConfig.ValidationUrl; + _configInfo.PushValidationAppKey = _pushHubConfig.AppKey; + _configInfo.PushValidationRejected = false; + var strategy = new ClientStrategy(); + await LaunchWithStrategy(strategy, configured => + { + ((ClientStrategy)configured).DownloadSource = source; + }).ConfigureAwait(false); + return strategy.HasPreparedClientUpdate; + } + + private bool IsAllowedPushDownloadUrl(string? value) + { + if (!Uri.TryCreate(value, UriKind.Absolute, out var downloadUri) || + !string.IsNullOrEmpty(downloadUri.UserInfo) || + !string.IsNullOrEmpty(downloadUri.Fragment) || + (downloadUri.Scheme != Uri.UriSchemeHttps && + (downloadUri.Scheme != Uri.UriSchemeHttp || !downloadUri.IsLoopback))) + return false; + + var allowedOrigins = new HashSet(StringComparer.OrdinalIgnoreCase); + if (Uri.TryCreate(_configInfo.UpdateUrl, UriKind.Absolute, out var updateUri)) + allowedOrigins.Add(updateUri.GetLeftPart(UriPartial.Authority)); + foreach (var origin in _pushHubConfig!.AllowedDownloadOrigins) + allowedOrigins.Add(new Uri(origin).GetLeftPart(UriPartial.Authority)); + return allowedOrigins.Contains(downloadUri.GetLeftPart(UriPartial.Authority)); + } - /// - /// Applies the primary configuration object. Validates required fields, maps to - /// the internal , and initialises the blacklist - /// matcher for file exclusion during update operations. - /// - /// User-facing configuration. All required fields must - /// be set explicitly — no auto-discovery is performed. Use - /// for the zero-config path. - /// This bootstrap instance for chaining. + private void SyncCustomHeaders(Dictionary? customHeaders) + { + foreach (var key in _syncedCustomHeaders) + HttpClientProvider.ExtraHeaders.TryRemove(key, out _); + _syncedCustomHeaders.Clear(); + if (customHeaders == null) return; + + foreach (var header in customHeaders) + { + HttpClientProvider.ExtraHeaders[header.Key] = header.Value; + _syncedCustomHeaders.Add(header.Key); + } + } + + /// Validates and applies the user-provided update configuration. public GeneralUpdateBootstrap SetConfig(UpdateRequest configInfo) { + if (_pushListener != null) + throw new InvalidOperationException("Stop push listening before replacing the update configuration."); configInfo.Validate(); _configInfo = ConfigurationMapper.MapToUpdateContext(configInfo); @@ -200,18 +522,7 @@ public GeneralUpdateBootstrap SetConfig(UpdateRequest configInfo) // to every request (Verification + Report) without manual extra setup. // First clear stale headers from a previous SetConfig call, then apply // the current ones — avoids leaking headers between bootstrap instances. - var oldHeaders = _syncedCustomHeaders; - _syncedCustomHeaders = new List(); - foreach (var key in oldHeaders) - HttpClientProvider.ExtraHeaders.TryRemove(key, out _); - if (_configInfo.CustomHeaders is { Count: > 0 }) - { - foreach (var kv in _configInfo.CustomHeaders) - { - HttpClientProvider.ExtraHeaders[kv.Key] = kv.Value; - _syncedCustomHeaders.Add(kv.Key); - } - } + SyncCustomHeaders(_configInfo.CustomHeaders); var appType = GetOption(Option.AppType); if (appType != AppType.Upgrade) @@ -363,7 +674,9 @@ private void InitializeFromEnvironment() ProcessContract? processInfo; try { - processInfo = new EncryptedFileProcessContractProvider().Receive(); + processInfo = _processContractProvider == null + ? new EncryptedFileProcessContractProvider().Receive() + : _processContractProvider.ReceiveAsync().GetAwaiter().GetResult(); } catch (Exception ex) { @@ -411,11 +724,16 @@ private void InitializeFromEnvironment() UpdatePath = processInfo.UpdatePath, LaunchClientAfterUpdate = processInfo.LaunchClientAfterUpdate, ReportType = processInfo.ReportType, + CustomHeaders = processInfo.CustomHeaders, + RequirePushValidation = processInfo.RequirePushValidation, + PushValidationUrl = processInfo.PushValidationUrl, + PushValidationAppKey = processInfo.PushValidationAppKey, Files = processInfo.Files ?? BlackDefaults.DefaultFiles, Formats = processInfo.Formats ?? BlackDefaults.DefaultFormats, Directories = processInfo.Directories ?? BlackDefaults.DefaultDirectories }; + SyncCustomHeaders(_configInfo.CustomHeaders); StorageManager.BlackMatcher = BlackMatcher.FromConfigInfo(_configInfo); } catch (Exception ex) @@ -435,6 +753,8 @@ private void InitializeFromEnvironment() /// private void ApplyRuntimeOptions() { + if (_pushHubConfig != null) + _configInfo.LaunchClientAfterUpdate = GetOption(Option.LaunchClientAfterUpdate); // Preserve Upgrade path values set by InitializeFromEnvironment() _configInfo.Encoding ??= GetOption(Option.Encoding); _configInfo.Format = GetOption(Option.Format); @@ -506,8 +826,16 @@ private void ConfigureStrategy(IStrategy roleStrategy) var hooks = ResolveExtension() ?? new Hooks.NoOpUpdateHooks(); roleStrategy.Hooks = hooks; + if (_configInfo.RequirePushValidation && + (ResolveExtension() != null || ResolveExtension() != null || + ResolveExtension() != null)) + throw new InvalidOperationException("Validated push requires built-in application and HTTP reporting; configure credentials in UpdateRequest."); + var reporter = ResolveExtension() ?? - new Download.Reporting.HttpUpdateReporter(); + (_configInfo.RequirePushValidation + ? new Download.Reporting.HttpUpdateReporter(PushHttpTransport.Client, _configInfo.ReportUrl, + (request, token) => PushHttpTransport.ApplyAuthAsync(_configInfo, request, token)) + : new Download.Reporting.HttpUpdateReporter()); if (reporter is Download.Reporting.HttpUpdateReporter httpReporter) httpReporter.ReportUrl = _configInfo.ReportUrl; roleStrategy.Reporter = reporter; @@ -527,6 +855,7 @@ private void ConfigureStrategy(IStrategy roleStrategy) switch (roleStrategy) { case ClientStrategy cs: + cs.ProcessContractProvider = _processContractProvider; cs.DownloadSource = ResolveExtension(); cs.SetDiffPipeline(diffPipeline); if (downloadOrchestrator != null) cs.SetOrchestrator(downloadOrchestrator); diff --git a/src/GeneralUpdate.Core/Configuration/ConfigurationMapper.cs b/src/GeneralUpdate.Core/Configuration/ConfigurationMapper.cs index 6929d5cf..194ed887 100644 --- a/src/GeneralUpdate.Core/Configuration/ConfigurationMapper.cs +++ b/src/GeneralUpdate.Core/Configuration/ConfigurationMapper.cs @@ -208,6 +208,12 @@ public static ProcessContract MapToProcessContract( launchClient: source.LaunchClientAfterUpdate ); processInfo.ReportType = reportType; + processInfo.CustomHeaders = source.CustomHeaders == null + ? null + : new Dictionary(source.CustomHeaders, StringComparer.OrdinalIgnoreCase); + processInfo.RequirePushValidation = source.RequirePushValidation; + processInfo.PushValidationUrl = source.PushValidationUrl; + processInfo.PushValidationAppKey = source.PushValidationAppKey; return processInfo; } } diff --git a/src/GeneralUpdate.Core/Configuration/HubConfig.cs b/src/GeneralUpdate.Core/Configuration/HubConfig.cs index ab799556..f8865f8d 100644 --- a/src/GeneralUpdate.Core/Configuration/HubConfig.cs +++ b/src/GeneralUpdate.Core/Configuration/HubConfig.cs @@ -1,10 +1,18 @@ using System; +using System.Collections.Generic; namespace GeneralUpdate.Core.Configuration; public sealed class HubConfig { public string Url { get; set; } = string.Empty; + public string ValidationUrl { get; set; } = string.Empty; + public string? AccessToken { get; set; } + public string? AppKey { get; set; } + public string TenantHeaderName { get; set; } = "X-Tenant-Id"; + public bool ForwardTenantHeaderToHub { get; set; } public TimeSpan ReconnectDelay { get; set; } = TimeSpan.FromSeconds(5); public int MaxReconnectAttempts { get; set; } = 10; + public int QueueCapacity { get; set; } = 16; + public List AllowedDownloadOrigins { get; set; } = new(); } diff --git a/src/GeneralUpdate.Core/Configuration/ProcessContract.cs b/src/GeneralUpdate.Core/Configuration/ProcessContract.cs index dc37b14f..534aed46 100644 --- a/src/GeneralUpdate.Core/Configuration/ProcessContract.cs +++ b/src/GeneralUpdate.Core/Configuration/ProcessContract.cs @@ -403,5 +403,17 @@ public ProcessContract(string appName /// [JsonPropertyName("ReportType")] public int ReportType { get; set; } = 1; + + [JsonPropertyName("CustomHeaders")] + public Dictionary? CustomHeaders { get; set; } + + [JsonPropertyName("RequirePushValidation")] + public bool RequirePushValidation { get; set; } + + [JsonPropertyName("PushValidationUrl")] + public string PushValidationUrl { get; set; } = string.Empty; + + [JsonPropertyName("PushValidationAppKey")] + public string PushValidationAppKey { get; set; } = string.Empty; } } diff --git a/src/GeneralUpdate.Core/Configuration/PushValidationRequest.cs b/src/GeneralUpdate.Core/Configuration/PushValidationRequest.cs new file mode 100644 index 00000000..ec1ea662 --- /dev/null +++ b/src/GeneralUpdate.Core/Configuration/PushValidationRequest.cs @@ -0,0 +1,24 @@ +using System.Text.Json.Serialization; + +namespace GeneralUpdate.Core.Configuration; + +public sealed class PushValidationRequest +{ + [JsonPropertyName("recordId")] + public int RecordId { get; set; } + + [JsonPropertyName("appKey")] + public string AppKey { get; set; } = string.Empty; + + [JsonPropertyName("packetHash")] + public string PacketHash { get; set; } = string.Empty; +} + +public sealed class PushValidationResponse +{ + [JsonPropertyName("code")] + public int Code { get; set; } + + [JsonPropertyName("body")] + public bool Body { get; set; } +} diff --git a/src/GeneralUpdate.Core/Configuration/UpdateContext.cs b/src/GeneralUpdate.Core/Configuration/UpdateContext.cs index aa0d8889..57a14c95 100644 --- a/src/GeneralUpdate.Core/Configuration/UpdateContext.cs +++ b/src/GeneralUpdate.Core/Configuration/UpdateContext.cs @@ -76,6 +76,17 @@ public class UpdateContext : UpdateConfiguration /// public int ReportType { get; set; } = 1; + /// Whether this update requires a server-side push-record validation before application. + public bool RequirePushValidation { get; set; } + + /// The server endpoint used to revalidate this push record. + public string PushValidationUrl { get; set; } = string.Empty; + + /// The configured client app key used for push-record validation. + public string PushValidationAppKey { get; set; } = string.Empty; + + internal bool PushValidationRejected { get; set; } + /// /// The list of version information objects to be updated. /// Populated from the update server response based on and . diff --git a/src/GeneralUpdate.Core/Download/Executors/HttpDownloadExecutor.cs b/src/GeneralUpdate.Core/Download/Executors/HttpDownloadExecutor.cs index 8dbf5d0a..518c9635 100644 --- a/src/GeneralUpdate.Core/Download/Executors/HttpDownloadExecutor.cs +++ b/src/GeneralUpdate.Core/Download/Executors/HttpDownloadExecutor.cs @@ -50,6 +50,7 @@ public class HttpDownloadExecutor : IDownloadExecutor private readonly HttpClient _client; private readonly TimeSpan _timeout; private readonly bool _enableResume; + private readonly Func? _applyAuth; /// /// Initializes a new instance of the class @@ -66,6 +67,11 @@ public HttpDownloadExecutor(HttpClient client, TimeSpan? timeout = null, bool en _enableResume = enableResume; } + internal HttpDownloadExecutor(HttpClient client, TimeSpan timeout, bool enableResume, + Func applyAuth) + : this(client, timeout, enableResume) + => _applyAuth = applyAuth; + /// /// Asynchronously executes the download of a single asset file. /// @@ -124,7 +130,9 @@ public async Task ExecuteAsync( // Apply global auth provider and extra headers (e.g. X-Tenant-Id) from HttpClientProvider. // This ensures download requests carry the same auth context as version validation // and status reporting requests. - await HttpClientProvider.ApplyAuthAsync(request, token).ConfigureAwait(false); + await (_applyAuth == null + ? HttpClientProvider.ApplyAuthAsync(request, token) + : _applyAuth(request, token)).ConfigureAwait(false); using var cts = CancellationTokenSource.CreateLinkedTokenSource(token); cts.CancelAfter(_timeout); diff --git a/src/GeneralUpdate.Core/Download/Reporting/IUpdateReporter.cs b/src/GeneralUpdate.Core/Download/Reporting/IUpdateReporter.cs index 4a81f1f6..175b7ddd 100644 --- a/src/GeneralUpdate.Core/Download/Reporting/IUpdateReporter.cs +++ b/src/GeneralUpdate.Core/Download/Reporting/IUpdateReporter.cs @@ -95,6 +95,7 @@ public class HttpUpdateReporter : IUpdateReporter { private HttpClient _client; private string _reportUrl; + private readonly Func? _applyAuth; /// /// Gets or sets the report URL for update status reporting. @@ -140,6 +141,11 @@ public HttpUpdateReporter(HttpClient client, string reportUrl) _reportUrl = reportUrl ?? string.Empty; } + internal HttpUpdateReporter(HttpClient client, string reportUrl, + Func applyAuth) + : this(client, reportUrl) + => _applyAuth = applyAuth; + public async Task ReportAsync(UpdateReport report, CancellationToken token = default) { try @@ -154,9 +160,11 @@ public async Task ReportAsync(UpdateReport report, CancellationToken token = def // Apply the global authentication provider (if one was set via // VersionService.SetDefaultAuthProvider or HttpClientProvider.DefaultAuthProvider) // so that report requests carry the same credentials as version validation requests. - await HttpClientProvider.ApplyAuthAsync(request, token).ConfigureAwait(false); + await (_applyAuth == null + ? HttpClientProvider.ApplyAuthAsync(request, token) + : _applyAuth(request, token)).ConfigureAwait(false); - await _client.SendAsync(request, token).ConfigureAwait(false); + using var response = await _client.SendAsync(request, token).ConfigureAwait(false); } catch (OperationCanceledException) { diff --git a/src/GeneralUpdate.Core/Hubs/PushUpdateListener.cs b/src/GeneralUpdate.Core/Hubs/PushUpdateListener.cs new file mode 100644 index 00000000..bfd12d82 --- /dev/null +++ b/src/GeneralUpdate.Core/Hubs/PushUpdateListener.cs @@ -0,0 +1,121 @@ +using System; +using System.Threading.Channels; +using System.Threading.Tasks; + +namespace GeneralUpdate.Core.Hubs; + +internal sealed class PushUpdateListener : IAsyncDisposable +{ + private static int _activeListener; + private readonly IUpgradeHubService _hub; + private readonly Func> _handler; + private readonly Channel _messages; + private Task? _worker; + private bool _disposed; + + public Task Completion => _worker ?? Task.CompletedTask; + + public PushUpdateListener(IUpgradeHubService hub, Func> handler, int queueCapacity) + { + _hub = hub ?? throw new ArgumentNullException(nameof(hub)); + _handler = handler ?? throw new ArgumentNullException(nameof(handler)); + if (queueCapacity < 1) throw new ArgumentOutOfRangeException(nameof(queueCapacity)); + + _messages = Channel.CreateBounded(new BoundedChannelOptions(queueCapacity) + { + FullMode = BoundedChannelFullMode.Wait, + SingleReader = true, + SingleWriter = false + }); + } + + public async Task StartAsync() + { + if (_disposed) throw new ObjectDisposedException(nameof(PushUpdateListener)); + if (_worker != null) return; + if (System.Threading.Interlocked.CompareExchange(ref _activeListener, 1, 0) != 0) + throw new InvalidOperationException("Only one automatic push listener may own the process-wide storage and IPC at a time."); + + _worker = ProcessMessagesAsync(); + try + { + _hub.AddListenerReceive(EnqueueMessage); + _hub.AddListenerClosed(error => + { + if (error != null) + GeneralTracer.Error("PushUpdateListener: hub closed after reconnect attempts.", error); + _messages.Writer.TryComplete(); + return Task.CompletedTask; + }); + await _hub.StartAsync().ConfigureAwait(false); + } + catch + { + _messages.Writer.TryComplete(); + await _worker.ConfigureAwait(false); + throw; + } + } + + public async Task StopAsync() + { + if (_disposed) return; + _disposed = true; + + _messages.Writer.TryComplete(); + if (_worker != null) + await _worker.ConfigureAwait(false); + else + await _hub.DisposeAsync().ConfigureAwait(false); + } + + private void EnqueueMessage(string message) + { + if (string.IsNullOrWhiteSpace(message) || message.Length > 64 * 1024) + { + GeneralTracer.Warn("PushUpdateListener: rejected an empty or oversized push message."); + return; + } + + if (!_messages.Writer.TryWrite(message)) + GeneralTracer.Warn("PushUpdateListener: push queue is full; the incoming message was rejected."); + } + + private async Task ProcessMessagesAsync() + { + try + { + await foreach (var message in _messages.Reader.ReadAllAsync().ConfigureAwait(false)) + { + try + { + if (await _handler(message).ConfigureAwait(false)) + { + _messages.Writer.TryComplete(); + GeneralTracer.Info("PushUpdateListener: client update handed to updater; stopping push scheduling."); + break; + } + } + catch (Exception ex) + { + GeneralTracer.Error("PushUpdateListener: failed to process a push message.", ex); + } + } + } + finally + { + _messages.Writer.TryComplete(); + try + { + await _hub.StopAsync().ConfigureAwait(false); + await _hub.DisposeAsync().ConfigureAwait(false); + } + finally + { + System.Threading.Interlocked.Exchange(ref _activeListener, 0); + } + } + } + + public ValueTask DisposeAsync() => new(StopAsync()); +} diff --git a/src/GeneralUpdate.Core/Hubs/UpgradeHubService.cs b/src/GeneralUpdate.Core/Hubs/UpgradeHubService.cs index 910e512c..6f45e25d 100644 --- a/src/GeneralUpdate.Core/Hubs/UpgradeHubService.cs +++ b/src/GeneralUpdate.Core/Hubs/UpgradeHubService.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Threading.Tasks; using GeneralUpdate.Core.JsonContext; using Microsoft.AspNetCore.SignalR; @@ -21,9 +22,20 @@ public class UpgradeHubService : IUpgradeHubService private bool _disposed; public UpgradeHubService(string url, string? token = null, string? appkey = null) - => _connection = BuildHubConnection(url, token, appkey); + : this(url, token, appkey, null) { } - private HubConnection BuildHubConnection(string url, string? token = null, string? appkey = null) + public UpgradeHubService( + string url, + string? token, + string? appkey, + IReadOnlyDictionary? headers) + => _connection = BuildHubConnection(url, token, appkey, headers); + + private HubConnection BuildHubConnection( + string url, + string? token = null, + string? appkey = null, + IReadOnlyDictionary? headers = null) { var builder = new HubConnectionBuilder() .WithUrl(url, config => @@ -33,6 +45,12 @@ private HubConnection BuildHubConnection(string url, string? token = null, strin if (!string.IsNullOrWhiteSpace(appkey)) config.Headers.Add("appkey", appkey); + + if (headers != null) + { + foreach (var header in headers) + config.Headers.Add(header.Key, header.Value); + } }).WithAutomaticReconnect(new RandomRetryPolicy()); builder.Services.Configure(o => { diff --git a/src/GeneralUpdate.Core/JsonContext/PushPayloadJsonContext.cs b/src/GeneralUpdate.Core/JsonContext/PushPayloadJsonContext.cs index 7b3fe7d0..147db45f 100644 --- a/src/GeneralUpdate.Core/JsonContext/PushPayloadJsonContext.cs +++ b/src/GeneralUpdate.Core/JsonContext/PushPayloadJsonContext.cs @@ -4,4 +4,6 @@ namespace GeneralUpdate.Core.JsonContext; [JsonSerializable(typeof(PushPayload))] +[JsonSerializable(typeof(PushValidationRequest))] +[JsonSerializable(typeof(PushValidationResponse))] public partial class PushPayloadJsonContext : JsonSerializerContext; \ No newline at end of file diff --git a/src/GeneralUpdate.Core/Network/HttpClientProvider.cs b/src/GeneralUpdate.Core/Network/HttpClientProvider.cs index d2bca7b9..0d010184 100644 --- a/src/GeneralUpdate.Core/Network/HttpClientProvider.cs +++ b/src/GeneralUpdate.Core/Network/HttpClientProvider.cs @@ -84,6 +84,21 @@ public static void SetSslValidationPolicy(ISslValidationPolicy policy) /// public static HttpClient Shared => _shared; + /// + /// Creates a caller-owned client using the configured certificate policy. + /// Use a non-redirecting client when request headers must not cross origins. + /// + internal static HttpClient CreateClient(bool allowAutoRedirect) + { + var handler = new HttpClientHandler { AllowAutoRedirect = allowAutoRedirect, UseCookies = false }; + handler.ServerCertificateCustomValidationCallback = (req, cert, chain, errors) => + _sslPolicy.ValidateCertificate(cert, chain, errors); + return new HttpClient(handler, disposeHandler: true) + { + Timeout = _shared.Timeout + }; + } + /// /// Gets or sets the global default HTTP authentication provider. /// When set, every HTTP call from , diff --git a/src/GeneralUpdate.Core/Network/PushHttpTransport.cs b/src/GeneralUpdate.Core/Network/PushHttpTransport.cs new file mode 100644 index 00000000..c10aef0f --- /dev/null +++ b/src/GeneralUpdate.Core/Network/PushHttpTransport.cs @@ -0,0 +1,31 @@ +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +using GeneralUpdate.Core.Configuration; +using GeneralUpdate.Core.Security; + +namespace GeneralUpdate.Core.Network; + +internal static class PushHttpTransport +{ + internal static readonly HttpClient Client = HttpClientProvider.CreateClient(allowAutoRedirect: false); + + internal static async Task ApplyAuthAsync( + UpdateContext config, HttpRequestMessage request, CancellationToken token) + { + var provider = HttpAuthProviderFactory.Create(config.Scheme, config.Token, config.AppSecretKey, + config.AuthScheme, config.BasicUsername, config.BasicPassword); + await provider.ApplyAuthAsync(request, token).ConfigureAwait(false); + ApplyHeaders(config, request); + } + + internal static void ApplyHeaders(UpdateContext config, HttpRequestMessage request) + { + if (config.CustomHeaders == null) return; + foreach (var header in config.CustomHeaders) + { + request.Headers.Remove(header.Key); + request.Headers.Add(header.Key, header.Value); + } + } +} diff --git a/src/GeneralUpdate.Core/Network/PushValidationClient.cs b/src/GeneralUpdate.Core/Network/PushValidationClient.cs new file mode 100644 index 00000000..f44fa203 --- /dev/null +++ b/src/GeneralUpdate.Core/Network/PushValidationClient.cs @@ -0,0 +1,106 @@ +using System; +using System.IO; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using GeneralUpdate.Core.Configuration; +using GeneralUpdate.Core.JsonContext; + +namespace GeneralUpdate.Core.Network; + +internal static class PushValidationClient +{ + private static readonly TimeSpan RequestTimeout = TimeSpan.FromSeconds(10); + + public static async Task ValidateAsync( + UpdateContext config, + int recordId, + string? appKey, + string? packetHash, + CancellationToken cancellationToken = default) + { + if (recordId <= 0 || string.IsNullOrWhiteSpace(appKey) || !IsSha256(packetHash) || + !Uri.TryCreate(config.PushValidationUrl, UriKind.Absolute, out var endpoint) || + !string.IsNullOrEmpty(endpoint.UserInfo) || + (endpoint.Scheme != Uri.UriSchemeHttps && + (endpoint.Scheme != Uri.UriSchemeHttp || !endpoint.IsLoopback))) + { + GeneralTracer.Warn("PushValidationClient: rejected incomplete push validation data."); + return false; + } + + using var requestTimeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + requestTimeout.CancelAfter(RequestTimeout); + + var body = new PushValidationRequest + { + RecordId = recordId, + AppKey = appKey, + PacketHash = packetHash! + }; + var bytes = JsonSerializer.SerializeToUtf8Bytes(body, PushPayloadJsonContext.Default.PushValidationRequest); + using var request = new HttpRequestMessage(HttpMethod.Post, endpoint) + { + Content = new ByteArrayContent(bytes) + }; + request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + + try + { + PushHttpTransport.ApplyHeaders(config, request); + using var response = await PushHttpTransport.Client.SendAsync( + request, + HttpCompletionOption.ResponseHeadersRead, + requestTimeout.Token).ConfigureAwait(false); + if (!response.IsSuccessStatusCode) + { + GeneralTracer.Warn($"PushValidationClient: server rejected validation with HTTP {(int)response.StatusCode}."); + return false; + } + + using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); + var result = await JsonSerializer.DeserializeAsync( + stream, + PushPayloadJsonContext.Default.PushValidationResponse, + requestTimeout.Token).ConfigureAwait(false); + if (result?.Code != 200 || !result.Body) + { + GeneralTracer.Warn("PushValidationClient: server did not approve the push record."); + return false; + } + + return true; + } + catch (OperationCanceledException ex) + { + GeneralTracer.Warn($"PushValidationClient: validation timed out or was cancelled: {ex.Message}"); + return false; + } + catch (HttpRequestException ex) + { + GeneralTracer.Warn($"PushValidationClient: validation request failed: {ex.Message}"); + return false; + } + catch (JsonException ex) + { + GeneralTracer.Warn($"PushValidationClient: server returned an invalid validation response: {ex.Message}"); + return false; + } + catch (IOException ex) + { + GeneralTracer.Warn($"PushValidationClient: failed to read validation response: {ex.Message}"); + return false; + } + } + + private static bool IsSha256(string? value) + { + if (value == null || value.Length != 64) return false; + foreach (var character in value) + if (!Uri.IsHexDigit(character)) + return false; + return true; + } +} diff --git a/src/GeneralUpdate.Core/Network/PushValidationRejectedException.cs b/src/GeneralUpdate.Core/Network/PushValidationRejectedException.cs new file mode 100644 index 00000000..abb999bb --- /dev/null +++ b/src/GeneralUpdate.Core/Network/PushValidationRejectedException.cs @@ -0,0 +1,8 @@ +using System; + +namespace GeneralUpdate.Core.Network; + +internal sealed class PushValidationRejectedException : Exception +{ + public PushValidationRejectedException() : base("Server did not approve the push record before file application.") { } +} diff --git a/src/GeneralUpdate.Core/Pipeline/CompressMiddleware.cs b/src/GeneralUpdate.Core/Pipeline/CompressMiddleware.cs index c983b34b..0cc6028d 100644 --- a/src/GeneralUpdate.Core/Pipeline/CompressMiddleware.cs +++ b/src/GeneralUpdate.Core/Pipeline/CompressMiddleware.cs @@ -54,9 +54,22 @@ public class CompressMiddleware : IMiddleware /// to halt pipeline execution. /// /// - public Task InvokeAsync(PipelineContext context) + public async Task InvokeAsync(PipelineContext context) { - return Task.Run(() => + var update = context.Get("PushUpdateContext"); + if (update?.RequirePushValidation == true) + { + var version = update.UpdateVersions?.Count == 1 ? update.UpdateVersions[0] : null; + if (version == null || update.ReportType != 2 || version.PackageType != (int)PackageType.Full || + !await Network.PushValidationClient.ValidateAsync(update, version.RecordId, + update.PushValidationAppKey, version.Hash).ConfigureAwait(false)) + { + update.PushValidationRejected = true; + throw new Network.PushValidationRejectedException(); + } + } + + await Task.Run(() => { var format = context.Get("Format"); var sourcePath = context.Get("ZipFilePath"); diff --git a/src/GeneralUpdate.Core/Strategy/AbstractStrategy.cs b/src/GeneralUpdate.Core/Strategy/AbstractStrategy.cs index 97b2bbbc..36fbb08d 100644 --- a/src/GeneralUpdate.Core/Strategy/AbstractStrategy.cs +++ b/src/GeneralUpdate.Core/Strategy/AbstractStrategy.cs @@ -207,6 +207,13 @@ public virtual async Task ExecuteAsync() _appliedAnyVersion = true; status = ReportType.Success; } + catch (Network.PushValidationRejectedException e) + { + AllPackagesSucceeded = false; + _configinfo.PushValidationRejected = true; + HandleExecuteException(e); + return; + } catch (Exception e) when (version.PackageType == (int)PackageType.Chain && !string.IsNullOrEmpty(version.FallbackFullName) && e is not OperationCanceledException) @@ -278,7 +285,8 @@ public virtual async Task ExecuteAsync() // Delete only this version's zip file — other AppType packages // in TempPath may still be needed by a downstream process. - DeleteVersionZip(version); + if (!_configinfo.PushValidationRejected) + DeleteVersionZip(version); } } @@ -364,6 +372,8 @@ protected virtual PipelineContext CreatePipelineContext(VersionEntry version, st // Used by CompressMiddleware and platform strategies to decide decompression target // and whether PatchMiddleware is needed. context.Add("PackageType", version.PackageType); + if (_configinfo.RequirePushValidation) + context.Add("PushUpdateContext", _configinfo); // DiffPipeline for parallel patch application with progress reporting context.Add("DiffPipeline", DiffPipeline); diff --git a/src/GeneralUpdate.Core/Strategy/ClientStrategy.cs b/src/GeneralUpdate.Core/Strategy/ClientStrategy.cs index 5cc33c79..9301f228 100644 --- a/src/GeneralUpdate.Core/Strategy/ClientStrategy.cs +++ b/src/GeneralUpdate.Core/Strategy/ClientStrategy.cs @@ -437,6 +437,14 @@ private async Task ExecuteStandardWorkflowAsync() { _reportType = 2; _configInfo.ReportType = 2; + if (_configInfo.RequirePushValidation) + { + if (_orchestrator != null || _customDownloadExecutor != null || _customDownloadPipelineFactory != null) + throw new InvalidOperationException( + "Validated push updates require the built-in HTTP download executor and orchestrator."); + _configInfo.VerifyChecksum = true; + GeneralTracer.Info("ClientStrategy: checksum verification is required for validated push packages."); + } } // Call server validation — returns assets from the two Validate calls @@ -599,10 +607,17 @@ private async Task ExecuteStandardWorkflowAsync() } else { - var httpClient = GeneralUpdate.Core.Network.HttpClientProvider.Shared; + var httpClient = _configInfo.RequirePushValidation + ? Network.PushHttpTransport.Client + : Network.HttpClientProvider.Shared; + var executor = _configInfo.RequirePushValidation + ? new Download.Executors.HttpDownloadExecutor(httpClient, + TimeSpan.FromSeconds(_configInfo.DownloadTimeOut), _configInfo.EnableResume, + (request, token) => Network.PushHttpTransport.ApplyAuthAsync(_configInfo, request, token)) + : _customDownloadExecutor; var orchestrator = new Download.Orchestrators.DefaultDownloadOrchestrator( httpClient, orchOptions, _customDownloadPolicy, - _customDownloadExecutor, _customDownloadPipelineFactory); + executor, _customDownloadPipelineFactory); return await orchestrator.ExecuteAsync(plan, _configInfo.TempPath, progress: progress).ConfigureAwait(false); } } @@ -666,6 +681,7 @@ async Task DownloadAndApplyAsync(Download.Models.DownloadPlan plan, UpdateScenar { case UpdateScenario.UpgradeOnly: await ApplyUpgradePackagesAsync(uVersions).ConfigureAwait(false); + if (_configInfo.PushValidationRejected) return; if (UpgradePackagesSucceeded()) { await SafeOnAfterUpdateAsync(hooksCtx).ConfigureAwait(false); @@ -728,6 +744,7 @@ async Task DownloadAndApplyAsync(Download.Models.DownloadPlan plan, UpdateScenar await DownloadAndApplyAsync(downloadPlan, scenario).ConfigureAwait(false); } + #endregion #region Scenario actions @@ -754,7 +771,11 @@ private async Task ApplyUpgradePackagesAsync(List upgradeVersions) // continues the loop, so ExecuteAsync() completing is not a // reliable success signal on its own. if ((_osStrategy as AbstractStrategy)?.AllPackagesSucceeded == true) + { WriteBackUpgradeVersion(upgradeVersions, _configInfo!.InstallPath); + if (_configInfo.RequirePushValidation) + _configInfo.UpgradeClientVersion = upgradeVersions.Last().Version!; + } } /// diff --git a/src/GeneralUpdate.Core/Strategy/UpdateStrategy.cs b/src/GeneralUpdate.Core/Strategy/UpdateStrategy.cs index 6f8e446d..5e26ab60 100644 --- a/src/GeneralUpdate.Core/Strategy/UpdateStrategy.cs +++ b/src/GeneralUpdate.Core/Strategy/UpdateStrategy.cs @@ -101,6 +101,14 @@ public void Create(UpdateContext parameter) public async Task ExecuteAsync() { if (_configInfo == null) throw new InvalidOperationException("UpdateStrategy not configured."); + if (_configInfo.RequirePushValidation && + (_configInfo.ReportType != 2 || _configInfo.UpdateVersions?.Count != 1 || + _configInfo.UpdateVersions[0].AppType != (int)AppType.Client || + _configInfo.UpdateVersions[0].PackageType != (int)PackageType.Full)) + { + GeneralTracer.Warn("UpdateStrategy: rejected invalid validated-push IPC contract."); + return; + } var ctx = BuildUpdateContext(); try @@ -123,6 +131,11 @@ public async Task ExecuteAsync() GeneralTracer.Info("UpdateStrategy: applying " + _configInfo.UpdateVersions.Count + " MainApp update(s)."); await _osStrategy.ExecuteAsync(); + if (_configInfo.PushValidationRejected) + { + GeneralTracer.Warn("UpdateStrategy: rejected push update; no files applied or terminal receipt sent."); + return; + } // Only advance the manifest version when every package was applied // successfully. AbstractStrategy catches per-package failures and diff --git a/tests/CoreTest/CoreTest.csproj b/tests/CoreTest/CoreTest.csproj index 99d514db..62ee75d1 100644 --- a/tests/CoreTest/CoreTest.csproj +++ b/tests/CoreTest/CoreTest.csproj @@ -21,6 +21,8 @@ + + \ No newline at end of file diff --git a/tests/CoreTest/Hubs/PushProcessIntegrationTests.cs b/tests/CoreTest/Hubs/PushProcessIntegrationTests.cs new file mode 100644 index 00000000..1c3e75a6 --- /dev/null +++ b/tests/CoreTest/Hubs/PushProcessIntegrationTests.cs @@ -0,0 +1,350 @@ +using System.Collections.Concurrent; +using System.Diagnostics; +using System.IO.Compression; +using System.Net; +using System.Security.Cryptography; +using System.Text.Json; +using GeneralUpdate.Core.Configuration; +using GeneralUpdate.Core.JsonContext; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.SignalR; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +namespace CoreTest.Hubs; + +[CollectionDefinition("Push process", DisableParallelization = true)] +public class PushProcessCollection; + +[Collection("Push process")] +public class PushProcessIntegrationTests +{ + [Fact] + public async Task ClientPush_AutomaticallyLaunchesUpdater_WithTwoChecksAndTenantReceipts() + { + await using var test = await PushFixture.StartAsync(); + await test.SendAsync(test.Packet(AppType.Client, 123)); + await test.WaitForFileAsync("updater-finished"); + + Assert.Equal("updated", await File.ReadAllTextAsync(Path.Combine(test.Root, "marker.txt"))); + Assert.NotEqual(await File.ReadAllTextAsync(Path.Combine(test.Root, "client-ready")), + await File.ReadAllTextAsync(Path.Combine(test.Root, "updater-started"))); + Assert.Equal(2, test.State.Validations.Count); + Assert.All(test.State.Validations, request => + { + Assert.Equal(123, request.RecordId); + Assert.Equal(PushFixture.AppKey, request.AppKey); + Assert.Equal(test.Hash, request.PacketHash); + Assert.Equal("push-tenant", request.Tenant); + Assert.False(request.MarkerExists); + }); + Assert.Contains(test.State.Reports, report => + report.RecordId == 123 && report.Type == 2 && report.Status == 2 && report.MarkerExists); + Assert.All(test.State.Reports, report => Assert.Equal("push-tenant", report.Tenant)); + Assert.Equal(0, test.State.Verifications); + } + + [Fact] + public async Task RevokedAfterDownload_RejectsInActualUpdater_BeforeFilesOrTerminalReports() + { + await using var test = await PushFixture.StartAsync(pause: true); + await test.SendAsync(test.Packet(AppType.Client, 124)); + await test.WaitForFileAsync("before-apply"); + Assert.Single(test.State.Validations); + test.State.ValidationStatus = 403; + File.WriteAllText(Path.Combine(test.Root, "resume-apply"), ""); + await test.WaitForFileAsync("updater-finished"); + + Assert.Equal(2, test.State.Validations.Count); + Assert.False(File.Exists(Path.Combine(test.Root, "marker.txt"))); + Assert.DoesNotContain(test.State.Reports, report => report.Status is 2 or 3); + } + + [Fact] + public async Task ValidationTimeout_RejectsWithoutDownload_AndQueueContinues() + { + await using var test = await PushFixture.StartAsync(); + test.State.ValidationDelay = TimeSpan.FromSeconds(15); + await test.SendAsync(test.Packet(AppType.Client, 128)); + await test.WaitUntilAsync(() => test.State.Validations.Count == 1); + test.State.ValidationDelay = TimeSpan.Zero; + await test.SendAsync(test.Packet(AppType.Upgrade, 129)); + await test.WaitUntilAsync(() => test.State.Reports.Any(r => r.RecordId == 129 && r.Status == 2)); + + Assert.Equal(1, test.State.Downloads); + Assert.DoesNotContain(test.State.Reports, report => report.RecordId == 128); + Assert.False(File.Exists(Path.Combine(test.Root, "updater-started"))); + } + + [Fact] + public async Task DownloadRedirect_DoesNotForwardTenantHeadersOrApplyFiles() + { + await using var test = await PushFixture.StartAsync(); + test.State.RedirectDownload = true; + await test.SendAsync(test.Packet(AppType.Client, 130)); + await test.WaitUntilAsync(() => test.State.Reports.Any(r => r.RecordId == 130 && r.Status == 3)); + + Assert.Equal(0, test.State.Redirects); + Assert.False(File.Exists(Path.Combine(test.Root, "marker.txt"))); + Assert.False(File.Exists(Path.Combine(test.Root, "updater-started"))); + } + + [Fact] + public async Task InvalidAndLegacyMessages_AreRejected_ThenUpgradePacketsAreSerialized() + { + await using var test = await PushFixture.StartAsync(); + var legacy = test.Packet(AppType.Client, 0); + legacy.RecordId = null; + await test.SendAsync(legacy); + var wrongProduct = test.Packet(AppType.Client, 10); + wrongProduct.ProductId = "different"; + await test.SendAsync(wrongProduct); + var wrongPlatform = test.Packet(AppType.Client, 11); + wrongPlatform.Platform = 0; + await test.SendAsync(wrongPlatform); + var chain = test.Packet(AppType.Client, 12); + chain.PackageType = 1; + await test.SendAsync(chain); + var wrongOrigin = test.Packet(AppType.Client, 13); + wrongOrigin.Url = "http://127.0.0.1:1/package.zip"; + await test.SendAsync(wrongOrigin); + var wrongFormat = test.Packet(AppType.Client, 14); + wrongFormat.Format = "tar"; + await test.SendAsync(wrongFormat); + await test.SendAsync(test.Packet(AppType.Upgrade, 201)); + var next = test.Packet(AppType.Upgrade, 202); + next.Version = "3.0.0"; + next.Name = "package-next.zip"; + await test.SendAsync(next); + await test.WaitUntilAsync(() => test.State.Reports.Any(r => r.RecordId == 202 && r.Status == 2)); + + Assert.Equal(new[] { 201, 201, 202, 202 }, test.State.Validations.Select(v => v.RecordId)); + Assert.Equal(2, test.State.Downloads); + Assert.True(File.Exists(Path.Combine(test.Root, "updater", "marker.txt"))); + Assert.False(File.Exists(Path.Combine(test.Root, "updater-started"))); + Assert.Equal(0, test.State.Verifications); + } + + [Theory] + [InlineData(200, """{"code":400,"body":false}""")] + [InlineData(200, """{"code":200,"body":false}""")] + [InlineData(200, """{"body":true}""")] + [InlineData(200, """{"code":200}""")] + [InlineData(200, "null")] + [InlineData(200, "{")] + [InlineData(403, """{"code":200,"body":true}""")] + [InlineData(404, """{"code":200,"body":true}""")] + [InlineData(500, """{"code":200,"body":true}""")] + [InlineData(307, """{"code":200,"body":true}""")] + public async Task NonApproval_FailsClosed_BeforeDownload(int status, string body) + { + await using var test = await PushFixture.StartAsync(); + test.State.ValidationStatus = status; + test.State.ValidationBody = body; + await test.SendAsync(test.Packet(AppType.Client, 126)); + await test.WaitUntilAsync(() => test.State.Validations.Count == 1); + // A later accepted packet is the queue barrier: it must execute after the rejected packet. + test.State.ValidationStatus = 200; + test.State.ValidationBody = """{"code":200,"body":true}"""; + await test.SendAsync(test.Packet(AppType.Upgrade, 127)); + await test.WaitUntilAsync(() => test.State.Reports.Any(r => r.RecordId == 127 && r.Status == 2)); + + Assert.Equal(1, test.State.Downloads); + Assert.DoesNotContain(test.State.Reports, report => report.RecordId == 126); + Assert.False(File.Exists(Path.Combine(test.Root, "updater-started"))); + Assert.Equal(0, test.State.Redirects); + } + + private sealed class PushFixture : IAsyncDisposable + { + public const string AppKey = "registered-push-client"; + public required string Root { get; init; } + public required string Url { get; init; } + public required string Hash { get; init; } + public required WebApplication App { get; init; } + public required Process Client { get; init; } + public required ServerState State { get; init; } + private readonly ConcurrentQueue _output = new(); + + public static async Task StartAsync(bool pause = false) + { + var root = Path.Combine(Path.GetTempPath(), "GeneralUpdate.PushProcess", Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(Path.Combine(root, "updater")); + var host = Environment.GetEnvironmentVariable("GENERALUPDATE_PUSH_HOST_PATH") ?? + Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, + "..", "..", "..", "..", "PushAotSmoke", "bin", "Release", "net10.0", + OperatingSystem.IsWindows() ? "PushAotSmoke.exe" : "PushAotSmoke")); + Assert.True(File.Exists(host), $"Build or publish the push host first: {host}"); + foreach (var file in Directory.GetFiles(Path.GetDirectoryName(host)!)) + File.Copy(file, Path.Combine(root, "updater", Path.GetFileName(file)), true); + var updater = Path.Combine(root, "updater", OperatingSystem.IsWindows() ? "PushUpdater.exe" : "PushUpdater"); + File.Copy(host, updater, true); + if (!OperatingSystem.IsWindows()) + File.SetUnixFileMode(updater, File.GetUnixFileMode(host)); + + using var archive = new MemoryStream(); + using (var zip = new ZipArchive(archive, ZipArchiveMode.Create, leaveOpen: true)) + { + using var writer = new StreamWriter(zip.CreateEntry("marker.txt").Open()); + writer.Write("updated"); + } + var bytes = archive.ToArray(); + var state = new ServerState { Root = root, Zip = bytes }; + var builder = WebApplication.CreateBuilder(); + builder.Logging.ClearProviders(); + builder.WebHost.UseUrls("http://127.0.0.1:0"); + builder.Services.AddSignalR(); + builder.Services.AddSingleton(state); + var app = builder.Build(); + app.MapHub("/UpgradeHub"); + app.MapPost("/Upgrade/Verification", () => + { + Interlocked.Increment(ref state.Verifications); + return Microsoft.AspNetCore.Http.Results.Json(new { code = 404, body = Array.Empty() }); + }); + app.MapPost("/Upgrade/ValidatePush", async (Microsoft.AspNetCore.Http.HttpContext context) => + { + var request = await JsonSerializer.DeserializeAsync(context.Request.Body, + PushPayloadJsonContext.Default.PushValidationRequest); + var status = state.ValidationStatus; + var body = state.ValidationBody; + var delay = state.ValidationDelay; + Assert.False(context.Request.Headers.ContainsKey("X-Poison")); + state.Validations.Enqueue(new(request!.RecordId, request.AppKey, request.PacketHash, + context.Request.Headers["X-Tenant-Id"].ToString(), + File.Exists(Path.Combine(root, "marker.txt")))); + if (delay > TimeSpan.Zero) await Task.Delay(delay, context.RequestAborted); + context.Response.StatusCode = status; + if (status == 307) context.Response.Headers.Location = "/redirected"; + context.Response.ContentType = "application/json"; + await Microsoft.AspNetCore.Http.HttpResponseWritingExtensions.WriteAsync(context.Response, body); + }); + app.MapGet("/package.zip", (Microsoft.AspNetCore.Http.HttpContext context) => + { + Assert.Equal("push-tenant", context.Request.Headers["X-Tenant-Id"].ToString()); + Assert.False(context.Request.Headers.ContainsKey("X-Poison")); + Interlocked.Increment(ref state.Downloads); + if (state.RedirectDownload) + return Microsoft.AspNetCore.Http.Results.Redirect("/redirected", permanent: false, preserveMethod: true); + return Microsoft.AspNetCore.Http.Results.Bytes(bytes, "application/zip"); + }); + app.MapPost("/redirected", () => Interlocked.Increment(ref state.Redirects)); + app.MapGet("/redirected", () => Interlocked.Increment(ref state.Redirects)); + app.MapPost("/Upgrade/Report", async (Microsoft.AspNetCore.Http.HttpContext context) => + { + using var document = await JsonDocument.ParseAsync(context.Request.Body); + Assert.False(context.Request.Headers.ContainsKey("X-Poison")); + var value = document.RootElement; + state.Reports.Enqueue(new(value.GetProperty("recordId").GetInt32(), + value.GetProperty("status").GetInt32(), value.GetProperty("type").GetInt32(), + context.Request.Headers["X-Tenant-Id"].ToString(), + File.Exists(Path.Combine(root, "marker.txt")) || + File.Exists(Path.Combine(root, "updater", "marker.txt")))); + return Microsoft.AspNetCore.Http.Results.Ok(); + }); + await app.StartAsync(); + var url = app.Urls.Single(); + var start = new ProcessStartInfo(host, "client") + { + UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true + }; + start.Environment["GU_PUSH_ROOT"] = root; + start.Environment["GU_PUSH_SERVER"] = url; + start.Environment["GU_PUSH_APPKEY"] = AppKey; + start.Environment["GU_PUSH_PAUSE_APPLY"] = pause ? "1" : "0"; + var process = Process.Start(start)!; + var fixture = new PushFixture + { + Root = root, Url = url, App = app, Client = process, State = state, + Hash = Convert.ToHexString(SHA256.HashData(bytes)) + }; + process.OutputDataReceived += (_, e) => { if (e.Data != null) fixture._output.Enqueue(e.Data); }; + process.ErrorDataReceived += (_, e) => { if (e.Data != null) fixture._output.Enqueue(e.Data); }; + process.BeginOutputReadLine(); + process.BeginErrorReadLine(); + try + { + await fixture.WaitForFileAsync("client-ready"); + } + catch + { + await fixture.DisposeAsync(); + throw; + } + return fixture; + } + + public PushPayload Packet(AppType type, int id) => new() + { + RecordId = id, ProductId = "push-product", + Platform = OperatingSystem.IsWindows() ? 1 : OperatingSystem.IsLinux() ? 2 : 3, + AppType = (int)type, PackageType = 2, Format = "zip", + Name = "package.zip", Url = Url + "/package.zip", Hash = Hash, Version = "2.0.0", + Size = State.Zip.Length + }; + + public Task SendAsync(PushPayload packet) => App.Services.GetRequiredService>() + .Clients.All.SendAsync("ReceiveMessage", + JsonSerializer.Serialize(packet, PushPayloadJsonContext.Default.PushPayload)); + + public Task WaitForFileAsync(string name) => WaitUntilAsync(() => File.Exists(Path.Combine(Root, name))); + + public async Task WaitUntilAsync(Func condition) + { + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(30)); + while (!condition()) + { + if (timeout.IsCancellationRequested) + Assert.Fail("Timed out waiting for push process: " + string.Join(Environment.NewLine, _output)); + await Task.Delay(50); + } + } + + public async ValueTask DisposeAsync() + { + File.WriteAllText(Path.Combine(Root, "client-stop"), ""); + File.WriteAllText(Path.Combine(Root, "resume-apply"), ""); + try + { + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(10)); + await Client.WaitForExitAsync(timeout.Token); + } + catch (OperationCanceledException) + { + Client.Kill(entireProcessTree: true); + await Client.WaitForExitAsync(); + } + Client.Dispose(); + await App.DisposeAsync(); + Directory.Delete(Root, recursive: true); + } + } + + public sealed class PushTestHub : Hub + { + public override Task OnConnectedAsync() + { + Assert.Equal(PushFixture.AppKey, Context.GetHttpContext()!.Request.Headers["appkey"].ToString()); + return base.OnConnectedAsync(); + } + } + + public sealed class ServerState + { + public string Root { get; init; } = ""; + public byte[] Zip { get; init; } = Array.Empty(); + public int ValidationStatus = 200; + public string ValidationBody = """{"code":200,"body":true}"""; + public TimeSpan ValidationDelay; + public bool RedirectDownload; + public int Downloads; + public int Redirects; + public int Verifications; + public ConcurrentQueue Validations { get; } = new(); + public ConcurrentQueue Reports { get; } = new(); + } + + public record Validation(int RecordId, string AppKey, string PacketHash, string Tenant, bool MarkerExists); + public record Receipt(int RecordId, int Status, int Type, string Tenant, bool MarkerExists); +} diff --git a/tests/PushAotSmoke/Program.cs b/tests/PushAotSmoke/Program.cs index c1254222..2841278c 100644 --- a/tests/PushAotSmoke/Program.cs +++ b/tests/PushAotSmoke/Program.cs @@ -4,6 +4,16 @@ using GeneralUpdate.Core.Download; using GeneralUpdate.Core.Download.Sources; using GeneralUpdate.Core.JsonContext; +using GeneralUpdate.Core.Event; +using GeneralUpdate.Core.Hooks; +using GeneralUpdate.Core.Ipc; + +if (args.Length > 0 && args[0] == "client" || + Path.GetFileNameWithoutExtension(Environment.ProcessPath)?.Equals("PushUpdater", StringComparison.OrdinalIgnoreCase) == true) +{ + await RunHostAsync(); + return; +} const string packet = """ {"Name":"pkg.zip","Url":"https://example.test/a","Version":"2.0.0", @@ -33,3 +43,89 @@ throw new InvalidOperationException("Push IPC serialization failed."); Console.WriteLine("Push Native AOT smoke passed."); + +static async Task RunHostAsync() +{ + var root = Environment.GetEnvironmentVariable("GU_PUSH_ROOT") + ?? throw new InvalidOperationException("GU_PUSH_ROOT is required."); + var updater = Path.GetFileNameWithoutExtension(Environment.ProcessPath)? + .Equals("PushUpdater", StringComparison.OrdinalIgnoreCase) == true; + var bootstrap = new GeneralUpdateBootstrap( + new EncryptedFileProcessContractProvider(Path.Combine(root, "ipc"))); + GeneralUpdate.Core.Network.HttpClientProvider.ExtraHeaders["X-Poison"] = "other-tenant"; + bootstrap.AddListenerException((_, e) => Console.Error.WriteLine(e.Exception)); + + if (updater) + { + File.WriteAllText(Path.Combine(root, "updater-started"), Environment.ProcessId.ToString()); + await bootstrap.SetOption(Option.AppType, AppType.Upgrade).Hooks().LaunchAsync(); + File.WriteAllText(Path.Combine(root, "updater-finished"), Environment.ProcessId.ToString()); + return; + } + + var serverUrl = Environment.GetEnvironmentVariable("GU_PUSH_SERVER") + ?? throw new InvalidOperationException("GU_PUSH_SERVER is required."); + var appKey = Environment.GetEnvironmentVariable("GU_PUSH_APPKEY") + ?? throw new InvalidOperationException("GU_PUSH_APPKEY is required."); + var tenant = Environment.GetEnvironmentVariable("GU_PUSH_TENANT") ?? "push-tenant"; + await bootstrap.SetConfig(new UpdateRequest + { + UpdateUrl = serverUrl + "/Upgrade/Verification", + ReportUrl = serverUrl + "/Upgrade/Report", + AppSecretKey = Environment.GetEnvironmentVariable("GU_PUSH_SECRET") + ?? "process-fixture-api-secret", + ProductId = Environment.GetEnvironmentVariable("GU_PUSH_PRODUCT") ?? "push-product", + ClientVersion = Environment.GetEnvironmentVariable("GU_PUSH_CLIENT_VERSION") ?? "1.0.0", + UpgradeClientVersion = Environment.GetEnvironmentVariable("GU_PUSH_UPGRADE_VERSION") ?? "1.0.0", + InstallPath = root, + MainAppName = "Client", + UpdateAppName = OperatingSystem.IsWindows() ? "PushUpdater.exe" : "PushUpdater", + UpdatePath = "updater", + CustomHeaders = new Dictionary { ["X-Tenant-Id"] = tenant } + }) + .EnablePushUpdates(new HubConfig + { + Url = serverUrl + "/UpgradeHub", + ValidationUrl = serverUrl + "/Upgrade/ValidatePush", + AppKey = appKey + }) + .SetOption(Option.AppType, AppType.Client) + .SetOption(Option.LaunchClientAfterUpdate, false) + .SetOption(Option.RetryCount, 0) + .SetOption(Option.VerifyChecksum, false) // validated push must still verify its hash + .LaunchAsync(); + File.WriteAllText(Path.Combine(root, "client-ready"), Environment.ProcessId.ToString()); + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(90)); + var stop = WaitForFileAsync(Path.Combine(root, "client-stop"), timeout.Token); + await Task.WhenAny(bootstrap.PushCompletion, stop); + await bootstrap.StopPushUpdatesAsync(); + File.WriteAllText(Path.Combine(root, "client-finished"), Environment.ProcessId.ToString()); +} + +static async Task WaitForFileAsync(string path, CancellationToken token) +{ + while (!File.Exists(path)) + await Task.Delay(50, token); +} + +public sealed class ApplyGateHooks : IUpdateHooks +{ + public async Task OnBeforeUpdateAsync(HookContext context) + { + var root = Environment.GetEnvironmentVariable("GU_PUSH_ROOT") + ?? throw new InvalidOperationException("GU_PUSH_ROOT is required."); + if (Environment.GetEnvironmentVariable("GU_PUSH_PAUSE_APPLY") == "1") + { + File.WriteAllText(Path.Combine(root, "before-apply"), Environment.ProcessId.ToString()); + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(60)); + while (!File.Exists(Path.Combine(root, "resume-apply"))) + await Task.Delay(50, timeout.Token); + } + return true; + } + + public Task OnDownloadCompletedAsync(DownloadContext ctx) => Task.CompletedTask; + public Task OnAfterUpdateAsync(HookContext ctx) => Task.CompletedTask; + public Task OnUpdateErrorAsync(HookContext ctx, Exception ex) => Task.CompletedTask; + public Task OnBeforeStartAppAsync(HookContext ctx) => Task.CompletedTask; +} From 528c5a51f896b86c97a8aa958cd5aefa9073e8f1 Mon Sep 17 00:00:00 2001 From: Juster Zhu Date: Mon, 23 Nov 2026 13:19:09 +0800 Subject: [PATCH 2/2] fix: reject unsafe credential-bearing automatic push flows Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- docs/core-execution-flow.md | 27 +++++++++---- .../Bootstrap/GeneralUpdateBootstrap.cs | 40 +++---------------- .../Configuration/ConfigurationMapper.cs | 18 +++++---- .../Configuration/HubConfig.cs | 2 - .../Configuration/ProcessContract.cs | 3 -- .../Hubs/UpgradeHubService.cs | 21 +--------- .../Network/PushHttpTransport.cs | 18 ++++----- .../Strategy/UpdateStrategy.cs | 5 ++- .../Configuration/ProcessContractTests.cs | 32 +++++++++++++++ .../Hubs/PushProcessIntegrationTests.cs | 40 ++++++++++++++++--- tests/PushAotSmoke/Program.cs | 8 +++- 11 files changed, 119 insertions(+), 95 deletions(-) diff --git a/docs/core-execution-flow.md b/docs/core-execution-flow.md index 442961a6..7419f4f9 100644 --- a/docs/core-execution-flow.md +++ b/docs/core-execution-flow.md @@ -43,6 +43,13 @@ sidebar_position: 4 #### 默认关闭的自动宿主路径 +**DRAFT / NOT DEPLOYABLE for credential-bearing flow。** 现有固定 AES IPC 没有 +经过验证的 OS 目录 ACL、父子身份认证、endpoint-tenant 绑定或篡改/重放拒绝机制。 +本层不是安全传输修复,也不是认证握手。自动配置含任何 CustomHeaders(包括租户头)、 +API Token 或 Basic 用户名/密码时,在监听开始前 fail-closed;不得借助该路径传凭据。 +必填的 AppSecretKey 仅保留在 Client 本地,不用于自动 HTTP 认证,也不进入自动 IPC。 +安全通道需要独立 PR;无凭据进程 fixture 成功不证明生产安装安全。 + `GeneralUpdateBootstrap` 默认仍使用原有轮询/升级入口。显式调用 `EnablePushUpdates` 才启动自动监听;该模式的 `LaunchAsync` 只连接 SignalR,不调用 Verification,不和轮询 混用。应用需要保留 bootstrap 实例,在退出时调用 `StopPushUpdatesAsync`;控制台宿主 @@ -84,7 +91,7 @@ Chain/未声明包类型无法证明差分前置版本,拒绝自动应用。 `{"recordId":123,"appKey":"registered-client","packetHash":"..."}`。 仅 HTTP 2xx 且 camelCase `code=200/body=true` 继续;缺字段、旧端点、超时、异常、 HTTP 403/其他非成功均拒绝。默认 10 秒超时,不添加 TTL。下载完成后,Client 包的 -端点、appKey、RecordId、Hash 和 CustomHeaders 经 IPC 交给真实 updater; +端点、appKey、RecordId 和 Hash 经 IPC 交给真实 updater(不传 HTTP 头或 API 凭据); updater 执行现有 `OnBeforeUpdateAsync` hook 和文件 hash 检查后, `CompressMiddleware` 在实际写入文件前再次请求同一三元组。 Upgrade 包走现有 ClientStrategy 的就地应用路径,并在同一写入边界复查。 @@ -94,20 +101,23 @@ Blocked/终态,本实现不声称消除了该竞态。 自动下载只允许 UpdateUrl 的精确 origin(scheme/host/port),其他可信 origin 必须 在 `HubConfig.AllowedDownloadOrigins` 明确列出;不要加入不可信地址。 -认证/租户头仅来自本地 UpdateRequest 的快照,不读取其他 bootstrap 的全局 HTTP 头。 +自动 HTTP 流不附带 API 认证、租户头或其他 bootstrap 的全局 HTTP 头。 下载、校验和报告禁用重定向及 cookie 容器,防止跨 origin 转发;需要重定向的部署应 -配置最终可信地址。Hub 只发送明确的 AppKey/AccessToken,不自动发送 API 租户头; -需要时显式设置 `ForwardTenantHeaderToHub=true` 和 `TenantHeaderName`。 +配置最终可信地址。Hub 只发送明确的 AppKey/AccessToken,不发送 API 租户头。 ValidatePush 谓词不使用租户头,但停用租户头可被服务器激活过滤器提前拒绝为 403。 -Local 下载仍需要 `request.CustomHeaders["X-Tenant-Id"]`,它同样随 IPC 传给报告。 -自定义认证/下载/OS/reporter 不适用该自动路径;使用本地请求凭据和现有 hooks。 +Local 下载如果需要 `X-Tenant-Id` 或认证,**本层自动流拒绝该配置,不能用于该部署**。 +旧手动 API 的进程级头配置行为未改变,但本层不新增头/凭据 IPC 传输。 +自定义认证/下载/OS/reporter 不适用该自动路径;使用现有 hooks,不能用它绕过安全限制。 每进程仅允许一个自动监听器,因为文件存储仍有进程级状态;不要并行运行其他 手动升级/静默轮询,或在监听期间修改 bootstrap 配置/选项。队列默认容量 16、 消息上限 64 Ki 字符,串行处理;满队列显式记录拒绝,不保证可靠投递/重放。 初始连接失败向调用者传播,连接建立后沿用 SignalR 自动重连;不保证重连耗尽后 自动恢复。连接/身份/路径必须由真实宿主配置,库不能推断任意程序的启动生命周期。 -IPC 的固定 AES 密钥不是本地攻击者认证边界,安装目录和 IPC 目录需要 OS 权限保护。 +IPC 的固定 AES 密钥不是本地攻击者认证边界。本层没有设置或实测 OS ACL;选用安装级 +目录不等于权限安全。也没有父子身份验证、租户与端点认证绑定、MAC 或重放 nonce。 +删除读过的文件不等于重放拒绝;本地攻击者可修改包括验证开关在内的合同字段。 +因此无凭据路径的验证/回执测试也不证明能抵御本地 IPC 攻击或可安全生产部署。 #### 手动兼容路径 @@ -129,7 +139,8 @@ IPC 的固定 AES 密钥不是本地攻击者认证边界,安装目录和 IPC `tests/CoreTest/Hubs/PushProcessIntegrationTests.cs` 使用真实 loopback Kestrel/SignalR, 通过公开 bootstrap 自动监听,实际启动不同 PID 的 updater 并写入 ZIP marker, -验证两次校验、撤销后的拒绝、租户 IPC/回执、旧消息拒绝、串行 Upgrade 调度、 +验证两次校验、撤销后的拒绝、不发送 API 凭据、带租户头/Token 时 fail-closed、 +旧消息拒绝、串行 Upgrade 调度、 超时/业务/HTTP 拒绝与禁止重定向。它不是 GeneralSpace/MySQL 联测。 `tests/PushAotSmoke` 同时提供该进程宿主和 source-generated JSON smoke; `.github/workflows/push-aot.yml` 在 Windows/Linux 发布 Native AOT 后用原生宿主运行 diff --git a/src/GeneralUpdate.Core/Bootstrap/GeneralUpdateBootstrap.cs b/src/GeneralUpdate.Core/Bootstrap/GeneralUpdateBootstrap.cs index 98772930..1fc27831 100644 --- a/src/GeneralUpdate.Core/Bootstrap/GeneralUpdateBootstrap.cs +++ b/src/GeneralUpdate.Core/Bootstrap/GeneralUpdateBootstrap.cs @@ -205,12 +205,6 @@ public GeneralUpdateBootstrap EnablePushUpdates(HubConfig config) throw new ArgumentOutOfRangeException(nameof(config), "Push queue capacity must be positive."); if (string.IsNullOrWhiteSpace(config.AppKey)) throw new ArgumentException("Push updates require an explicitly configured AppKey.", nameof(config)); - if (!IsValidHeaderName(config.TenantHeaderName) || - config.TenantHeaderName.Equals("Authorization", StringComparison.OrdinalIgnoreCase) || - config.TenantHeaderName.Equals("Cookie", StringComparison.OrdinalIgnoreCase) || - config.TenantHeaderName.Equals("Host", StringComparison.OrdinalIgnoreCase) || - config.TenantHeaderName.Equals("appkey", StringComparison.OrdinalIgnoreCase)) - throw new ArgumentException("TenantHeaderName must be a non-sensitive tenant-scoping header.", nameof(config)); if (!IsSecureEndpoint(config.ValidationUrl)) throw new ArgumentException("Push validation URL must be an absolute HTTPS URL (HTTP is allowed only for loopback).", nameof(config)); if (config.AllowedDownloadOrigins == null || @@ -224,8 +218,6 @@ public GeneralUpdateBootstrap EnablePushUpdates(HubConfig config) ValidationUrl = config.ValidationUrl, AccessToken = config.AccessToken, AppKey = config.AppKey, - TenantHeaderName = config.TenantHeaderName, - ForwardTenantHeaderToHub = config.ForwardTenantHeaderToHub, ReconnectDelay = config.ReconnectDelay, MaxReconnectAttempts = config.MaxReconnectAttempts, QueueCapacity = config.QueueCapacity, @@ -240,15 +232,6 @@ private static bool IsSecureEndpoint(string? value) (uri.Scheme == Uri.UriSchemeHttp && uri.IsLoopback)) && string.IsNullOrEmpty(uri.UserInfo); - private static bool IsValidHeaderName(string? name) - { - if (string.IsNullOrWhiteSpace(name)) return false; - foreach (var character in name) - if (!(char.IsLetterOrDigit(character) || character == '-')) - return false; - return true; - } - /// Stops and disposes the opt-in push listener, waiting for queued messages to finish. public async Task StopPushUpdatesAsync() { @@ -313,6 +296,10 @@ private async Task StartPushUpdatesAsync() AppMetadataDiscoverer.Discover(_configInfo); if (string.IsNullOrWhiteSpace(_configInfo.ProductId)) throw new InvalidOperationException("Push updates require ProductId in the request or installed manifest."); + if (_configInfo.CustomHeaders?.Count > 0 || !string.IsNullOrEmpty(_configInfo.Token) || + !string.IsNullOrEmpty(_configInfo.BasicUsername) || !string.IsNullOrEmpty(_configInfo.BasicPassword)) + throw new InvalidOperationException( + "NOT DEPLOYABLE: credential-bearing or tenant-header push flows require a separately authenticated IPC channel."); if (ResolveExtension() != null || ResolveExtension() != null || ResolveExtension() != null || @@ -328,25 +315,10 @@ private async Task StartPushUpdatesAsync() if (_configInfo.CustomHeaders != null) _configInfo.CustomHeaders = new Dictionary(_configInfo.CustomHeaders, StringComparer.OrdinalIgnoreCase); - var hubHeaders = new Dictionary(StringComparer.OrdinalIgnoreCase); - if (_pushHubConfig!.ForwardTenantHeaderToHub && _configInfo.CustomHeaders != null) - { - foreach (var header in _configInfo.CustomHeaders) - { - if (header.Key.Equals(_pushHubConfig!.TenantHeaderName, StringComparison.OrdinalIgnoreCase) && - !string.IsNullOrWhiteSpace(header.Value)) - { - hubHeaders[_pushHubConfig.TenantHeaderName] = header.Value; - break; - } - } - } - var hub = new UpgradeHubService( _pushHubConfig!.Url, _pushHubConfig.AccessToken, - _pushHubConfig.AppKey, - hubHeaders); + _pushHubConfig.AppKey); var listener = new PushUpdateListener(hub, ProcessPushMessageAsync, _pushHubConfig.QueueCapacity); _pushListener = listener; try @@ -724,7 +696,6 @@ private void InitializeFromEnvironment() UpdatePath = processInfo.UpdatePath, LaunchClientAfterUpdate = processInfo.LaunchClientAfterUpdate, ReportType = processInfo.ReportType, - CustomHeaders = processInfo.CustomHeaders, RequirePushValidation = processInfo.RequirePushValidation, PushValidationUrl = processInfo.PushValidationUrl, PushValidationAppKey = processInfo.PushValidationAppKey, @@ -733,7 +704,6 @@ private void InitializeFromEnvironment() Directories = processInfo.Directories ?? BlackDefaults.DefaultDirectories }; - SyncCustomHeaders(_configInfo.CustomHeaders); StorageManager.BlackMatcher = BlackMatcher.FromConfigInfo(_configInfo); } catch (Exception ex) diff --git a/src/GeneralUpdate.Core/Configuration/ConfigurationMapper.cs b/src/GeneralUpdate.Core/Configuration/ConfigurationMapper.cs index 194ed887..931104c9 100644 --- a/src/GeneralUpdate.Core/Configuration/ConfigurationMapper.cs +++ b/src/GeneralUpdate.Core/Configuration/ConfigurationMapper.cs @@ -177,6 +177,11 @@ public static ProcessContract MapToProcessContract( { if (source == null) throw new ArgumentNullException(nameof(source), "UpdateContext source cannot be null"); + if (source.RequirePushValidation && + (source.CustomHeaders?.Count > 0 || !string.IsNullOrEmpty(source.Token) || + !string.IsNullOrEmpty(source.BasicUsername) || !string.IsNullOrEmpty(source.BasicPassword))) + throw new InvalidOperationException( + "NOT DEPLOYABLE: automatic push cannot transfer credentials or tenant headers through unauthenticated IPC."); // 在单一位置创建 ProcessContract,包含所有必需参数 // 集中管理 ProcessContract 的参数映射逻辑 @@ -189,16 +194,16 @@ public static ProcessContract MapToProcessContract( compressEncoding: source.Encoding, // 调用此方法前已计算好的值 compressFormat: source.Format.ToExtension(), // 调用此方法前已计算好的值 downloadTimeOut: source.DownloadTimeOut, // 调用此方法前已计算好的值 - appSecretKey: source.AppSecretKey, + appSecretKey: source.RequirePushValidation ? string.Empty : source.AppSecretKey, updateVersions: updateVersions, // 来自 API 响应 reportUrl: source.ReportUrl, backupDirectory: source.BackupDirectory, // 调用此方法前已计算好的值 bowl: source.Bowl, - scheme: source.Scheme, - token: source.Token, + scheme: source.RequirePushValidation ? null : source.Scheme, + token: source.RequirePushValidation ? null : source.Token, authScheme: source.AuthScheme, - basicUsername: source.BasicUsername, - basicPassword: source.BasicPassword, + basicUsername: source.RequirePushValidation ? null : source.BasicUsername, + basicPassword: source.RequirePushValidation ? null : source.BasicPassword, driverDirectory: source.DriverDirectory, // 驱动更新所需的目录 tempPath: source.TempPath, // 客户端的下载临时路径,供升级进程定位包文件 blackFileFormats: blackFileFormats, // 来自 BlackListManager @@ -208,9 +213,6 @@ public static ProcessContract MapToProcessContract( launchClient: source.LaunchClientAfterUpdate ); processInfo.ReportType = reportType; - processInfo.CustomHeaders = source.CustomHeaders == null - ? null - : new Dictionary(source.CustomHeaders, StringComparer.OrdinalIgnoreCase); processInfo.RequirePushValidation = source.RequirePushValidation; processInfo.PushValidationUrl = source.PushValidationUrl; processInfo.PushValidationAppKey = source.PushValidationAppKey; diff --git a/src/GeneralUpdate.Core/Configuration/HubConfig.cs b/src/GeneralUpdate.Core/Configuration/HubConfig.cs index f8865f8d..5d41c975 100644 --- a/src/GeneralUpdate.Core/Configuration/HubConfig.cs +++ b/src/GeneralUpdate.Core/Configuration/HubConfig.cs @@ -9,8 +9,6 @@ public sealed class HubConfig public string ValidationUrl { get; set; } = string.Empty; public string? AccessToken { get; set; } public string? AppKey { get; set; } - public string TenantHeaderName { get; set; } = "X-Tenant-Id"; - public bool ForwardTenantHeaderToHub { get; set; } public TimeSpan ReconnectDelay { get; set; } = TimeSpan.FromSeconds(5); public int MaxReconnectAttempts { get; set; } = 10; public int QueueCapacity { get; set; } = 16; diff --git a/src/GeneralUpdate.Core/Configuration/ProcessContract.cs b/src/GeneralUpdate.Core/Configuration/ProcessContract.cs index 534aed46..f3ba54ed 100644 --- a/src/GeneralUpdate.Core/Configuration/ProcessContract.cs +++ b/src/GeneralUpdate.Core/Configuration/ProcessContract.cs @@ -404,9 +404,6 @@ public ProcessContract(string appName [JsonPropertyName("ReportType")] public int ReportType { get; set; } = 1; - [JsonPropertyName("CustomHeaders")] - public Dictionary? CustomHeaders { get; set; } - [JsonPropertyName("RequirePushValidation")] public bool RequirePushValidation { get; set; } diff --git a/src/GeneralUpdate.Core/Hubs/UpgradeHubService.cs b/src/GeneralUpdate.Core/Hubs/UpgradeHubService.cs index 6f45e25d..abd3c11a 100644 --- a/src/GeneralUpdate.Core/Hubs/UpgradeHubService.cs +++ b/src/GeneralUpdate.Core/Hubs/UpgradeHubService.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using System.Threading.Tasks; using GeneralUpdate.Core.JsonContext; using Microsoft.AspNetCore.SignalR; @@ -22,20 +21,9 @@ public class UpgradeHubService : IUpgradeHubService private bool _disposed; public UpgradeHubService(string url, string? token = null, string? appkey = null) - : this(url, token, appkey, null) { } + => _connection = BuildHubConnection(url, token, appkey); - public UpgradeHubService( - string url, - string? token, - string? appkey, - IReadOnlyDictionary? headers) - => _connection = BuildHubConnection(url, token, appkey, headers); - - private HubConnection BuildHubConnection( - string url, - string? token = null, - string? appkey = null, - IReadOnlyDictionary? headers = null) + private HubConnection BuildHubConnection(string url, string? token = null, string? appkey = null) { var builder = new HubConnectionBuilder() .WithUrl(url, config => @@ -46,11 +34,6 @@ private HubConnection BuildHubConnection( if (!string.IsNullOrWhiteSpace(appkey)) config.Headers.Add("appkey", appkey); - if (headers != null) - { - foreach (var header in headers) - config.Headers.Add(header.Key, header.Value); - } }).WithAutomaticReconnect(new RandomRetryPolicy()); builder.Services.Configure(o => { diff --git a/src/GeneralUpdate.Core/Network/PushHttpTransport.cs b/src/GeneralUpdate.Core/Network/PushHttpTransport.cs index c10aef0f..6d0a17c6 100644 --- a/src/GeneralUpdate.Core/Network/PushHttpTransport.cs +++ b/src/GeneralUpdate.Core/Network/PushHttpTransport.cs @@ -2,7 +2,7 @@ using System.Threading; using System.Threading.Tasks; using GeneralUpdate.Core.Configuration; -using GeneralUpdate.Core.Security; +using System; namespace GeneralUpdate.Core.Network; @@ -10,22 +10,18 @@ internal static class PushHttpTransport { internal static readonly HttpClient Client = HttpClientProvider.CreateClient(allowAutoRedirect: false); - internal static async Task ApplyAuthAsync( + internal static Task ApplyAuthAsync( UpdateContext config, HttpRequestMessage request, CancellationToken token) { - var provider = HttpAuthProviderFactory.Create(config.Scheme, config.Token, config.AppSecretKey, - config.AuthScheme, config.BasicUsername, config.BasicPassword); - await provider.ApplyAuthAsync(request, token).ConfigureAwait(false); ApplyHeaders(config, request); + return Task.CompletedTask; } internal static void ApplyHeaders(UpdateContext config, HttpRequestMessage request) { - if (config.CustomHeaders == null) return; - foreach (var header in config.CustomHeaders) - { - request.Headers.Remove(header.Key); - request.Headers.Add(header.Key, header.Value); - } + if (config.CustomHeaders?.Count > 0 || !string.IsNullOrEmpty(config.Token) || + !string.IsNullOrEmpty(config.BasicUsername) || !string.IsNullOrEmpty(config.BasicPassword)) + throw new InvalidOperationException( + "NOT DEPLOYABLE: credentials and tenant headers require authenticated IPC before automatic push can send them."); } } diff --git a/src/GeneralUpdate.Core/Strategy/UpdateStrategy.cs b/src/GeneralUpdate.Core/Strategy/UpdateStrategy.cs index 5e26ab60..5ee9ede3 100644 --- a/src/GeneralUpdate.Core/Strategy/UpdateStrategy.cs +++ b/src/GeneralUpdate.Core/Strategy/UpdateStrategy.cs @@ -102,7 +102,10 @@ public async Task ExecuteAsync() { if (_configInfo == null) throw new InvalidOperationException("UpdateStrategy not configured."); if (_configInfo.RequirePushValidation && - (_configInfo.ReportType != 2 || _configInfo.UpdateVersions?.Count != 1 || + (!string.IsNullOrEmpty(_configInfo.AppSecretKey) || + !string.IsNullOrEmpty(_configInfo.Token) || !string.IsNullOrEmpty(_configInfo.BasicUsername) || + !string.IsNullOrEmpty(_configInfo.BasicPassword) || _configInfo.CustomHeaders?.Count > 0 || + _configInfo.ReportType != 2 || _configInfo.UpdateVersions?.Count != 1 || _configInfo.UpdateVersions[0].AppType != (int)AppType.Client || _configInfo.UpdateVersions[0].PackageType != (int)PackageType.Full)) { diff --git a/tests/CoreTest/Configuration/ProcessContractTests.cs b/tests/CoreTest/Configuration/ProcessContractTests.cs index a0105fd3..277c5af1 100644 --- a/tests/CoreTest/Configuration/ProcessContractTests.cs +++ b/tests/CoreTest/Configuration/ProcessContractTests.cs @@ -9,6 +9,38 @@ public class ProcessContractTests private static string ExistingDir => Path.GetTempPath(); private static List SingleVersion => new() { new VersionEntry { Version = "2.0.0" } }; + [Fact] + public void ValidatedPushContract_DoesNotExportLocalApiSecret() + { + var source = new UpdateContext + { + MainAppName = "Client", InstallPath = ExistingDir, ClientVersion = "1.0.0", + LastVersion = "2.0.0", Encoding = Encoding.UTF8, Format = Format.Zip, + AppSecretKey = "local-api-secret", BackupDirectory = ExistingDir, + RequirePushValidation = true, PushValidationUrl = "https://api.example.test/Upgrade/ValidatePush", + PushValidationAppKey = "registered-client" + }; + var contract = ConfigurationMapper.MapToProcessContract( + source, SingleVersion, new(), new(), new(), 2); + Assert.Empty(contract.AppSecretKey); + Assert.Null(contract.Token); + Assert.Null(contract.BasicUsername); + Assert.Null(contract.BasicPassword); + Assert.Equal("registered-client", contract.PushValidationAppKey); + } + + [Fact] + public void ValidatedPushContract_RejectsTenantHeaderWithoutAuthenticatedChannel() + { + var source = new UpdateContext + { + RequirePushValidation = true, + CustomHeaders = new() { ["X-Tenant-Id"] = "private-tenant" } + }; + Assert.Throws(() => + ConfigurationMapper.MapToProcessContract(source, SingleVersion, new(), new(), new(), 2)); + } + [Fact] public void Ctor_AppNameNull_ThrowsArgumentNullException() { diff --git a/tests/CoreTest/Hubs/PushProcessIntegrationTests.cs b/tests/CoreTest/Hubs/PushProcessIntegrationTests.cs index 1c3e75a6..f484341f 100644 --- a/tests/CoreTest/Hubs/PushProcessIntegrationTests.cs +++ b/tests/CoreTest/Hubs/PushProcessIntegrationTests.cs @@ -21,7 +21,7 @@ public class PushProcessCollection; public class PushProcessIntegrationTests { [Fact] - public async Task ClientPush_AutomaticallyLaunchesUpdater_WithTwoChecksAndTenantReceipts() + public async Task ClientPush_AutomaticallyLaunchesUpdater_WithTwoChecksWithoutCredentials() { await using var test = await PushFixture.StartAsync(); await test.SendAsync(test.Packet(AppType.Client, 123)); @@ -36,15 +36,32 @@ public async Task ClientPush_AutomaticallyLaunchesUpdater_WithTwoChecksAndTenant Assert.Equal(123, request.RecordId); Assert.Equal(PushFixture.AppKey, request.AppKey); Assert.Equal(test.Hash, request.PacketHash); - Assert.Equal("push-tenant", request.Tenant); + Assert.Equal("", request.Tenant); Assert.False(request.MarkerExists); }); Assert.Contains(test.State.Reports, report => report.RecordId == 123 && report.Type == 2 && report.Status == 2 && report.MarkerExists); - Assert.All(test.State.Reports, report => Assert.Equal("push-tenant", report.Tenant)); + Assert.All(test.State.Reports, report => Assert.Equal("", report.Tenant)); Assert.Equal(0, test.State.Verifications); } + [Theory] + [InlineData("GU_PUSH_TENANT")] + [InlineData("GU_PUSH_TOKEN")] + [InlineData("GU_PUSH_BASIC_USERNAME")] + [InlineData("GU_PUSH_BASIC_PASSWORD")] + public async Task CredentialBearingConfiguration_FailsClosedBeforeListening(string credentialSetting) + { + await using var test = await PushFixture.StartAsync(credentialSetting: credentialSetting); + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(30)); + await test.Client.WaitForExitAsync(timeout.Token); + Assert.NotEqual(0, test.Client.ExitCode); + Assert.False(File.Exists(Path.Combine(test.Root, "client-ready"))); + Assert.Empty(test.State.Validations); + Assert.Equal(0, test.State.Downloads); + Assert.Empty(test.State.Reports); + } + [Fact] public async Task RevokedAfterDownload_RejectsInActualUpdater_BeforeFilesOrTerminalReports() { @@ -167,7 +184,7 @@ private sealed class PushFixture : IAsyncDisposable public required ServerState State { get; init; } private readonly ConcurrentQueue _output = new(); - public static async Task StartAsync(bool pause = false) + public static async Task StartAsync(bool pause = false, string? credentialSetting = null) { var root = Path.Combine(Path.GetTempPath(), "GeneralUpdate.PushProcess", Guid.NewGuid().ToString("N")); Directory.CreateDirectory(Path.Combine(root, "updater")); @@ -211,6 +228,8 @@ public static async Task StartAsync(bool pause = false) var body = state.ValidationBody; var delay = state.ValidationDelay; Assert.False(context.Request.Headers.ContainsKey("X-Poison")); + Assert.False(context.Request.Headers.ContainsKey("Authorization")); + Assert.False(context.Request.Headers.ContainsKey("X-Update-Signature")); state.Validations.Enqueue(new(request!.RecordId, request.AppKey, request.PacketHash, context.Request.Headers["X-Tenant-Id"].ToString(), File.Exists(Path.Combine(root, "marker.txt")))); @@ -222,8 +241,10 @@ public static async Task StartAsync(bool pause = false) }); app.MapGet("/package.zip", (Microsoft.AspNetCore.Http.HttpContext context) => { - Assert.Equal("push-tenant", context.Request.Headers["X-Tenant-Id"].ToString()); + Assert.Equal("", context.Request.Headers["X-Tenant-Id"].ToString()); Assert.False(context.Request.Headers.ContainsKey("X-Poison")); + Assert.False(context.Request.Headers.ContainsKey("Authorization")); + Assert.False(context.Request.Headers.ContainsKey("X-Update-Signature")); Interlocked.Increment(ref state.Downloads); if (state.RedirectDownload) return Microsoft.AspNetCore.Http.Results.Redirect("/redirected", permanent: false, preserveMethod: true); @@ -253,6 +274,12 @@ public static async Task StartAsync(bool pause = false) start.Environment["GU_PUSH_SERVER"] = url; start.Environment["GU_PUSH_APPKEY"] = AppKey; start.Environment["GU_PUSH_PAUSE_APPLY"] = pause ? "1" : "0"; + start.Environment.Remove("GU_PUSH_TENANT"); + start.Environment.Remove("GU_PUSH_TOKEN"); + start.Environment.Remove("GU_PUSH_BASIC_USERNAME"); + start.Environment.Remove("GU_PUSH_BASIC_PASSWORD"); + if (credentialSetting != null) + start.Environment[credentialSetting] = "sensitive-test-value"; var process = Process.Start(start)!; var fixture = new PushFixture { @@ -265,7 +292,8 @@ public static async Task StartAsync(bool pause = false) process.BeginErrorReadLine(); try { - await fixture.WaitForFileAsync("client-ready"); + if (credentialSetting == null) + await fixture.WaitForFileAsync("client-ready"); } catch { diff --git a/tests/PushAotSmoke/Program.cs b/tests/PushAotSmoke/Program.cs index 2841278c..a2ddd956 100644 --- a/tests/PushAotSmoke/Program.cs +++ b/tests/PushAotSmoke/Program.cs @@ -67,13 +67,16 @@ static async Task RunHostAsync() ?? throw new InvalidOperationException("GU_PUSH_SERVER is required."); var appKey = Environment.GetEnvironmentVariable("GU_PUSH_APPKEY") ?? throw new InvalidOperationException("GU_PUSH_APPKEY is required."); - var tenant = Environment.GetEnvironmentVariable("GU_PUSH_TENANT") ?? "push-tenant"; + var tenant = Environment.GetEnvironmentVariable("GU_PUSH_TENANT"); await bootstrap.SetConfig(new UpdateRequest { UpdateUrl = serverUrl + "/Upgrade/Verification", ReportUrl = serverUrl + "/Upgrade/Report", AppSecretKey = Environment.GetEnvironmentVariable("GU_PUSH_SECRET") ?? "process-fixture-api-secret", + Token = Environment.GetEnvironmentVariable("GU_PUSH_TOKEN"), + BasicUsername = Environment.GetEnvironmentVariable("GU_PUSH_BASIC_USERNAME"), + BasicPassword = Environment.GetEnvironmentVariable("GU_PUSH_BASIC_PASSWORD"), ProductId = Environment.GetEnvironmentVariable("GU_PUSH_PRODUCT") ?? "push-product", ClientVersion = Environment.GetEnvironmentVariable("GU_PUSH_CLIENT_VERSION") ?? "1.0.0", UpgradeClientVersion = Environment.GetEnvironmentVariable("GU_PUSH_UPGRADE_VERSION") ?? "1.0.0", @@ -81,7 +84,8 @@ await bootstrap.SetConfig(new UpdateRequest MainAppName = "Client", UpdateAppName = OperatingSystem.IsWindows() ? "PushUpdater.exe" : "PushUpdater", UpdatePath = "updater", - CustomHeaders = new Dictionary { ["X-Tenant-Id"] = tenant } + CustomHeaders = string.IsNullOrEmpty(tenant) ? null : + new Dictionary { ["X-Tenant-Id"] = tenant } }) .EnablePushUpdates(new HubConfig {