Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Desktop updater installs only an update signed by Harness (#4435) (#3524)

0xken15ac1ef96b4f4e
diff --git a/.github/actions/windows-signing/action.yml b/.github/actions/windows-signing/action.yml
index 3d53f7dc3..d28e19820 100644
--- a/.github/actions/windows-signing/action.yml
+++ b/.github/actions/windows-signing/action.yml
@@ -1,6 +1,6 @@
name: Windows Authenticode signing
description: >-
- Sign every .exe and .dll under a folder that carries no signature yet, through Azure Artifact Signing, then check
+ Sign every .exe, .dll and .cat under a folder that carries no signature yet, through Azure Artifact Signing, then check
every one of them: a valid signature, a timestamp, and ours naming the expected publisher. Files that already carry
a valid signature (Microsoft's ConPTY) are left as they are. Windows x64 runners only: the Artifact Signing action
does not run on Windows Arm, so arm64 builds are signed here too (Authenticode does not depend on the CPU).
@@ -8,7 +8,7 @@ description: >-
inputs:
path:
- description: The folder whose .exe and .dll files are signed, searched recursively
+ description: The folder whose .exe, .dll and .cat files are signed, searched recursively
required: true
publisher:
description: The certificate's common name every signature we add must carry (the validated identity)
@@ -43,8 +43,8 @@ runs:
SIGN_PATH: ${{ inputs.path }}
run: |
$ErrorActionPreference = 'Stop'
- $files = @(Get-ChildItem -LiteralPath $env:SIGN_PATH -Recurse -File | Where-Object { $_.Extension -in '.exe', '.dll' })
- if ($files.Count -eq 0) { throw "no .exe or .dll under $env:SIGN_PATH" }
+ $files = @(Get-ChildItem -LiteralPath $env:SIGN_PATH -Recurse -File | Where-Object { $_.Extension -in '.exe', '.dll', '.cat' })
+ if ($files.Count -eq 0) { throw "no .exe, .dll or .cat under $env:SIGN_PATH" }
$unsigned = @()
foreach ($file in $files) {
$status = (Get-AuthenticodeSignature -LiteralPath $file.FullName).Status
@@ -97,7 +97,7 @@ runs:
$ErrorActionPreference = 'Stop'
$ours = @(Get-Content -LiteralPath $env:SIGN_LIST -Encoding utf8)
$failed = @()
- foreach ($file in (Get-ChildItem -LiteralPath $env:SIGN_PATH -Recurse -File | Where-Object { $_.Extension -in '.exe', '.dll' })) {
+ foreach ($file in (Get-ChildItem -LiteralPath $env:SIGN_PATH -Recurse -File | Where-Object { $_.Extension -in '.exe', '.dll', '.cat' })) {
$signature = Get-AuthenticodeSignature -LiteralPath $file.FullName
$signer = if ($signature.SignerCertificate) { $signature.SignerCertificate.GetNameInfo('SimpleName', $false) } else { '' }
$problem = if ($signature.Status -ne 'Valid') { "status $($signature.Status)" }
diff --git a/.github/workflows/release-desktop.yml b/.github/workflows/release-desktop.yml
index 6951ed544..92c6aa419 100644
--- a/.github/workflows/release-desktop.yml
+++ b/.github/workflows/release-desktop.yml
@@ -546,6 +546,41 @@ jobs:
endpoint: ${{ vars.SIGNING_ENDPOINT }}
account: ${{ vars.SIGNING_ACCOUNT }}
profile: ${{ vars.SIGNING_PROFILE }}
+ # The Dart code (data/app.so) and the other files Authenticode cannot sign, by hash, in a catalog signed
+ # next. The updater installs a version folder only when this catalog is signed like the running app and
+ # every file in the folder matches it (desktop/lib/update/update_signature.dart). Written after the
+ # programs are signed, so their listed hashes are of the bytes that ship.
+ - name: Write the file catalogs
+ run: |
+ $ErrorActionPreference = 'Stop'
+ foreach ($arch in 'x64', 'arm64') {
+ $folder = (Resolve-Path -LiteralPath "windows-sign/$arch/app/$env:VERSION").Path
+ $catalog = Join-Path $env:RUNNER_TEMP "harness-desktop-$arch.cat"
+ New-FileCatalog -CatalogVersion 2.0 -Path $folder -CatalogFilePath $catalog | Out-Null
+ Move-Item -LiteralPath $catalog -Destination (Join-Path $folder 'harness-desktop.cat')
+ }
+ - name: Sign the file catalogs
+ uses: ./.github/actions/windows-signing
+ with:
+ path: windows-sign
+ publisher: ${{ vars.WINDOWS_SIGNING_PUBLISHER || 'AUTONOMOUS INC.' }}
+ azure-client-id: ${{ vars.AZURE_CLIENT_ID }}
+ azure-tenant-id: ${{ vars.AZURE_TENANT_ID }}
+ azure-subscription-id: ${{ vars.AZURE_SUBSCRIPTION_ID }}
+ endpoint: ${{ vars.SIGNING_ENDPOINT }}
+ account: ${{ vars.SIGNING_ACCOUNT }}
+ profile: ${{ vars.SIGNING_PROFILE }}
+ # What the updater will ask of the same folder once it is unpacked.
+ - name: Check the file catalogs
+ run: |
+ $ErrorActionPreference = 'Stop'
+ foreach ($arch in 'x64', 'arm64') {
+ $folder = (Resolve-Path -LiteralPath "windows-sign/$arch/app/$env:VERSION").Path
+ $result = Test-FileCatalog -CatalogFilePath (Join-Path $folder 'harness-desktop.cat') -Path $folder -FilesToSkip 'harness-desktop.cat' -Detailed
+ if ($result.Status -ne 'Valid') { throw "$arch catalog check: $($result.Status)" }
+ if ($result.Signature.Status -ne 'Valid') { throw "$arch catalog signature: $($result.Signature.Status)" }
+ Write-Host "$arch catalog valid: $($result.CatalogItems.Count) files, signed by $($result.Signature.SignerCertificate.Subject)"
+ }
# The same entries package-windows.ps1 writes: files only, relative, with forward slashes.
- name: Write the signed zips
run: |
diff --git a/cli/src/scripts/windowsWorkflows.spec.ts b/cli/src/scripts/windowsWorkflows.spec.ts
index ca9612689..18d9862b0 100644
--- a/cli/src/scripts/windowsWorkflows.spec.ts
+++ b/cli/src/scripts/windowsWorkflows.spec.ts
@@ -156,4 +156,19 @@ describe('the Windows release workflows', () => {
expect(action).toContain('timestamp-rfc3161: http://timestamp.acs.microsoft.com')
expect(action).not.toMatch(/client-secret|azure-password/)
})
+
+ // The Desktop updater (desktop/lib/update/update_signature.dart) installs a Windows version folder only when its
+ // signed catalog lists every file: data/app.so, the Dart code, has no Authenticode signature of its own.
+ it('signs a file catalog of each Desktop version folder, after its programs, and checks it', () => {
+ const sign = read('release-desktop.yml').match(/\n sign-windows:\n([\s\S]*?)(?=\n [\w-]+:\n|$)/)?.[1] ?? ''
+ const at = (text: string) => sign.indexOf(text)
+ expect(sign.match(/uses: \.\/\.github\/actions\/windows-signing/g)).toHaveLength(2)
+ expect(at('New-FileCatalog -CatalogVersion 2.0')).toBeGreaterThan(at('uses: ./.github/actions/windows-signing'))
+ expect(sign).toContain("Join-Path $folder 'harness-desktop.cat'")
+ expect(at('Test-FileCatalog')).toBeGreaterThan(at('name: Sign the file catalogs'))
+ expect(at('Test-FileCatalog')).toBeLessThan(at('name: Write the signed zips'))
+ expect(sign).toContain("-FilesToSkip 'harness-desktop.cat'")
+ const action = readFileSync(join(workflows, '..', 'actions', 'windows-signing', 'action.yml'), 'utf8')
+ expect(action.match(/\$_\.Extension -in '\.exe', '\.dll', '\.cat'/g)).toHaveLength(2)
+ })
})
diff --git a/desktop/CLAUDE.md b/desktop/CLAUDE.md
index ffbb906c1..fc256ce0d 100644
--- a/desktop/CLAUDE.md
+++ b/desktop/CLAUDE.md
@@ -908,7 +908,8 @@ add a kind there, not at the call site.
- The app has no flash UI: the dial is flashed with `harness flash`. `SerialPortLease` sees that
flash's lease file and pauses daemon supervision so `harness start` cannot steal the port mid-write.
- `lib/update/desktop_updater.dart` self-updates from the GCS manifest (sha256-verified, strictly
- newer only). Its keys must match what writes the manifest — `_otaKeyMacOS`/`_otaKeyMacOSArm64` the
+ newer only, and on macOS and Windows signed by the running app's own publisher:
+ `lib/update/update_signature.dart`, RELEASE.md "How a running app self-updates"). Its keys must match what writes the manifest — `_otaKeyMacOS`/`_otaKeyMacOSArm64` the
variant table in `scripts/publish-macos-variant.sh`, `desktop-linux-<arch>` the `OTA_KEY` in
`scripts/upload-desktop-linux.sh`. An Intel Mac reads only `desktop-macos` (the Skia build); Apple
Silicon takes the newer of `desktop-macos-arm64` and `desktop-macos`, arm64 winning a tie.
diff --git a/desktop/RELEASE.md b/desktop/RELEASE.md
index e272420a3..b1a367a43 100644
--- a/desktop/RELEASE.md
+++ b/desktop/RELEASE.md
@@ -392,7 +392,16 @@ which doesn't reliably pick up the quarantine flag in the first place).
republishing an old build cannot downgrade anyone.
3. After the user chooses **Update now**, downloads the zip and verifies its sha256 **before** anything is unpacked. A mismatch is discarded.
4. Unpacks into a staging directory and re-reads `CFBundleShortVersionString` from the staged bundle as
- a sanity check that the download really is the version it claims to be.
+ a sanity check that the download really is the version it claims to be. It installs it only if whoever signed the running app signed it too (`lib/update/update_signature.dart`): on macOS
+ `codesign --verify --deep --strict` against a Developer ID requirement with the running app's team and identifier,
+ notarized; on Windows every `.exe`/`.dll` and the launcher Authenticode-valid, the app, the launcher and
+ `app/<version>/harness-desktop.cat` signed like the running `harness-desktop.exe` (subject and Artifact Signing
+ identity), and that catalog matching every file in the folder, `data/app.so` included. Otherwise the banner says
+ it is not signed by the running app's publisher and the current version stays. The manifest can only pick among
+ builds we signed. A running app that is itself unsigned (a local or staging build) keeps the sha256 check alone;
+ Linux AppImages are unsigned, so Linux does too. Rotating keys: a new Developer ID certificate or a renewed
+ Artifact Signing certificate changes neither the team nor the identity, so nothing is needed. A new team or a new
+ identity validation needs one bridge release, signed the old way, whose rule also accepts the new signer.
5. Checks on launch (including the sign-in screen) and every minute. When a newer build exists,
it shows a non-blocking notification. The user chooses **Update now** to download and install it,
or **Skip version** to silence that exact version. A later version is shown normally; the account
@@ -429,7 +438,8 @@ flutter run -d macos \
A local origin is enough for that manifest: serve a zip of any `Harness.app` (its
`CFBundleShortVersionString` must match the version the manifest advertises, which the staging step
-verifies) with its real `size` and `sha256`, and write the body slowly if you want to read the
+verifies) with its real `size` and `sha256` — a local build is ad hoc signed, so it skips the signature check (step 4 above),
+while a released build only takes a zip signed by its own team — and write the body slowly if you want to read the
percentage rather than watch it jump to 100. `applyStaged` replaces the bundle it is running from,
so run a COPY of the build rather than the one `flutter run` owns.
@@ -603,7 +613,8 @@ its own runner and `upload-windows` publishes from ubuntu. Three files go to `ha
`Harness.exe --install` (`installer/`, docs/superpowers/specs/2026-10-19-windows-installer-design.md).
`sign-windows` Authenticode-signs every `.exe` and `.dll` in both zips and `harness-install.exe` through Azure Artifact
-Signing, as **AUTONOMOUS INC.**, once the repository variable `WINDOWS_SIGNING` is `required`
+Signing, then writes and signs `app/<version>/harness-desktop.cat`, a catalog of every file in the version folder
+that the updater checks ("How a running app self-updates", step 4), as **AUTONOMOUS INC.**, once the repository variable `WINDOWS_SIGNING` is `required`
([docs/windows-code-signing.md](../docs/windows-code-signing.md)). Until then it is skipped and the files ship
unsigned: Windows shows SmartScreen once, on the installer a browser downloaded, and Smart App Control blocks the build
where it is on. Once signing is required, a failed signature stops the release and a candidate prepared unsigned is
diff --git a/desktop/lib/update/desktop_updater.dart b/desktop/lib/update/desktop_updater.dart
index c2b7d0d60..453c203d0 100644
--- a/desktop/lib/update/desktop_updater.dart
+++ b/desktop/lib/update/desktop_updater.dart
@@ -11,6 +11,7 @@ import '../core/runtime_architecture.dart';
import '../core/runtime_platform.dart';
import '../core/app_version.dart';
import '../core/staging_build.dart';
+import 'update_signature.dart';
import 'windows_update_swap.dart';
/// Published by `scripts/upload-desktop.sh` (`make upload-desktop`) — see
@@ -74,6 +75,16 @@ class UpdateInfo {
});
}
+/// Refuses a staged update with [UpdateRefused] unless its signer is the
+/// running app's: [staged] is the macOS bundle or the Windows version folder,
+/// [launcher] the staged Windows `Harness.exe`, [version] the manifest's,
+/// which a staged Windows app must also say it is.
+typedef UpdateSignatureCheck = Future<void> Function(
+ String staged, {
+ String? launcher,
+ required String version,
+});
+
enum DesktopUpdateCheckStatus { upToDate, available, disabled, failed }
/// A failed or disabled check cannot establish that the installed app is current.
@@ -236,6 +247,7 @@ class DesktopUpdater {
final String _architecture;
final String? _windowsInstallRoot;
final Future<void> Function(String, List<String>)? _startDetached;
+ final UpdateSignatureCheck? _verifySignature;
final _checksInFlight = <String?, Future<DesktopUpdateCheck>>{};
/// How often the background poll asks the manifest.
@@ -276,6 +288,9 @@ class DesktopUpdater {
String? windowsInstallRoot,
Future<void> Function(String executable, List<String> arguments)?
startDetached,
+ // Defaults to checking against the running app's own signature. Tests
+ // whose fixtures are not signed pass their own.
+ UpdateSignatureCheck? verifySignature,
}) : _dio =
dio ??
Dio(
@@ -298,7 +313,39 @@ class DesktopUpdater {
// ignore: prefer_initializing_formals
_windowsInstallRoot = windowsInstallRoot,
// ignore: prefer_initializing_formals
- _startDetached = startDetached;
+ _startDetached = startDetached,
+ // ignore: prefer_initializing_formals
+ _verifySignature = verifySignature;
+
+ Future<void> _checkSignature(
+ String staged, {
+ String? launcher,
+ required String version,
+ }) => (_verifySignature ?? _signedLikeThisApp)(
+ staged,
+ launcher: launcher,
+ version: version,
+ );
+
+ /// Linux AppImages carry no signature, so Linux keeps the sha256 check.
+ Future<void> _signedLikeThisApp(
+ String staged, {
+ String? launcher,
+ required String version,
+ }) async {
+ if (_isWindows) {
+ return verifyWindowsUpdate(
+ stagedFolder: staged,
+ stagedLauncher: launcher!,
+ runningExe: RuntimePlatform.resolvedExecutable,
+ version: version,
+ );
+ }
+ if (_isLinux) return;
+ final running = currentBundlePath(isLinux: false, isWindows: false);
+ if (running == null) throw cannotCheckSignature;
+ return verifyMacUpdate(stagedBundle: staged, runningBundle: running);
+ }
/// The manifest entries this build may install, most preferred first — [_newestEntry] takes the
/// newest of them, an earlier key winning a tie.
@@ -425,7 +472,10 @@ class DesktopUpdater {
/// holds more than the hash alone authenticates. On Linux, the download itself is the artifact (a
/// single AppImage file), so the sha256 check already covers everything there is: it is made
/// executable and staged as-is, with nothing to unpack or recheck.
- /// Returns null (and cleans up anything partially written) on any verification failure.
+ /// On macOS and Windows the unpacked build must also be signed by whoever
+ /// signed the running app ([UpdateSignatureCheck]); a refusal deletes what
+ /// was staged and throws [UpdateRefused], whose message says why.
+ /// Returns null (and cleans up anything partially written) on any other verification failure.
/// [onProgress] reports the DOWNLOAD only — bytes received out of
/// [UpdateInfo.size]. The manifest's size is the denominator rather than the
/// response's, because a CDN that omits `Content-Length` leaves Dio reporting
@@ -485,6 +535,16 @@ class DesktopUpdater {
await stagingDir.delete(recursive: true);
return null;
}
+ try {
+ await _checkSignature(
+ swap.stagedFolder!,
+ launcher: swap.stagedLauncher,
+ version: info.version,
+ );
+ } on UpdateRefused {
+ await swap.discardStaged();
+ rethrow;
+ }
return StagedUpdate._windows(
version: info.version,
bundlePath: root,
@@ -545,23 +605,32 @@ class DesktopUpdater {
await stagingDir.delete(recursive: true);
return null;
}
+ // The bundle's own version was compared with the manifest's above.
+ await _checkSignature(bundlePath, version: info.version);
return StagedUpdate(
version: info.version,
bundlePath: bundlePath,
stagingDirPath: stagingDir.path,
);
+ } on UpdateRefused {
+ await _deleteQuietly(stagingDir);
+ rethrow;
} catch (error) {
debugPrint('DesktopUpdater.downloadAndStage: $error');
- try {
- await stagingDir?.delete(recursive: true);
- } catch (_) {
- // best-effort cleanup
- }
+ await _deleteQuietly(stagingDir);
return null;
}
}
+ static Future<void> _deleteQuietly(Directory? dir) async {
+ try {
+ await dir?.delete(recursive: true);
+ } catch (_) {
+ // best-effort cleanup
+ }
+ }
+
/// Hands off to a detached helper that waits for THIS process (pid [selfPid]) to exit, backs the
/// running bundle up as `Harness.app.prev`, swaps [staged] into place, relaunches it, and restores
/// the backup if the relaunch doesn't stay alive a few seconds later. Returns as soon as the helper
diff --git a/desktop/lib/update/update_signature.dart b/desktop/lib/update/update_signature.dart
new file mode 100644
index 000000000..9e9f81c30
--- /dev/null
+++ b/desktop/lib/update/update_signature.dart
@@ -0,0 +1,459 @@
+/// An update installs only when the publisher that signed the running app
+/// signed it too: a manifest someone else wrote can point at a build with the
+/// right sha256, but it cannot sign one as us.
+///
+/// The running app is the reference, not a name written here, so a release
+/// signed the way the last one was always passes, and nothing changes the day
+/// a short-lived certificate is renewed. A running app that is itself unsigned
+/// (a local build, a Windows staging build) has nothing to compare with and
+/// keeps the sha256 check alone; released builds are all signed, so an
+/// installed release only ever moves to another signed one.
+library;
+
+import 'dart:async';
+import 'dart:convert';
+import 'dart:io';
+
+import 'package:flutter/foundation.dart';
+
+import '../bootstrap/environment_provisioner.dart' show windowsPowerShellPath;
+import '../core/hidden_process.dart';
+import '../core/runtime_platform.dart';
+
+/// Long enough for a cold `codesign --deep` over a 300 MB bundle or a
+/// PowerShell start on a busy PC; a check that takes longer refuses.
+const signatureCheckTimeout = Duration(seconds: 60);
+
+/// Why an update was not installed, in words for the person: the banner shows
+/// "Could not install Harness X: " followed by [message].
+class UpdateRefused implements Exception {
+ const UpdateRefused(this.message);
+ final String message;
+
+ @override
+ String toString() => message;
+}
+
+/// The update is not from whoever made the running app.
+UpdateRefused notFromPublisher(String publisher) => UpdateRefused(
+ 'it is not signed by $publisher, who made the Harness you are using, so it '
+ 'may not be genuine. You are still on your current version.',
+);
+
+/// Harness could not find out who signed the update or itself.
+const cannotCheckSignature = UpdateRefused(
+ 'Harness could not check who signed it. You are still on your current '
+ 'version; try again later.',
+);
+
+/// The running macOS app's signer: what a staged bundle must also carry.
+class MacSigner {
+ const MacSigner({
+ required this.team,
+ required this.identifier,
+ required this.name,
+ });
+
+ /// The Developer ID team, e.g. `54DJVWMJCC`.
+ final String team;
+
+ /// The bundle identifier, e.g. `ai.autonomous.harness`.
+ final String identifier;
+
+ /// The certificate's person-readable name, e.g. `Autonomous Inc.`.
+ final String name;
+}
+
+/// Reads `codesign -dv --verbose=2` of the running bundle. Null means it is
+/// ad hoc or unsigned. Anything else it cannot read throws, so a missing tool
+/// or path is never mistaken for an unsigned build.
+MacSigner? parseMacSigner(String codesignDisplay) {
+ String? field(String key) => RegExp(
+ '^$key=(.*)\$',
+ multiLine: true,
+ ).firstMatch(codesignDisplay)?.group(1)?.trim();
+
+ if (codesignDisplay.contains('code object is not signed at all') ||
+ field('Signature') == 'adhoc') {
+ return null;
+ }
+ final team = field('TeamIdentifier');
+ final identifier = field('Identifier');
+ final authority = RegExp(
+ r'^Authority=Developer ID Application: (.+) \(([A-Z0-9]{10})\)$',
+ multiLine: true,
+ ).firstMatch(codesignDisplay);
+ if (team == null ||
+ identifier == null ||
+ authority == null ||
+ authority.group(2) != team) {
+ throw cannotCheckSignature;
+ }
+ return MacSigner(
+ team: team,
+ identifier: identifier,
+ name: authority.group(1)!,
+ );
+}
+
+/// The code requirement a staged bundle must meet: Apple's Developer ID chain
+/// (intermediate and leaf marker fields), the running app's team and
+/// identifier, and Apple's notarization ticket.
+String macUpdateRequirement(MacSigner signer) =>
+ 'anchor apple generic'
+ ' and certificate 1[field.1.2.840.113635.100.6.2.6]'
+ ' and certificate leaf[field.1.2.840.113635.100.6.1.13]'
+ ' and certificate leaf[subject.OU] = "${signer.team}"'
+ ' and identifier "${signer.identifier}"'
+ ' and notarized';
+
+/// One Authenticode signature as `Get-AuthenticodeSignature` reports it.
+class WindowsSigner {
+ const WindowsSigner({
+ required this.status,
+ required this.subject,
+ required this.identity,
+ });
+
+ factory WindowsSigner.fromJson(Map<String, dynamic> json) => WindowsSigner(
+ status: json['status'] as String? ?? '',
+ subject: json['subject'] as String? ?? '',
+ identity: json['identity'] as String? ?? '',
+ );
+
+ /// `Valid`, `NotSigned`, `HashMismatch`, `UnknownError`, …
+ final String status;
+
+ /// The signing certificate's subject.
+ final String subject;
+
+ /// Azure Artifact Signing's identity EKUs (`1.3.6.1.4.1.311.97.*` other
+ /// than the generic `.97.1.0`), sorted and space-separated. They name the
+ /// validated identity and stay the same while the 3-day certificates
+ /// rotate, so a lookalike subject on another identity does not match.
+ final String identity;
+
+ bool get valid => status == 'Valid';
+
+ /// The certificate's common name, e.g. `AUTONOMOUS INC.`.
+ String get name =>
+ RegExp(r'(?:^|, )CN=("[^"]*"|[^,]*)').firstMatch(subject)?.group(1) ??
+ subject;
+
+ bool sameAs(WindowsSigner other) =>
+ subject == other.subject && identity == other.identity;
+}
+
+/// The staged version folder's file catalog: `Test-FileCatalog`'s verdict on
+/// every file, and the catalog's own signature.
+class WindowsCatalog {
+ const WindowsCatalog({required this.status, required this.signer});
+ final String status;
+ final WindowsSigner signer;
+}
+
+/// What the hidden PowerShell found, keyed by file name relative to the
+/// version folder (the launcher as `Harness.exe`).
+class WindowsSignatureReport {
+ const WindowsSignatureReport({
+ required this.running,
+ required this.runningFolder,
+ required this.files,
+ required this.catalog,
+ required this.stagedVersion,
+ });
+
+ factory WindowsSignatureReport.fromJson(Map<String, dynamic> json) {
+ // PowerShell writes a one-item list as the item itself.
+ Map<String, WindowsSigner> byPath(Object? list) => {
+ for (final row
+ in (list is Map ? [list] : list as List? ?? const []).cast<Map>())
+ row['path'] as String: WindowsSigner.fromJson(row.cast()),
+ };
+ final catalog = json['catalog'] as Map?;
+ return WindowsSignatureReport(
+ running: WindowsSigner.fromJson((json['running'] as Map).cast()),
+ runningFolder: byPath(json['runningFolder']),
+ files: byPath(json['files']),
+ catalog: catalog == null
+ ? null
+ : WindowsCatalog(
+ status: catalog['status'] as String? ?? '',
+ signer: WindowsSigner.fromJson(
+ (catalog['signer'] as Map? ?? const {}).cast(),
+ ),
+ ),
+ stagedVersion: json['stagedVersion'] as String?,
+ );
+ }
+
+ /// The running `harness-desktop.exe`.
+ final WindowsSigner running;
+
+ /// Every `.exe` and `.dll` beside it.
+ final Map<String, WindowsSigner> runningFolder;
+
+ /// Every staged `.exe` and `.dll`, and the staged launcher.
+ final Map<String, WindowsSigner> files;
+ final WindowsCatalog? catalog;
+
+ /// The staged `harness-desktop.exe`'s ProductVersion, e.g. `1.3.91+42`
+ /// (`--build-name` and `--build-number`); null when it has none.
+ final String? stagedVersion;
+}
+
+/// The files only we may sign: the app and its launcher.
+const _ourFiles = {'harness-desktop.exe', 'harness.exe'};
+
+/// Null when the staged Windows update may install as [version] (the
+/// manifest's); otherwise what is wrong, for the log. Every staged program file must be validly signed; the app,
+/// the launcher and the catalog by the running app's signer; any other file
+/// by a signer the running version folder already trusts (Microsoft for
+/// WebView2Loader.dll). The catalog covers the files Authenticode cannot sign,
+/// the Dart code in `data/app.so` above all. The staged app must also say it
+/// is [version], as a macOS bundle must: a genuine older build, served as a
+/// newer one, is refused.
+String? windowsUpdateRefusal(
+ WindowsSignatureReport report, {
+ required String version,
+}) {
+ final running = report.running;
+ if (running.status == 'NotSigned') return null;
+ if (!running.valid) {
+ return 'the running harness-desktop.exe signature is ${running.status}';
+ }
+ final trusted = [
+ running,
+ ...report.runningFolder.values.where((signer) => signer.valid),
+ ];
+ for (final required in ['harness-desktop.exe', 'Harness.exe']) {
+ if (!report.files.keys.any(
+ (path) => path.toLowerCase() == required.toLowerCase(),
+ )) {
+ return 'the update has no $required';
+ }
+ }
+ for (final MapEntry(key: path, value: signer) in report.files.entries) {
+ if (!signer.valid) return '$path signature is ${signer.status}';
+ final ours = _ourFiles.contains(
+ path.split(RegExp(r'[/\\]')).last.toLowerCase(),
+ );
+ final allowed = ours ? signer.sameAs(running) : trusted.any(signer.sameAs);
+ if (!allowed) return '$path is signed by ${signer.subject}';
+ }
+ final catalog = report.catalog;
+ if (catalog == null) return 'the update has no file catalog';
+ if (catalog.status != 'Valid') {
+ return 'the file catalog check says ${catalog.status}';
+ }
+ if (!catalog.signer.valid || !catalog.signer.sameAs(running)) {
+ return 'the file catalog is signed by "${catalog.signer.subject}" '
+ '(${catalog.signer.status})';
+ }
+ final staged = report.stagedVersion?.split('+').first.trim();
+ if (staged != version) {
+ return 'the update is Harness ${staged == null || staged.isEmpty ? '(no version)' : staged}, '
+ 'not $version';
+ }
+ return null;
+}
+
+/// Refuses [stagedBundle] unless it meets [macUpdateRequirement] for the
+/// signer of [runningBundle]; a running bundle with no signer passes it.
+Future<void> verifyMacUpdate({
+ required String stagedBundle,
+ required String runningBundle,
+ Duration timeout = signatureCheckTimeout,
+}) async {
+ final display = await _run('/usr/bin/codesign', [
+ '-dv',
+ '--verbose=2',
+ runningBundle,
+ ], timeout);
+ final signer = parseMacSigner('${display.stdout}${display.stderr}');
+ if (signer == null) {
+ debugPrint(
+ 'UpdateSignature: the running app is not signed; the update is checked by sha256 only',
+ );
+ return;
+ }
+ final check = await _run('/usr/bin/codesign', [
+ '--verify',
+ '--deep',
+ '--strict',
+ '-R=${macUpdateRequirement(signer)}',
+ stagedBundle,
+ ], timeout);
+ if (check.exitCode != 0) {
+ debugPrint('UpdateSignature: refused: ${'${check.stderr}'.trim()}');
+ throw notFromPublisher(signer.name);
+ }
+}
+
+/// Prints one [WindowsSignatureReport] as JSON. Paths come in through the
+/// environment, so no file name is ever parsed as PowerShell.
+@visibleForTesting
+const windowsReportScript = r"""
+$ErrorActionPreference = 'Stop'
+$ProgressPreference = 'SilentlyContinue'
+# 5.1's own module by path: a PSModulePath handed on by PowerShell 7 (a pwsh
+# window that started Harness, CI) makes autoload pick 7's, which 5.1 cannot
+# load, and the signature cmdlets are then not found.
+Import-Module -Name (Join-Path $PSHOME 'Modules\Microsoft.PowerShell.Security\Microsoft.PowerShell.Security.psd1')
+[Console]::OutputEncoding = [Text.UTF8Encoding]::new($false)
+function Signer($signature) {
+ $certificate = $signature.SignerCertificate
+ $identity = @()
+ if ($certificate) {
+ $identity = @($certificate.EnhancedKeyUsageList | ForEach-Object { $_.ObjectId } |
+ Where-Object { $_ -like '1.3.6.1.4.1.311.97.*' -and $_ -ne '1.3.6.1.4.1.311.97.1.0' } | Sort-Object)
+ }
+ [ordered]@{
+ status = "$($signature.Status)"
+ subject = if ($certificate) { $certificate.Subject } else { '' }
+ identity = $identity -join ' '
+ }
+}
+function Read-Signer($path) {
+ try { Signer (Get-AuthenticodeSignature -LiteralPath $path) }
+ catch { [ordered]@{ status = 'Unreadable'; subject = ''; identity = '' } }
+}
+# Files are listed from the very path their names are cut from: another form
+# of the same folder (an 8.3 name, say) would cut the wrong number of letters.
+function Programs($folder) {
+ $base = (Get-Item -LiteralPath $folder).FullName.TrimEnd('\')
+ @(Get-ChildItem -LiteralPath $base -Recurse -File -Force |
+ Where-Object { $_.Extension -in '.exe', '.dll' } | ForEach-Object {
+ if (-not $_.FullName.StartsWith($base + '\', [StringComparison]::OrdinalIgnoreCase)) {
+ throw "$($_.FullName) is outside $base"
+ }
+ $row = Read-Signer $_.FullName
+ $row.path = $_.FullName.Substring($base.Length + 1).Replace('\', '/')
+ $row
+ })
+}
+$files = @(Programs $env:HARNESS_UPDATE_STAGED)
+$stagedVersion = (Get-Item -LiteralPath (Join-Path $env:HARNESS_UPDATE_STAGED 'harness-desktop.exe')).VersionInfo.ProductVersion
+$launcher = Read-Signer $env:HARNESS_UPDATE_LAUNCHER
+$launcher.path = 'Harness.exe'
+$files += $launcher
+$catalog = $null
+$catalogPath = Join-Path $env:HARNESS_UPDATE_STAGED 'harness-desktop.cat'
+if (Test-Path -LiteralPath $catalogPath -PathType Leaf) {
+ try {
+ $result = Test-FileCatalog -CatalogFilePath $catalogPath -Path $env:HARNESS_UPDATE_STAGED -FilesToSkip 'harness-desktop.cat' -Detailed
+ $catalog = [ordered]@{ status = "$($result.Status)"; signer = Signer $result.Signature }
+ } catch {
+ $catalog = [ordered]@{ status = 'Unreadable'; signer = (Read-Signer $catalogPath) }
+ }
+}
+[ordered]@{
+ running = Read-Signer $env:HARNESS_UPDATE_RUNNING
+ runningFolder = @(Programs (Split-Path -Parent $env:HARNESS_UPDATE_RUNNING))
+ files = $files
+ catalog = $catalog
+ stagedVersion = $stagedVersion
+} | ConvertTo-Json -Depth 5 -Compress
+""";
+
+/// Asks a hidden Windows PowerShell who signed the running app, everything
+/// beside it, every staged program and the staged file catalog.
+Future<WindowsSignatureReport> readWindowsSignatureReport({
+ required String stagedFolder,
+ required String stagedLauncher,
+ required String runningExe,
+ Duration timeout = signatureCheckTimeout,
+}) async {
+ final script = windowsReportScript.codeUnits;
+ final utf16 = Uint8List(script.length * 2);
+ for (var i = 0; i < script.length; i++) {
+ utf16[i * 2] = script[i] & 0xff;
+ utf16[i * 2 + 1] = script[i] >> 8;
+ }
+ final result = await _run(
+ windowsPowerShellPath(RuntimePlatform.environment),
+ [
+ '-NoProfile',
+ '-NonInteractive',
+ '-ExecutionPolicy',
+ 'Bypass',
+ '-EncodedCommand',
+ base64.encode(utf16),
+ ],
+ timeout,
+ environment: {
+ 'HARNESS_UPDATE_STAGED': stagedFolder,
+ 'HARNESS_UPDATE_LAUNCHER': stagedLauncher,
+ 'HARNESS_UPDATE_RUNNING': runningExe,
+ },
+ );
+ try {
+ if (result.exitCode != 0) throw FormatException('exit ${result.exitCode}');
+ return WindowsSignatureReport.fromJson(
+ (jsonDecode('${result.stdout}') as Map).cast(),
+ );
+ } on Object catch (error) {
+ debugPrint(
+ 'UpdateSignature: no report ($error): ${'${result.stderr}'.trim()}',
+ );
+ throw cannotCheckSignature;
+ }
+}
+
+/// Refuses the staged Windows update unless [windowsUpdateRefusal] passes it.
+Future<void> verifyWindowsUpdate({
+ required String stagedFolder,
+ required String stagedLauncher,
+ required String runningExe,
+ required String version,
+ Duration timeout = signatureCheckTimeout,
+}) async {
+ final report = await readWindowsSignatureReport(
+ stagedFolder: stagedFolder,
+ stagedLauncher: stagedLauncher,
+ runningExe: runningExe,
+ timeout: timeout,
+ );
+ if (report.running.status == 'NotSigned') {
+ debugPrint(
+ 'UpdateSignature: the running app is not signed; the update is checked by sha256 only',
+ );
+ return;
+ }
+ final refusal = windowsUpdateRefusal(report, version: version);
+ if (refusal != null) {
+ debugPrint('UpdateSignature: refused: $refusal');
+ throw notFromPublisher(report.running.name);
+ }
+}
+
+/// Runs a check through [startHidden] (no console window on Windows) and
+/// refuses the update when it cannot finish within [timeout].
+Future<ProcessResult> _run(
+ String executable,
+ List<String> arguments,
+ Duration timeout, {
+ Map<String, String>? environment,
+}) async {
+ final Process process;
+ try {
+ process = await startHidden(
+ executable,
+ arguments,
+ environment: environment,
+ );
+ } on ProcessException catch (error) {
+ debugPrint('UpdateSignature: could not start $executable: $error');
+ throw cannotCheckSignature;
+ }
+ final stdout = process.stdout.transform(utf8.decoder).join();
+ final stderr = process.stderr.transform(utf8.decoder).join();
+ try {
+ final code = await process.exitCode.timeout(timeout);
+ return ProcessResult(process.pid, code, await stdout, await stderr);
+ } on TimeoutException {
+ process.kill();
+ debugPrint('UpdateSignature: $executable took over ${timeout.inSeconds} s');
+ throw cannotCheckSignature;
+ }
+}
diff --git a/desktop/lib/update/windows_update_swap.dart b/desktop/lib/update/windows_update_swap.dart
index 641ec63f3..3c152e2d3 100644
--- a/desktop/lib/update/windows_update_swap.dart
+++ b/desktop/lib/update/windows_update_swap.dart
@@ -51,6 +51,17 @@ class WindowsUpdateSwap {
bool get launcherNeedsRepair =>
!_ordinaryFile(p.join(installRoot, launcherExe));
+ /// The staged version folder and launcher, for the signature check; null
+ /// until [stage] succeeds.
+ String? get stagedFolder => switch ((_attemptRoot, _stagedVersion)) {
+ (final attempt?, final version?) => _staging(attempt, version),
+ _ => null,
+ };
+ String? get stagedLauncher => switch (_attemptRoot) {
+ final attempt? => p.join(attempt, '$launcherExe.new'),
+ null => null,
+ };
+
String get _app => p.join(installRoot, 'app');
String _staging(String attempt, String version) =>
p.join(attempt, 'app', '$version.staging');
diff --git a/desktop/test/desktop_updater_test.dart b/desktop/test/desktop_updater_test.dart
index 381eecf3c..00feb881c 100644
--- a/desktop/test/desktop_updater_test.dart
+++ b/desktop/test/desktop_updater_test.dart
@@ -10,6 +10,7 @@ import 'package:dio/dio.dart';
import 'package:archive/archive.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/update/desktop_updater.dart';
+import 'package:harness/update/update_signature.dart';
import 'package:path/path.dart' as p;
Future<String> _sha256Hex(List<int> bytes) async {
@@ -157,6 +158,14 @@ Uint8List _windowsZip(String version) {
return ZipEncoder().encodeBytes(archive);
}
+/// The fixtures here are not signed; update_signature_*_test.dart checks real
+/// signatures, and these tests check what the updater does with the verdict.
+Future<void> _signedByUs(
+ String staged, {
+ String? launcher,
+ required String version,
+}) async {}
+
void main() {
late Directory scratch;
HttpServer? server;
@@ -254,6 +263,7 @@ void main() {
windowsInstallRoot: root,
startDetached: (exe, args) async => starts.add((exe, args)),
dio: dio,
+ verifySignature: _signedByUs,
);
final staged = await updater.downloadAndStage(
UpdateInfo(
@@ -278,6 +288,57 @@ void main() {
);
});
+ test('Windows refuses a package its signature check rejects and keeps the current version', () async {
+ final root = p.join(scratch.path, 'Harness');
+ Directory(p.join(root, 'app', '1.2.0')).createSync(recursive: true);
+ File(p.join(root, 'app', '1.2.0', 'harness-desktop.exe'))
+ .writeAsStringSync('old app');
+ File(p.join(root, 'Harness.exe')).writeAsStringSync('old launcher');
+ File(p.join(root, 'Harness.ico')).writeAsStringSync('old icon');
+ File(p.join(root, 'current')).writeAsStringSync('1.2.0\r\n');
+ final bytes = _windowsZip('1.3.0');
+ final checked = <(String, String?)>[];
+ final updater = DesktopUpdater(
+ isWindows: true,
+ releaseMode: true,
+ windowsInstallRoot: root,
+ dio: Dio()..httpClientAdapter = _MemoryAdapter(bytes),
+ verifySignature: (staged, {launcher, required version}) async {
+ expect(
+ File(p.join(staged, 'harness-desktop.exe')).existsSync(),
+ isTrue,
+ );
+ expect(File(launcher!).readAsStringSync(), 'launcher 1.3.0');
+ // The staged app's own version is checked against the manifest's.
+ expect(version, '1.3.0');
+ checked.add((staged, launcher));
+ throw const UpdateRefused('it is not signed by AUTONOMOUS INC.');
+ },
+ );
+ await expectLater(
+ updater.downloadAndStage(
+ UpdateInfo(
+ version: '1.3.0',
+ url: 'https://fixture.invalid/update.zip',
+ sha256: await _sha256Hex(bytes),
+ size: bytes.length,
+ ),
+ ),
+ throwsA(isA<UpdateRefused>()),
+ );
+ expect(checked.single.$1, endsWith('1.3.0.staging'));
+ expect(Directory(checked.single.$1).existsSync(), isFalse);
+ expect(File(p.join(root, 'current')).readAsStringSync(), '1.2.0\r\n');
+ expect(
+ File(p.join(root, 'Harness.exe')).readAsStringSync(),
+ 'old launcher',
+ );
+ expect(
+ Directory(p.join(root, 'app')).listSync().map((e) => p.basename(e.path)),
+ ['1.2.0'],
+ );
+ });
+
test(
'Windows reports partial publication when launcher start fails',
() async {
@@ -296,6 +357,7 @@ void main() {
startDetached: (_, _) async =>
throw const ProcessException('Harness.exe', [], 'blocked'),
dio: Dio()..httpClientAdapter = _MemoryAdapter(bytes),
+ verifySignature: _signedByUs,
);
final staged = await updater.downloadAndStage(
UpdateInfo(
@@ -550,6 +612,7 @@ void main() {
enabled: true,
dio: Dio(),
isLinux: false,
+ verifySignature: _signedByUs,
);
final info = UpdateInfo(
version: newVersion,
@@ -600,6 +663,7 @@ void main() {
enabled: true,
dio: Dio(),
isLinux: false,
+ verifySignature: _signedByUs,
);
final info = UpdateInfo(
version: newVersion,
@@ -614,6 +678,41 @@ void main() {
await Directory(staged.stagingDirPath).delete(recursive: true);
}, skip: _macOnly);
+ test('downloadAndStage refuses a bundle its signature check rejects, and removes it', () async {
+ await serveMetadataAndZip(manifestVersion: newVersion);
+ final checked = <String>[];
+ final updater = DesktopUpdater(
+ isWindows: false,
+ enabled: true,
+ dio: Dio(),
+ isLinux: false,
+ verifySignature: (staged, {launcher, required version}) async {
+ expect(File('$staged/Contents/Info.plist').existsSync(), isTrue);
+ checked.add(staged);
+ throw const UpdateRefused('it is not signed by Autonomous Inc.');
+ },
+ );
+ await expectLater(
+ updater.downloadAndStage(
+ UpdateInfo(
+ version: newVersion,
+ url: 'http://127.0.0.1:${server!.port}/Harness-macos.zip',
+ sha256: zipSha,
+ size: zipBytes.length,
+ ),
+ ),
+ throwsA(
+ isA<UpdateRefused>().having(
+ (e) => e.message,
+ 'message',
+ 'it is not signed by Autonomous Inc.',
+ ),
+ ),
+ );
+ expect(checked.single, endsWith('Harness.app'));
+ expect(Directory(p.dirname(checked.single)).existsSync(), isFalse);
+ }, skip: _macOnly);
+
test('downloadAndStage rejects a bundle whose Info.plist does not match the advertised version', () async {
await serveMetadataAndZip(manifestVersion: newVersion);
final updater = DesktopUpdater(
diff --git a/desktop/test/update_progress_test.dart b/desktop/test/update_progress_test.dart
index 92373eb9d..4c8206d51 100644
--- a/desktop/test/update_progress_test.dart
+++ b/desktop/test/update_progress_test.dart
@@ -8,6 +8,7 @@ import 'package:harness/settings/sections/about_section.dart';
import 'package:harness/state/app_state.dart';
import 'package:harness/update/desktop_updater.dart';
import 'package:harness/update/manual_update_check.dart';
+import 'package:harness/update/update_signature.dart';
import 'package:harness/widgets/update_notice.dart';
import 'package:harness/measurement/product_runtime_health.dart';
@@ -83,6 +84,19 @@ void main() {
},
);
+ test('a refused signature reaches the banner in plain words', () async {
+ final installing = app.installAvailableUpdate();
+ await Future<void>.delayed(Duration.zero);
+ installer.staged.completeError(notFromPublisher('Autonomous Inc.'));
+ expect(await installing, isFalse);
+ expect(
+ app.updateError,
+ 'Could not install Harness 1.2.3: it is not signed by Autonomous Inc., '
+ 'who made the Harness you are using, so it may not be genuine. You are '
+ 'still on your current version.',
+ );
+ });
+
testWidgets('the banner counts the download, then goes quiet to unpack', (
tester,
) async {
diff --git a/desktop/test/update_signature_macos_test.dart b/desktop/test/update_signature_macos_test.dart
new file mode 100644
index 000000000..394145029
--- /dev/null
+++ b/desktop/test/update_signature_macos_test.dart
@@ -0,0 +1,158 @@
+import 'dart:io';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/update/update_signature.dart';
+import 'package:path/path.dart' as p;
+
+/// Real `codesign` on real bundles. Unsigned and ad-hoc fixtures are built
+/// here; a Developer ID, notarized one cannot be (that needs the signing
+/// identity), so the signed cases use an installed release:
+/// `HARNESS_SIGNED_APP_FIXTURE`, else `/Applications/Harness.app`.
+final String? _macOnly = Platform.isMacOS ? null : 'needs codesign (macOS)';
+
+String? _signedRelease() {
+ final path =
+ Platform.environment['HARNESS_SIGNED_APP_FIXTURE'] ??
+ '/Applications/Harness.app';
+ if (!Platform.isMacOS || !Directory(path).existsSync()) return null;
+ final display = Process.runSync('/usr/bin/codesign', ['-dv', path]);
+ return '${display.stderr}'.contains('TeamIdentifier=54DJVWMJCC')
+ ? path
+ : null;
+}
+
+/// A minimal `Harness.app`: Info.plist and an unsigned Mach-O.
+String _unsignedBundle(String dir, String name) {
+ final bundle = p.join(dir, name);
+ Directory(p.join(bundle, 'Contents', 'MacOS')).createSync(recursive: true);
+ File(p.join(bundle, 'Contents', 'Info.plist')).writeAsStringSync('''
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>CFBundleExecutable</key>
+ <string>Harness</string>
+ <key>CFBundleIdentifier</key>
+ <string>ai.autonomous.harness</string>
+ <key>CFBundleShortVersionString</key>
+ <string>9.9.9</string>
+</dict>
+</plist>
+''');
+ final binary = p.join(bundle, 'Contents', 'MacOS', 'Harness');
+ File('/usr/bin/true').copySync(binary);
+ final strip = Process.runSync('/usr/bin/codesign', [
+ '--remove-signature',
+ binary,
+ ]);
+ expect(strip.exitCode, 0, reason: '${strip.stderr}');
+ return bundle;
+}
+
+String _adHocBundle(String dir, String name) {
+ final bundle = _unsignedBundle(dir, name);
+ final sign = Process.runSync('/usr/bin/codesign', [
+ '--force',
+ '--sign',
+ '-',
+ bundle,
+ ]);
+ expect(sign.exitCode, 0, reason: '${sign.stderr}');
+ return bundle;
+}
+
+/// An APFS clone: instant, and changing it leaves the original alone.
+String _clone(String source, String dir, String name) {
+ final target = p.join(dir, name);
+ final copy = Process.runSync('/bin/cp', ['-cR', source, target]);
+ expect(copy.exitCode, 0, reason: '${copy.stderr}');
+ return target;
+}
+
+Matcher _refusedWith(String text) => throwsA(
+ isA<UpdateRefused>().having((e) => e.message, 'message', contains(text)),
+);
+
+void main() {
+ late Directory scratch;
+ final signed = _signedRelease();
+ final noSigned =
+ _macOnly ??
+ (signed == null
+ ? 'no notarized Developer ID Harness here: set HARNESS_SIGNED_APP_FIXTURE'
+ : null);
+
+ setUp(() => scratch = Directory.systemTemp.createTempSync('update-sig-'));
+ tearDown(() => scratch.deleteSync(recursive: true));
+
+ test(
+ 'a running build with no signer of its own keeps the sha256 check alone',
+ () async {
+ final running = _adHocBundle(scratch.path, 'Running.app');
+ await verifyMacUpdate(
+ stagedBundle: _unsignedBundle(scratch.path, 'Harness.app'),
+ runningBundle: running,
+ );
+ },
+ skip: _macOnly,
+ );
+
+ test('a running app whose signer cannot be read refuses', () async {
+ await expectLater(
+ verifyMacUpdate(
+ stagedBundle: _unsignedBundle(scratch.path, 'Harness.app'),
+ runningBundle: p.join(scratch.path, 'Missing.app'),
+ ),
+ _refusedWith('could not check'),
+ );
+ }, skip: _macOnly);
+
+ test('a check that runs out of time refuses', () async {
+ await expectLater(
+ verifyMacUpdate(
+ stagedBundle: _unsignedBundle(scratch.path, 'Harness.app'),
+ runningBundle: _adHocBundle(scratch.path, 'Running.app'),
+ timeout: Duration.zero,
+ ),
+ _refusedWith('could not check'),
+ );
+ }, skip: _macOnly);
+
+ test('an unsigned update is refused by a signed release', () async {
+ await expectLater(
+ verifyMacUpdate(
+ stagedBundle: _unsignedBundle(scratch.path, 'Harness.app'),
+ runningBundle: signed!,
+ ),
+ _refusedWith('not signed by Autonomous Inc.'),
+ );
+ }, skip: noSigned);
+
+ test('an ad-hoc signed update is refused by a signed release', () async {
+ await expectLater(
+ verifyMacUpdate(
+ stagedBundle: _adHocBundle(scratch.path, 'Harness.app'),
+ runningBundle: signed!,
+ ),
+ _refusedWith('not signed by Autonomous Inc.'),
+ );
+ }, skip: noSigned);
+
+ test('a correctly signed and notarized update installs', () async {
+ await verifyMacUpdate(
+ stagedBundle: _clone(signed!, scratch.path, 'Harness.app'),
+ runningBundle: signed,
+ );
+ }, skip: noSigned);
+
+ test('a signed update changed after signing is refused', () async {
+ final staged = _clone(signed!, scratch.path, 'Harness.app');
+ final resources = Directory(p.join(staged, 'Contents', 'Resources'));
+ final victim = resources.listSync().whereType<File>().first;
+ victim.writeAsStringSync('changed', mode: FileMode.append);
+ await expectLater(
+ verifyMacUpdate(stagedBundle: staged, runningBundle: signed),
+ _refusedWith('not signed by Autonomous Inc.'),
+ );
+ }, skip: noSigned);
+}
diff --git a/desktop/test/update_signature_test.dart b/desktop/test/update_signature_test.dart
new file mode 100644
index 000000000..ccc896a9f
--- /dev/null
+++ b/desktop/test/update_signature_test.dart
@@ -0,0 +1,364 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/update/update_signature.dart';
+
+/// `codesign -dv --verbose=2` of the published 1.3.89 Apple Silicon bundle.
+const _released = '''
+Executable=/Applications/Harness.app/Contents/MacOS/Harness
+Identifier=ai.autonomous.harness
+Format=app bundle with Mach-O universal (x86_64 arm64)
+CodeDirectory v=20500 size=23009 flags=0x10000(runtime) hashes=708+7 location=embedded
+Signature size=8980
+Authority=Developer ID Application: Autonomous Inc. (54DJVWMJCC)
+Authority=Developer ID Certification Authority
+Authority=Apple Root CA
+Timestamp=Nov 7, 2026 at 1:30:44 PM
+Notarization Ticket=stapled
+Info.plist entries=31
+TeamIdentifier=54DJVWMJCC
+Runtime Version=15.5.0
+Sealed Resources version=2 rules=13 files=20
+Internal requirements count=1 size=216
+''';
+
+/// The same bundle re-signed ad hoc, as a local build is.
+const _adHoc = '''
+Executable=/tmp/x/Harness.app/Contents/MacOS/Harness
+Identifier=ai.autonomous.harness
+CodeDirectory v=20400 size=5870 flags=0x2(adhoc) hashes=177+3 location=embedded
+Signature=adhoc
+TeamIdentifier=not set
+''';
+
+const _ours = WindowsSigner(
+ status: 'Valid',
+ subject:
+ 'CN=AUTONOMOUS INC., O=AUTONOMOUS INC., L=Redlands, S=California, C=US',
+ identity: '1.3.6.1.4.1.311.97.585055327.208923272.208213867.148721407',
+);
+const _microsoft = WindowsSigner(
+ status: 'Valid',
+ subject: 'CN=Microsoft Corporation, O=Microsoft Corporation, L=Redmond, S=Washington, C=US',
+ identity: '',
+);
+const _unsigned = WindowsSigner(status: 'NotSigned', subject: '', identity: '');
+
+/// The 1.3.89 package's shape, with the catalog the release now signs.
+/// The version the manifest names; the staged app says it with its build number.
+const _version = '1.3.91';
+
+String? _refusal(WindowsSignatureReport report) =>
+ windowsUpdateRefusal(report, version: _version);
+
+WindowsSignatureReport _report({
+ String? stagedVersion = '1.3.91+42',
+ WindowsSigner running = _ours,
+ Map<String, WindowsSigner>? files,
+ WindowsCatalog? catalog = const WindowsCatalog(
+ status: 'Valid',
+ signer: _ours,
+ ),
+}) => WindowsSignatureReport(
+ running: running,
+ runningFolder: const {
+ 'harness-desktop.exe': _ours,
+ 'flutter_windows.dll': _ours,
+ 'WebView2Loader.dll': _microsoft,
+ },
+ files:
+ files ??
+ const {
+ 'Harness.exe': _ours,
+ 'harness-desktop.exe': _ours,
+ 'flutter_windows.dll': _ours,
+ 'WebView2Loader.dll': _microsoft,
+ },
+ catalog: catalog,
+ stagedVersion: stagedVersion,
+);
+
+void main() {
+ group('the running macOS app', () {
+ test('a released build names its team, identifier and publisher', () {
+ final signer = parseMacSigner(_released)!;
+ expect(signer.team, '54DJVWMJCC');
+ expect(signer.identifier, 'ai.autonomous.harness');
+ expect(signer.name, 'Autonomous Inc.');
+ });
+
+ test('an ad-hoc or unsigned build has no signer to match', () {
+ expect(parseMacSigner(_adHoc), isNull);
+ expect(
+ parseMacSigner('/x/Harness.app: code object is not signed at all\n'),
+ isNull,
+ );
+ });
+
+ test('output it cannot read refuses rather than passing as unsigned', () {
+ expect(
+ () => parseMacSigner('/x/Harness.app: No such file or directory\n'),
+ throwsA(isA<UpdateRefused>()),
+ );
+ expect(() => parseMacSigner(''), throwsA(isA<UpdateRefused>()));
+ });
+
+ test(
+ 'the requirement pins Developer ID, the team, the app and notarization',
+ () {
+ final requirement = macUpdateRequirement(parseMacSigner(_released)!);
+ expect(requirement, startsWith('anchor apple generic'));
+ expect(
+ requirement,
+ contains('certificate 1[field.1.2.840.113635.100.6.2.6]'),
+ );
+ expect(
+ requirement,
+ contains('certificate leaf[field.1.2.840.113635.100.6.1.13]'),
+ );
+ expect(
+ requirement,
+ contains('certificate leaf[subject.OU] = "54DJVWMJCC"'),
+ );
+ expect(requirement, contains('identifier "ai.autonomous.harness"'));
+ expect(requirement, endsWith('and notarized'));
+ },
+ );
+ });
+
+ group('the Windows rule', () {
+ // Security review 2 of #3524: a manifest someone else wrote could serve a
+ // genuine older signed build, one with a known hole, as a newer version.
+ // The staged app's own version must be the manifest's, as on macOS.
+ test(
+ 'a genuine older build served as a newer version refuses, naming both',
+ () {
+ final why = _refusal(_report(stagedVersion: '1.3.80+7'));
+ expect(why, contains('1.3.80'));
+ expect(why, contains(_version));
+ },
+ );
+
+ test('a staged app whose version cannot be read refuses', () {
+ expect(_refusal(_report(stagedVersion: null)), isNotNull);
+ expect(_refusal(_report(stagedVersion: '')), isNotNull);
+ });
+
+ test('the build number after + is not part of the version', () {
+ expect(_refusal(_report(stagedVersion: '1.3.91')), isNull);
+ expect(
+ windowsUpdateRefusal(
+ _report(stagedVersion: '1.3.91-rc.2+40'),
+ version: '1.3.91-rc.2',
+ ),
+ isNull,
+ );
+ expect(_refusal(_report(stagedVersion: '1.3.910+1')), isNotNull);
+ });
+
+ test('the report reads the staged app\'s version', () {
+ final report = WindowsSignatureReport.fromJson({
+ 'running': {'status': 'NotSigned', 'subject': '', 'identity': ''},
+ 'stagedVersion': '1.3.91+42',
+ });
+ expect(report.stagedVersion, '1.3.91+42');
+ });
+
+ test('the released shape passes: our files, Microsoft\'s WebView2 loader, a valid catalog', () {
+ expect(_refusal(_report()), isNull);
+ });
+
+ test('a running app that is itself unsigned has no signer to match', () {
+ expect(_refusal(_report(running: _unsigned, catalog: null)), isNull);
+ });
+
+ test('a running app whose signature is broken refuses', () {
+ expect(
+ _refusal(
+ _report(
+ running: const WindowsSigner(
+ status: 'HashMismatch',
+ subject: '',
+ identity: '',
+ ),
+ ),
+ ),
+ contains('running'),
+ );
+ });
+
+ test('an extra unsigned DLL refuses, naming it', () {
+ expect(
+ _refusal(
+ _report(
+ files: const {
+ 'Harness.exe': _ours,
+ 'harness-desktop.exe': _ours,
+ 'evil.dll': _unsigned,
+ },
+ ),
+ ),
+ contains('evil.dll'),
+ );
+ });
+
+ test(
+ 'the app signed by someone else refuses, even a trusted publisher',
+ () {
+ expect(
+ _refusal(
+ _report(
+ files: const {
+ 'Harness.exe': _ours,
+ 'harness-desktop.exe': _microsoft,
+ },
+ ),
+ ),
+ contains('harness-desktop.exe'),
+ );
+ },
+ );
+
+ test('the same company name under another identity refuses', () {
+ const lookalike = WindowsSigner(
+ status: 'Valid',
+ subject: 'CN=AUTONOMOUS INC., O=AUTONOMOUS INC., L=Redlands, S=California, C=US',
+ identity: '1.3.6.1.4.1.311.97.1.2.3.4',
+ );
+ expect(
+ _refusal(
+ _report(
+ files: const {
+ 'Harness.exe': lookalike,
+ 'harness-desktop.exe': _ours,
+ },
+ ),
+ ),
+ contains('Harness.exe'),
+ );
+ });
+
+ test('a missing launcher or app refuses', () {
+ expect(
+ _refusal(_report(files: const {'harness-desktop.exe': _ours})),
+ contains('Harness.exe'),
+ );
+ });
+
+ test('no catalog, a changed file or an unsigned catalog refuses', () {
+ expect(_refusal(_report(catalog: null)), contains('catalog'));
+ expect(
+ _refusal(
+ _report(
+ catalog: const WindowsCatalog(
+ status: 'ValidationFailed',
+ signer: _ours,
+ ),
+ ),
+ ),
+ contains('catalog'),
+ );
+ expect(
+ _refusal(
+ _report(
+ catalog: const WindowsCatalog(status: 'Valid', signer: _unsigned),
+ ),
+ ),
+ contains('catalog'),
+ );
+ expect(
+ _refusal(
+ _report(
+ catalog: const WindowsCatalog(status: 'Valid', signer: _microsoft),
+ ),
+ ),
+ contains('catalog'),
+ );
+ });
+
+ test('the report reads what the PowerShell script prints', () {
+ final report = WindowsSignatureReport.fromJson({
+ 'running': {'status': 'Valid', 'subject': 'CN=A', 'identity': '1.2'},
+ 'runningFolder': [
+ {
+ 'path': 'a.dll',
+ 'status': 'Valid',
+ 'subject': 'CN=B',
+ 'identity': '',
+ },
+ ],
+ 'files': [
+ {
+ 'path': 'Harness.exe',
+ 'status': 'NotSigned',
+ 'subject': '',
+ 'identity': '',
+ },
+ ],
+ 'catalog': {
+ 'status': 'Valid',
+ 'signer': {'status': 'Valid', 'subject': 'CN=A', 'identity': '1.2'},
+ },
+ });
+ expect(report.running.subject, 'CN=A');
+ expect(report.runningFolder['a.dll']!.subject, 'CN=B');
+ expect(report.files['Harness.exe']!.status, 'NotSigned');
+ expect(report.catalog!.signer.identity, '1.2');
+ expect(
+ WindowsSignatureReport.fromJson({
+ 'running': {'status': 'NotSigned', 'subject': '', 'identity': ''},
+ 'runningFolder': [],
+ 'files': [],
+ 'catalog': null,
+ }).catalog,
+ isNull,
+ );
+ });
+
+ test('the publisher name comes from the certificate subject', () {
+ expect(_ours.name, 'AUTONOMOUS INC.');
+ });
+ });
+
+ // Windows CI run 42350030998: a PowerShell 7 step (and a PowerShell 7
+ // window that starts Harness) hands Windows PowerShell 5.1 a PSModulePath
+ // with 7's modules first, and 5.1 then cannot autoload
+ // Microsoft.PowerShell.Security: Get-AuthenticodeSignature is "found in the
+ // module ... but the module could not be loaded", and every update would be
+ // refused. The report loads 5.1's own module by path before using it.
+ test('the Windows report loads Windows PowerShell\'s own Security module first', () {
+ const load =
+ r"Import-Module -Name (Join-Path $PSHOME 'Modules\Microsoft.PowerShell.Security\Microsoft.PowerShell.Security.psd1')";
+ final script = windowsReportScript;
+ expect(script, contains(load));
+ expect(
+ script.indexOf(load),
+ lessThan(script.indexOf('Get-AuthenticodeSignature')),
+ );
+ expect(script.indexOf(load), lessThan(script.indexOf('Test-FileCatalog')));
+ });
+
+ // Windows CI run 42354774882: Resolve-Path gave the temp folder in another
+ // form than Get-ChildItem's FullName (8.3 RUNNER~1 against runneradmin), so
+ // cutting the root's length off named harness-desktop.exe
+ // "ng/harness-desktop.exe" and every update would have been refused. Each
+ // file is named relative to the very path it was listed from.
+ test(
+ 'the Windows report names files relative to the path it lists them from',
+ () {
+ final script = windowsReportScript;
+ expect(script, isNot(contains('Resolve-Path')));
+ expect(
+ script,
+ contains(
+ r"$base = (Get-Item -LiteralPath $folder).FullName.TrimEnd('\')",
+ ),
+ );
+ expect(script, contains(r'Get-ChildItem -LiteralPath $base -Recurse'));
+ expect(
+ script,
+ contains(
+ r"if (-not $_.FullName.StartsWith($base + '\', [StringComparison]::OrdinalIgnoreCase))",
+ ),
+ );
+ },
+ );
+}
diff --git a/desktop/test/update_signature_windows_test.dart b/desktop/test/update_signature_windows_test.dart
new file mode 100644
index 000000000..e5916589b
--- /dev/null
+++ b/desktop/test/update_signature_windows_test.dart
@@ -0,0 +1,286 @@
+import 'dart:convert';
+import 'dart:io';
+
+import 'package:flutter/foundation.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/bootstrap/environment_provisioner.dart'
+ show windowsPowerShellPath;
+import 'package:harness/core/hidden_process.dart';
+import 'package:harness/update/update_signature.dart';
+import 'package:path/path.dart' as p;
+
+/// Real `Get-AuthenticodeSignature` and `Test-FileCatalog` on real files.
+/// Nothing here can be signed by a trusted publisher (that needs a signing
+/// identity), so the signed fixture is a Microsoft program every Windows has,
+/// with its signature embedded, standing in for the running app.
+final String? _windowsOnly = Platform.isWindows
+ ? null
+ : 'needs Authenticode (Windows)';
+
+/// .NET Framework programs carry an embedded Microsoft signature; most of
+/// System32 is signed only through the system catalog, which a copy keeps.
+const _candidates = [
+ r'Microsoft.NET\Framework64\v4.0.30319\csc.exe',
+ r'Microsoft.NET\Framework64\v4.0.30319\vbc.exe',
+ r'Microsoft.NET\Framework64\v4.0.30319\MSBuild.exe',
+ r'Microsoft.NET\Framework\v4.0.30319\csc.exe',
+];
+
+const _loadSecurity =
+ r"Import-Module -Name (Join-Path $PSHOME 'Modules\Microsoft.PowerShell.Security\Microsoft.PowerShell.Security.psd1')";
+
+/// What [body] printed through debugPrint, where the refusal names its rule.
+Future<List<String>> _logged(Future<void> Function() body) async {
+ final lines = <String>[];
+ final previous = debugPrint;
+ debugPrint = (message, {wrapWidth}) => lines.add(message ?? '');
+ try {
+ await body();
+ } finally {
+ debugPrint = previous;
+ }
+ return lines;
+}
+
+Future<String> _powershell(String script) async {
+ final result = await runHidden(windowsPowerShellPath(Platform.environment), [
+ '-NoProfile',
+ '-NonInteractive',
+ '-EncodedCommand',
+ // As the report does: 5.1's own Security module, whatever PSModulePath
+ // this process hands on (a PowerShell 7 step in CI).
+ base64.encode(_utf16le('$_loadSecurity\n$script')),
+ ]);
+ expect(result.exitCode, 0, reason: '${result.stderr}');
+ return '${result.stdout}'.trim();
+}
+
+Uint8List _utf16le(String text) {
+ final units = text.codeUnits;
+ final bytes = Uint8List(units.length * 2);
+ for (var i = 0; i < units.length; i++) {
+ bytes[i * 2] = units[i] & 0xff;
+ bytes[i * 2 + 1] = units[i] >> 8;
+ }
+ return bytes;
+}
+
+Future<String> _embeddedSignedProgram() async {
+ final root = Platform.environment['SystemRoot'] ?? r'C:\Windows';
+ final named = [
+ for (final candidate in _candidates) "'${p.join(root, candidate)}'",
+ ].join(', ');
+ final system32 = p.join(root, 'System32');
+ final found = await _powershell(
+ "foreach (\$path in @($named) + @((Get-ChildItem -LiteralPath '$system32' -Filter *.exe).FullName)) { "
+ 'if (-not (Test-Path -LiteralPath \$path)) { continue }; '
+ '\$s = Get-AuthenticodeSignature -LiteralPath \$path; '
+ "if (\$s.SignatureType -eq 'Authenticode' -and \$s.Status -eq 'Valid') "
+ '{ \$path; break } }',
+ );
+ if (found.isEmpty) fail('no program with an embedded signature here');
+ return found;
+}
+
+/// [source] without its Authenticode certificate table, and one byte of its
+/// DOS stub changed so no system catalog lists it either: unsigned.
+void _stripSignature(String source, String target) {
+ final bytes = File(source).readAsBytesSync();
+ final view = ByteData.sublistView(bytes);
+ final pe = view.getUint32(0x3c, Endian.little);
+ final magic = view.getUint16(pe + 24, Endian.little);
+ final security = pe + 24 + (magic == 0x10b ? 96 : 112) + 4 * 8;
+ final offset = view.getUint32(security, Endian.little);
+ expect(offset, isNot(0), reason: '$source has no embedded signature');
+ view.setUint32(security, 0, Endian.little);
+ view.setUint32(security + 4, 0, Endian.little);
+ bytes[0x4e] ^= 0x01;
+ File(target).writeAsBytesSync(Uint8List.sublistView(bytes, 0, offset));
+}
+
+void main() {
+ late Directory scratch;
+ late String signed;
+ late String unsigned;
+ late String staged;
+ late String launcher;
+
+ setUp(() async {
+ if (!Platform.isWindows) return;
+ scratch = Directory.systemTemp.createTempSync('update-sig-');
+ signed = p.join(scratch.path, 'running', 'harness-desktop.exe');
+ Directory(p.dirname(signed)).createSync();
+ File(await _embeddedSignedProgram()).copySync(signed);
+ unsigned = p.join(scratch.path, 'unsigned', 'harness-desktop.exe');
+ Directory(p.dirname(unsigned)).createSync();
+ _stripSignature(signed, unsigned);
+ staged = p.join(scratch.path, 'app', '9.9.9.staging');
+ Directory(p.join(staged, 'data')).createSync(recursive: true);
+ File(signed).copySync(p.join(staged, 'harness-desktop.exe'));
+ File(p.join(staged, 'data', 'app.so')).writeAsStringSync('dart code');
+ launcher = p.join(scratch.path, 'Harness.exe.new');
+ File(signed).copySync(launcher);
+ });
+ tearDown(() {
+ if (Platform.isWindows) scratch.deleteSync(recursive: true);
+ });
+
+ Future<WindowsSignatureReport> report({String? running}) =>
+ readWindowsSignatureReport(
+ stagedFolder: staged,
+ stagedLauncher: launcher,
+ runningExe: running ?? signed,
+ );
+
+ // As the release does: over app/<version>, which the updater unpacks
+ // as app/<version>.staging.
+ Future<void> writeCatalog() {
+ final built = p.join(p.dirname(staged), '9.9.9');
+ return _powershell(
+ "Rename-Item -LiteralPath '$staged' -NewName '9.9.9'; "
+ "New-FileCatalog -CatalogVersion 2.0 -Path '$built' "
+ "-CatalogFilePath '${scratch.path}\\c.cat' | Out-Null; "
+ "Move-Item -LiteralPath '${scratch.path}\\c.cat' "
+ "-Destination '$built\\harness-desktop.cat'; "
+ "Rename-Item -LiteralPath '$built' -NewName '9.9.9.staging'",
+ );
+ }
+
+ test(
+ 'the report reads who signed each program and the running app',
+ () async {
+ _stripSignature(signed, p.join(staged, 'extra.dll'));
+ final found = await report();
+ expect(found.running.status, 'Valid');
+ expect(found.running.subject, contains('Microsoft'));
+ expect(found.runningFolder.keys, contains('harness-desktop.exe'));
+ expect(found.files['harness-desktop.exe']!.sameAs(found.running), isTrue);
+ expect(found.files['Harness.exe']!.sameAs(found.running), isTrue);
+ expect(found.files['extra.dll']!.status, 'NotSigned');
+ expect(found.files.keys, isNot(contains('data/app.so')));
+ expect(found.catalog, isNull);
+ // The staged app's own version, which must be the manifest's.
+ final productVersion = await _powershell(
+ "(Get-Item -LiteralPath '${p.join(staged, 'harness-desktop.exe')}')"
+ '.VersionInfo.ProductVersion',
+ );
+ expect(productVersion, isNotEmpty);
+ expect(found.stagedVersion, productVersion);
+ },
+ skip: _windowsOnly,
+ );
+
+ test('one program in a folder still reads as a list', () async {
+ final found = await report(running: unsigned);
+ expect(found.runningFolder.keys, ['harness-desktop.exe']);
+ expect(
+ found.files.keys,
+ unorderedEquals(['harness-desktop.exe', 'Harness.exe']),
+ );
+ }, skip: _windowsOnly);
+
+ test('a changed program reads as changed, not as signed', () async {
+ final copy = File(p.join(staged, 'harness-desktop.exe'));
+ final bytes = copy.readAsBytesSync();
+ bytes[bytes.length ~/ 2] ^= 0xff;
+ copy.writeAsBytesSync(bytes);
+ final found = await report();
+ expect(found.files['harness-desktop.exe']!.valid, isFalse);
+ }, skip: _windowsOnly);
+
+ test('the catalog covers app.so: a changed or extra file fails it', () async {
+ await writeCatalog();
+ var found = await report();
+ expect(found.catalog!.status, 'Valid');
+ expect(found.catalog!.signer.status, 'NotSigned');
+
+ File(p.join(staged, 'data', 'app.so')).writeAsStringSync('other code');
+ found = await report();
+ expect(found.catalog!.status, 'ValidationFailed');
+
+ File(p.join(staged, 'data', 'app.so')).writeAsStringSync('dart code');
+ File(p.join(staged, 'data', 'extra.bin')).writeAsStringSync('more');
+ found = await report();
+ expect(found.catalog!.status, 'ValidationFailed');
+ }, skip: _windowsOnly);
+
+ // Run 42354774882 refused both of these for the wrong reason ("the update
+ // has no harness-desktop.exe"): the log says which rule refused.
+ test('an unsigned catalog is refused, in plain words', () async {
+ await writeCatalog();
+ final logged = await _logged(
+ () => expectLater(
+ verifyWindowsUpdate(
+ stagedFolder: staged,
+ stagedLauncher: launcher,
+ runningExe: signed,
+ version: '9.9.9',
+ ),
+ throwsA(
+ isA<UpdateRefused>().having(
+ (e) => e.message,
+ 'message',
+ contains('not signed by Microsoft'),
+ ),
+ ),
+ ),
+ );
+ expect(
+ logged,
+ contains(contains('refused: the file catalog is signed by')),
+ );
+ }, skip: _windowsOnly);
+
+ test('an unsigned program is refused', () async {
+ await writeCatalog();
+ _stripSignature(signed, launcher);
+ final logged = await _logged(
+ () => expectLater(
+ verifyWindowsUpdate(
+ stagedFolder: staged,
+ stagedLauncher: launcher,
+ runningExe: signed,
+ version: '9.9.9',
+ ),
+ throwsA(isA<UpdateRefused>()),
+ ),
+ );
+ expect(
+ logged,
+ contains(contains('refused: Harness.exe signature is NotSigned')),
+ );
+ }, skip: _windowsOnly);
+
+ test(
+ 'a running app that is itself unsigned keeps the sha256 check alone',
+ () async {
+ _stripSignature(signed, launcher);
+ await verifyWindowsUpdate(
+ stagedFolder: staged,
+ stagedLauncher: launcher,
+ runningExe: unsigned,
+ version: '9.9.9',
+ );
+ },
+ skip: _windowsOnly,
+ );
+
+ test('a check that runs out of time refuses', () async {
+ await expectLater(
+ verifyWindowsUpdate(
+ stagedFolder: staged,
+ stagedLauncher: launcher,
+ runningExe: signed,
+ version: '9.9.9',
+ timeout: Duration.zero,
+ ),
+ throwsA(
+ isA<UpdateRefused>().having(
+ (e) => e.message,
+ 'message',
+ contains('could not check'),
+ ),
+ ),
+ );
+ }, skip: _windowsOnly);
+}
diff --git a/docs/plans/2026-11-07-desktop-update-signature-plan.md b/docs/plans/2026-11-07-desktop-update-signature-plan.md
new file mode 100644
index 000000000..888806350
--- /dev/null
+++ b/docs/plans/2026-11-07-desktop-update-signature-plan.md
@@ -0,0 +1,172 @@
+# Desktop Update Signature Implementation Plan
+
+> Task #4435. Written by the writing-plans skill as this project's Engineer works: one Engineer implements it task by
+> task, test first, and the pull request's review is the one independent review.
+
+**Goal:** The Desktop updater installs a build only when the same publisher that signed the running app signed it, so a
+wrong manifest (right sha256, wrong build) is refused on macOS and Windows.
+
+**Architecture:** One new file, `desktop/lib/update/update_signature.dart`, holds the rule and the two OS checks; the
+updater calls it once the download is unpacked and before anything is installed. macOS asks `codesign` to check the
+staged bundle against a Developer ID requirement built from the running app's own team and identifier, `notarized`
+included. Windows asks a hidden PowerShell for the Authenticode signer of every `.exe` and `.dll` and for a signed file
+catalog that covers the whole version folder (the Dart code is `data/app.so`, which Authenticode cannot sign), and the
+rule compares them with the running app's signer in Dart. The release signs that catalog.
+
+**Tech Stack:** Dart/Flutter (desktop), `/usr/bin/codesign`, Windows PowerShell 5.1 (`Get-AuthenticodeSignature`,
+`New-FileCatalog`, `Test-FileCatalog`), GitHub Actions (release-desktop.yml, windows-signing action).
+
+**Spec:** the task brief (#4435). Verified on main 610ccb05c and the published 1.3.89 packages, 2026-11-07:
+
+1. `downloadAndStage` (desktop_updater.dart:435) checks size and sha256, then unpacks; nothing checks a signature.
+2. macOS 1.3.89 (`Harness-macos-arm64.zip`): Developer ID Application: Autonomous Inc. (54DJVWMJCC), identifier
+ `ai.autonomous.harness`, hardened runtime, notarized and stapled. `codesign --verify --deep --strict -R='anchor apple
+ generic and certificate 1[field.1.2.840.113635.100.6.2.6] and certificate leaf[field.1.2.840.113635.100.6.1.13] and
+ certificate leaf[subject.OU] = "54DJVWMJCC" and notarized'` passes in 1.3 s; an ad-hoc copy, a tampered copy and
+ another team's app fail.
+3. Windows 1.3.89 (`Harness-windows-x64.zip`, signing `required` since 2026-11-03): `Harness.exe`, `harness-desktop.exe`
+ and every plugin DLL are signed `C=US, ST=California, L=Redlands, O=AUTONOMOUS INC., CN=AUTONOMOUS INC.`, leaf valid
+ 3 days, with the Artifact Signing identity EKU `1.3.6.1.4.1.311.97.585055327.208923272.208213867.148721407`;
+ `WebView2Loader.dll` is signed by Microsoft Corporation. `data/app.so`, `icudtl.dat` and `flutter_assets/` carry no
+ signature.
+4. Windows staging builds (windows-desktop.yml release mode) and local macOS builds are unsigned or ad-hoc.
+
+## Global Constraints
+
+- Desktop only for app code; the release change is the Windows signing job and action that already sign Desktop.
+- Never read a signing secret. Tests sign nothing with a real identity: ad-hoc and unsigned fixtures only.
+- Must not break the update from 1.3.89 to the next release: 1.3.89 runs the old updater, which accepts any extra file
+ under `app/<version>/`, so the catalog is invisible to it.
+- Windows rules: every child process through `startHidden` (`lib/core/hidden_process.dart`); no window opens.
+- Every wait has a timeout (60 s); a check that cannot finish refuses the update.
+- Copy is plain words, shown in the update banner through the existing `updateError`.
+
+## The rule
+
+- The running app's signer is read from the running app: macOS team ID + bundle identifier (`codesign -dv`), Windows
+ certificate subject + Artifact Signing identity EKUs (`Get-AuthenticodeSignature` on the running
+ `harness-desktop.exe`).
+- A running app that is verifiably unsigned (macOS ad-hoc or no signature, Windows `NotSigned`) has no signer to match;
+ it keeps today's sha256-only behaviour and logs that. Only dev and staging builds are unsigned, so this never weakens
+ a released install, and once an install is signed it accepts only signed updates.
+- Anything else that fails to read the running signer refuses the update.
+- macOS: the staged bundle must satisfy the Developer ID requirement with the running team and identifier, deep and
+ strict, and `notarized`.
+- Windows: every staged `.exe`/`.dll` and the staged launcher must be `Valid`; `harness-desktop.exe`, `Harness.exe` and
+ the catalog must have the running signer; any other file may also have a signer one of the running version folder's
+ own files has (Microsoft for `WebView2Loader.dll`). The catalog `app/<version>/harness-desktop.cat` must exist and
+ `Test-FileCatalog` must say `Valid` (every file listed, none changed, none extra).
+
+## Key rotation
+
+- macOS: a new Developer ID certificate under the same team changes nothing. A new team: one bridge release, signed by
+ the old team, whose rule also accepts the new team ID; releases after it are signed by the new team.
+- Windows: Artifact Signing's 3-day certificates rotate by themselves; the rule compares the subject and the identity
+ EKU, never a thumbprint. Renewing the identity validation keeps the EKU. A new identity validation (new EKU or
+ subject): the same bridge release, accepting the next identity as well.
+
+## Review Focus
+
+- A running app whose signer cannot be read (codesign or PowerShell missing, times out, prints nothing): refused, not
+ treated as unsigned. Test: `readMacSigner` on a missing path and a runner that times out → refusal.
+- A package with one extra unsigned DLL or a changed `app.so` but valid signed exes: refused. Test: Windows rule with an
+ extra `NotSigned` file, and catalog status `ValidationFailed`.
+- Same team, different app (`identifier` differs): refused. Test: requirement contains the identifier.
+- Refusal leaves the current version untouched and removes the staged files. Test: Windows `current` unchanged and the
+ attempt folder gone after a refusal.
+- The 1.3.89 → next update: nothing in 1.3.89's path changes. Test: the existing staging tests still pass with the
+ catalog entry present in the zip.
+
+---
+
+### Task 1: The rule (pure Dart, any OS)
+
+**Files:**
+- Create: `desktop/lib/update/update_signature.dart`
+- Test: `desktop/test/update_signature_test.dart`
+
+**Interfaces:**
+- Produces: `class UpdateRefused implements Exception { final String message; }` (`toString()` is the message);
+ `class MacSigner { team, identifier, name }`, `MacSigner? parseMacSigner(String codesignDv)` (null = unsigned/ad-hoc),
+ `String macUpdateRequirement(MacSigner)`;
+ `class WindowsSigner { status, subject, identity }`, `class WindowsSignatureReport { running, runningFolder, files,
+ catalog }` with `fromJson`, `String? windowsUpdateRefusal(WindowsSignatureReport, {version})` (null = accept).
+
+- [ ] **Step 1: Write the failing tests:** `parseMacSigner` reads team, identifier and the Developer ID name from the
+ 1.3.89 `codesign -dv --verbose=2` text, and returns null for `Signature=adhoc` and for "code object is not signed at
+ all"; `macUpdateRequirement` holds the anchor, both Developer ID fields, the team, the identifier and `notarized`;
+ `windowsUpdateRefusal` accepts the 1.3.89 shape (AUTONOMOUS files + Microsoft WebView2Loader, catalog Valid by
+ AUTONOMOUS), and refuses: an extra `NotSigned` dll; `harness-desktop.exe` signed by Microsoft; a different identity
+ EKU with the same subject; catalog missing; catalog `ValidationFailed`; catalog `NotSigned`; running status
+ `HashMismatch`. Running `NotSigned` → accept.
+- [ ] **Step 2: Run** `flutter test test/update_signature_test.dart` → fails to compile (no file).
+- [ ] **Step 3: Implement** the types and functions.
+- [ ] **Step 4: Run** the same → PASS.
+- [ ] **Step 5: Commit** (test first, then code).
+
+### Task 2: The macOS check
+
+**Files:**
+- Modify: `desktop/lib/update/update_signature.dart`
+- Test: `desktop/test/update_signature_macos_test.dart` (skipped off macOS)
+
+**Interfaces:**
+- Produces: `Future<void> verifyMacUpdate({required String stagedBundle, required String runningBundle, String
+ version, Duration timeout})` throwing `UpdateRefused`.
+
+- [ ] **Step 1: Write the failing tests** with fixtures built in the test (a tiny bundle whose executable is a copy of
+ `/usr/bin/true`): unsigned staged → refused; ad-hoc staged → refused; running ad-hoc → accepted (no signer); and,
+ when a notarized Developer ID Harness is on the machine (`HARNESS_SIGNED_APP_FIXTURE`, else
+ `/Applications/Harness.app` if it verifies), a clone of it → accepted, a tampered clone → refused, the unsigned
+ fixture against it → refused.
+- [ ] **Step 2: Run** `flutter test test/update_signature_macos_test.dart` → fails (no `verifyMacUpdate`).
+- [ ] **Step 3: Implement** with `codesign -dv --verbose=2` on the running bundle and `codesign --verify --deep
+ --strict -R=<requirement>` on the staged one, both through one timed runner.
+- [ ] **Step 4: Run** → PASS. **Step 5: Commit.**
+
+### Task 3: The Windows check
+
+**Files:**
+- Modify: `desktop/lib/update/update_signature.dart`
+- Test: `desktop/test/update_signature_windows_test.dart` (skipped off Windows)
+
+**Interfaces:**
+- Produces: `Future<void> verifyWindowsUpdate({required String stagedFolder, required String stagedLauncher, required
+ String runningExe, String version, Duration timeout})` throwing `UpdateRefused`; the PowerShell script reads paths
+ from environment variables and prints one JSON `WindowsSignatureReport`.
+
+- [ ] **Step 1: Write the failing tests:** running = a Microsoft-signed system exe, staged folder with a copy of it and
+ an unsigned dll → refused naming the dll; a folder with a `New-FileCatalog` catalog (unsigned) → refused for the
+ catalog; the report reads `Valid` and the Microsoft subject for the system exe; running = an unsigned exe → accepted.
+ The PowerShell runs through `startHidden`.
+- [ ] **Step 2–5:** run → fails; implement; run → PASS (Windows CI or a Windows machine); commit.
+
+### Task 4: The updater refuses, cleans up and says why
+
+**Files:**
+- Modify: `desktop/lib/update/desktop_updater.dart`, `desktop/lib/update/windows_update_swap.dart` (staged paths)
+- Test: `desktop/test/desktop_updater_test.dart`
+
+**Interfaces:**
+- Consumes: `verifyMacUpdate`, `verifyWindowsUpdate`, `UpdateRefused`.
+- Produces: `DesktopUpdater({... Future<void> Function(String staged)? verifySignature})`; `downloadAndStage` throws
+ `UpdateRefused` after deleting what it staged; `WindowsUpdateSwap.stagedFolder` / `stagedLauncher`.
+
+- [ ] **Step 1: Write the failing tests:** macOS and Windows staging with a `verifySignature` that throws → the call
+ throws `UpdateRefused`, the staging dir is gone, Windows `current` still names the old version; the verifier
+ receives the staged bundle (macOS) and the staged folder (Windows). Existing staging tests pass an accepting verifier.
+- [ ] **Step 2–5:** run → fails; wire the check in after the version check (macOS) and after `swap.stage` (Windows);
+ run `flutter test test/desktop_updater_test.dart test/windows_update_swap_test.dart` → PASS; commit. The banner
+ already shows `Could not install Harness X: <message>` through the generic catch in `app_state.dart`.
+
+### Task 5: The release signs a catalog
+
+**Files:**
+- Modify: `.github/workflows/release-desktop.yml` (`sign-windows`), `.github/actions/windows-signing/action.yml`
+ (`.cat` beside `.exe`/`.dll`), `desktop/RELEASE.md`, `docs/windows-code-signing.md`, `desktop/CLAUDE.md`
+
+- [ ] **Step 1:** after the first signing pass, `New-FileCatalog -CatalogVersion 2.0` over each `app/<version>` folder
+ into `harness-desktop.cat` (written outside, then moved in), a second signing pass signs it, and `Test-FileCatalog`
+ must say `Valid` before the zips are written again.
+- [ ] **Step 2:** `actionlint` both workflows; docs say what the updater checks and how rotation works.
+- [ ] **Step 3: Commit.**
diff --git a/docs/windows-code-signing.md b/docs/windows-code-signing.md
index 86909fb60..51ecb20c4 100644
--- a/docs/windows-code-signing.md
+++ b/docs/windows-code-signing.md
@@ -12,7 +12,7 @@ and Windows ships unsigned, exactly as before this change.
| Release | Job | Files |
| --- | --- | --- |
-| Desktop (`release-desktop.yml`) | `sign-windows` | every `.exe` and `.dll` in `Harness-windows-x64.zip` and `Harness-windows-arm64.zip` (`Harness.exe`, `harness-desktop.exe`, `harness_pipe_io.dll`, Flutter's and the plugins' DLLs), and `harness-install.exe` |
+| Desktop (`release-desktop.yml`) | `sign-windows` | every `.exe` and `.dll` in `Harness-windows-x64.zip` and `Harness-windows-arm64.zip` (`Harness.exe`, `harness-desktop.exe`, `harness_pipe_io.dll`, Flutter's and the plugins' DLLs), then `app/<version>/harness-desktop.cat`, a catalog of every file in the version folder, and `harness-install.exe` |
| CLI (`release.yml`) | `pty-sign` | `harness-pty.exe`, `harness-launch.exe`, `harness.exe`, `harness-serial.exe` for x64 and arm64 |
A file that already carries a valid signature keeps it: Microsoft's `conpty.dll` and `OpenConsole.exe` are not
@@ -37,6 +37,10 @@ pty-build (x64, arm64) ──> pty-sign (x64 only) ──────> windows-s
4. Verify every `.exe` and `.dll` with `Get-AuthenticodeSignature`. Each needs status Valid and a timestamp, and
each one we signed must name `WINDOWS_SIGNING_PUBLISHER`. The check uses the publisher name, not a thumbprint,
because the certificate changes every few days.
+- **The Desktop catalog.** `data/app.so` (the Dart code), `icudtl.dat` and `flutter_assets/` cannot carry an
+ Authenticode signature, so after the programs are signed `New-FileCatalog -CatalogVersion 2.0` lists every file of
+ `app/<version>/` by hash in `harness-desktop.cat`, a second pass of the action signs it, and `Test-FileCatalog` must
+ say Valid. The updater refuses a version folder without it (`desktop/lib/update/update_signature.dart`).
- **Desktop zips are opened, signed and written again** with the entries `package-windows.ps1` writes, under the same
artifact names (`overwrite: true`). `upload-windows` and `check-windows-zip.py` are unchanged. The manifest's
sha256 is the hash of the signed bytes.
@@ -148,8 +152,8 @@ unsigned again. Files already published stay validly signed, because each signat
## Not covered yet
-- **The updater and `harness-install.exe` do not check the publisher** of what they download; they rely on sha256
- from the manifest. Requiring an AUTONOMOUS INC. signature there is a separate change for after signing is live.
+- **`harness-install.exe` does not check the publisher** of the zip it downloads; it relies on sha256 from the manifest.
+ The Desktop updater does (#4435): it installs a version only when it is signed like the running app.
- **`windows-desktop.yml`'s staging release mode** builds unsigned staging packages. Add the same signing job there
if staging E2E should cover signed files.
- **The Windows Node runtime** (`release-node-runtime-windows.yml`) republishes nodejs.org's `node.exe`, which the