Skip to content

fix(computers): keep pairing across updates and restarts - #573

Merged
nixuuu merged 1 commit into
devfrom
fix/pairing-survives-updates
Nov 12, 2026
Merged

nixuuu merged 1 commit into
devfrom
fix/pairing-survives-updates

Conversation

@nixuuu

@nixuuu nixuuu commented Nov 12, 2026 •

Copy link
Copy Markdown
Member

An update or restart can surface an authentication failure as “Pair again” even when the saved computer identity has not changed. Reconnect now treats RPC authentication failures as retryable and requires repeated, locally verified TLS pin mismatches before requesting new trust. A successful handshake with the saved identity clears stale pairing state.

Investigation

Changes

  • Use a local CertificatePinMismatch signal emitted only after TLS proof of possession and validation of a different self-signed certificate. Override ConnectError's inherited structural Symbol.hasInstance check so ordinary RPC errors cannot impersonate this local class. Without this override the new LAN test correctly caught a real route-deletion bug, not test timing. Invalid/expired certificates remain rejected without declaring an identity change.
  • Exhaust routes first. Require the same different certificate at the same manual route in two consecutive failed rounds. A matching pinned TLS connection or ready incoming link outweighs stale addresses. Only a verified pin mismatch removes a discovered LAN route. Saved pins are never replaced automatically.
  • Clear confirmation evidence after pinned TLS verification, a successful handshake, explicit pairing, route edits and unlink. Existing successful handshake recovery also clears a persisted pairing_required after restart.
  • Use the shared reason “{name}'s identity changed. Pair again to trust it.” for linked computer availability and app updates, including the relay's name when its identity changed. Remove the contradictory automatic-retry explanation for that state. Add stable auth-failure classifications to diagnostics without logging certificates, keys, addresses or RPC payloads.
  • Document persistence and recovery. No proto changes, protocol bump or migration.

Regression coverage

Added gateway↔gateway integration scenarios using independent databases and real TLS listeners:

  1. Repeated startup Unauthenticated on manual and LAN routes preserves trust and resumes; verify the LAN route remains after each attempt. RPC error text cannot impersonate a local pin mismatch, and failed TLS connections cannot confirm a manual route's identity change.
  2. An early listener returns Unavailable for both Pair and Connect until ready.
  3. Both gateway/core restarts reuse persisted identities/certificates and reconnect; a protocol-1 .133 hello without new capabilities links with a .137 hello and resumes after upgrading.
  4. A real new key requires confirmed pairing, receives no RPC, never replaces the pin, and has consistent availability/update explanations.
  5. A persisted stale pairing state heals after restart; a valid alternate route outweighs a stale manual address with another key.

The older-version scenario exercises the compatible wire hello/capability set, not archived app binaries. Installer and OS keychain behavior was inspected in source, not exercised on macOS/Windows.

Validation

  • After maintainer clearance, ran only the two authorized test files, sequentially, at nice -n 19, using TMPDIR=/var/tmp and bun run check:tmp: linked-pairing-recovery.test.ts 10 pass, linked-capability-compatibility.test.ts 3 pass. Both temp-directory checks passed. The original LAN failure reproduced before the fix (8 pass / 1 fail); the strengthened assertion confirmed deletion immediately after the first auth failure.
  • Changed-file formatting and lint passed; git diff --check is clean. Earlier dependency install and repository formatting/lint checks passed before the original push.
  • CI validates generation, full typechecking, all test shards and builds for the rebased head. Browser verification remains pending; the UI change reuses existing components and only changes status explanations.

Copy audit (§8)

“{name} must be paired again” / “Link it again…” / “unavailable, trying again automatically” → “{name}'s identity changed. Pair again to trust it.” The text states the verified problem and the explicit trust action, uses two short sentences and avoids TLS jargon. The compact action badge remains “Pair again”. Names are interpolated as whole values and existing wrapping/layout remains in place; short/long-name checks at desktop/phone widths have not been run yet.

Related: #13

@nixuuu
nixuuu marked this pull request as ready for review November 12, 2026 14:44
@nixuuu

nixuuu commented Nov 12, 2026

Copy link
Copy Markdown
Member Author

Static follow-up found a deterministic .133 → .137 handshake regression, beyond the status misclassification fixed here: the full desktop advertises 33 capabilities, but validateHello() permits only 32 and throws Unauthenticated: Invalid computer identity.

  1. Exact release boundary. .133 runtime-presence.ts:82–118 advertises 4 base + 25 serving + config + moves + updates = 32 capabilities. .137:83–120 advertises 4 + 26 + 3 = 33. #559 / 2adcbc0c6 adds REMOTE_THREAD_PANEL. The production constructor supplies serve, shared, core and updates (start.ts:26–37), enabling every conditional item. Both .133 store.ts:178–185 and .137 store.ts:178–185 reject this list. The handshake invokes that validator after TLS pin authentication; the old dial catch:285–293 then converts this RPC rejection into pairing_required on the manual route. Updating forces the handshake to run again; changing certificates is unnecessary to trigger it. My initial investigation missed this payload-size boundary. fix(computers): keep pairing across updates and restarts #573 alone changes the warning to retrying but cannot repair these handshakes.

  2. Listener before credentials/peers: not the normal production path. main.ts:56–64 awaits migrations and owner lookup; main.ts:126–131 awaits computer-link startup before network.start(). runtime-presence.ts:126–143 loads the identity and peers. network.ts:88–93 also awaits identity/settings before opening TLS. Peer authentication queries Postgres directly, not an asynchronously populated credential cache. No listener yields a connection failure; a database error propagates as an operation failure, not an empty peer cache. fix(computers): keep pairing across updates and restarts #573 adds an explicit early/stopping Unavailable guard as defense in depth.

  3. Swapping a serving gateway binary: not how desktop updates install. runtime.ts:64–65 marks the bundled services desktop, excluding standalone self-update. main.ts:278–321 announces updating, closes controller stdin and calls updates.install() only after the controller exits. controller.ts:80–106 stops the runtime on EOF (or kills its owned groups at the deadline); process.ts:146–162 waits for service exits in reverse order. The installer boundary runs afterwards. While draining, the old listener authenticates against the same persisted identity; after shutdown the socket is unavailable.

  4. Version-dependent identity path: not found. identity.ts:6–8,33–39 fixes the data directory to Canopy; main.ts:39–42 fixes the app/keychain name before opening it. runtime.ts:221–236 always uses that directory's postgres; database.ts:18–21 reuses data/PG_VERSION. ComputerStore.identity():64–88 reuses the certificate and encrypted key; it generates only when the row is absent and does not replace identity on decryption failure.

  5. macOS keychain denial after signing changes: cannot produce this serving-peer auth rejection through the normal startup path. vault.ts:20–44 checks availability and awaits decryption without catching denial or creating replacement secrets; re-encryption preserves the decrypted values. New secrets are generated only when the file is absent (47–54). main.ts:440–449 awaits that operation before spawning the controller, so denial stops startup before a gateway/listener exists. Source inspection cannot establish whether macOS actually denied access on the maintainer's machine; it establishes that this path does not silently rotate the TLS identity.

I am preparing the requested follow-up PR for the capability overflow, including compatibility with the unchanged 32-entry validator on .133. Merely raising the new validator's limit would still leave .133 rejecting the newer side. No local tests or servers have been run. The 33-entry regression is established statically for the full desktop configuration; without incident logs, I cannot claim it explains every earlier report or the reported success of re-pairing (the same validator also runs during pairing).

@nixuuu

nixuuu commented Nov 12, 2026

Copy link
Copy Markdown
Member Author

The requested follow-up is now open: #574, head 3edff6fca. It repairs the 33-capability handshake regression introduced by #559, independently of this PR's auth-error classification fix. Both fixes are needed for the full desktop configuration: #573 alone would leave the peer retrying a hello that .133 rejects.

The follow-up splits every outgoing hello at 32 entries, retains the original configuration/move/update features in that prefix, and combines both fields under a bounded receiver limit. Older peers ignore the additive overflow field; new peers also accept unfixed .137 hellos with all 33 entries in field 7. No new identity is trusted automatically.

The new integration coverage uses the complete production desktop constructor, includes both gateways restarting on their existing databases, and exercises the old 32-entry guard rather than only changing an app-version string. It emulates the older decoder/validator; it does not launch a released desktop binary. No local tests or servers were run; execution and repository checks are left to CI.

The static conclusion remains: this exact release pair has a deterministic capability-count rejection after successful TLS pin verification. The traced normal startup/update/keychain paths do not silently rotate the identity or open a listener before secrets load. Without production logs, that does not establish the cause of every earlier update report or explain why re-pairing succeeded on the reported machine.

nixuuu added a commit that referenced this pull request Nov 12, 2026
The full desktop hello grew from 32 capabilities in nightly.133 to 33 in
nightly.137 when #559 added `remote_thread_panel_v1`. Both versions
reject more than 32 as `Unauthenticated: Invalid computer identity`, so
an update reconnect can fail after TLS pin authentication succeeds. #573
prevents the false pairing warning, but does not repair this handshake
failure.

Keep the original nightly.133 capabilities in field 7 (at most 32
entries) and send subsequent capabilities in additive
`NodeHello.additional_capabilities` (field 8). Older peers ignore field
8 and keep all their existing configuration, move and update
capabilities. New peers combine both fields before negotiation and
accept unfixed nightly.137 hellos containing 33 entries in field 7.
Bound the combined list at 128 and reject overflow with
`InvalidArgument`. Pair requests/responses, connect, welcome and rename
broadcasts all use the same encoding. TLS pins, certificate verification
and owner scoping retain their existing checks.

Added gateway-to-gateway integration coverage using the actual desktop
`startComputerLinks` constructor, which enables every production
capability:

- Complete production pairing, followed by restarting both gateways on
their existing databases; compare pins and full negotiated capabilities.
- Raw unfixed 33-entry Pair and Connect requests over pinned TLS, plus
malformed overflow rejection without changing persisted trust.
- Mixed-version pairing in both directions and rename handshakes against
the nightly.133 32-entry guard and unknown-field behavior. This fixture
emulates the old decoder/validator; it does not run a released desktop
binary.

Validation: generated protobuf bindings with `bun run gen`; formatted
changed source files; `git diff --check` is clean. No local tests,
typecheck, lint, build, servers or Docker runs: the maintainer has a
performance measurement running and requested CI-only execution. CI must
validate the new coverage and repository gates. No UI copy changed.

Static investigation and startup/updater/keychain evidence:
#573 (comment).
The source establishes this release regression in the full desktop
configuration; incident logs would be needed to attribute every earlier
report or explain successful re-pairing under a different configuration.

Fixes: #559
Related: #573
Separate locally verified TLS pin mismatches from retryable RPC authentication failures. Confirm changed certificates across failed route rounds, preserve pinned identities through restarts, and explain identity changes consistently.

Add gateway-to-gateway restart, authentication recovery, legacy capability and trust regression coverage. Local tests await maintainer clearance; lint and formatting pass.

Related: #13
@nixuuu
nixuuu force-pushed the fix/pairing-survives-updates branch from 31bd38b to 8cbb63f Compare November 12, 2026 15:13
@nixuuu

nixuuu commented Nov 12, 2026

Copy link
Copy Markdown
Member Author

Rebased onto origin/dev with merged #574 and pushed 8cbb63f05. Git applied the overlapping hello changes cleanly; the capability splitting/normalization is preserved.

The repeated CI failure was a real route-retention bug, not timing. Connect's ConnectError defines a structural Symbol.hasInstance; the new CertificatePinMismatch extends ConnectError inherited it, so error instanceof CertificatePinMismatch incorrectly matched ordinary RPC errors. A transient auth failure therefore deleted the LAN route after the first attempt, leaving only one call for the test's two dials. The same misclassification could also accumulate false identity-change evidence from failed TLS connections on manual routes.

The mismatch class now overrides that check to require its own local prototype (transport.ts:27–34). This retains Connect error handling while ensuring RPC status/messages cannot produce the local TLS proof. Strengthened the LAN regression to check route retention after the first attempt and added a repeated failed-TLS/manual-route scenario. The existing real-key-change/no-auto-trust scenario still passes.

Authorized local verification ran sequentially, one file at a time, at nice -n 19, with TMPDIR=/var/tmp and the temp-directory gate:

  • Before fix: pairing recovery 8 passed / 1 failed, reproducing CI; an isolated assertion confirmed the route was already gone after the first auth error.
  • After fix: pairing recovery 10 passed / 0 failed, temp directory clean.
  • Rebased capability compatibility: 3 passed / 0 failed, temp directory clean.
  • Changed-file formatting and lint passed; git diff --check is clean.

The full checks are running in CI for the new head. No other local test files were run.

@nixuuu
nixuuu merged commit 12a6346 into dev Nov 12, 2026
22 of 26 checks passed
@nixuuu
nixuuu deleted the fix/pairing-survives-updates branch November 12, 2026 15:58
nixuuu added a commit that referenced this pull request Nov 12, 2026
The cross-version pairing recovery test read B's saved version
immediately after observing A's `connected` status. In both failed #573
runs it expected `0.2.0-nightly.137` and received the pairing-time
`0.0.0-dev`. A can finish processing B's hello while B is still
processing A's welcome, so A's status is not a barrier for B's database
write.

This is test timing. Each side already awaits its [hello metadata
write](https://github.com/itsoltech/canopy/blob/12a6346b262c50e2d8fbabfcb63689bffcf75822/apps/gateway/src/computers/runtime-frames.ts#L255-L267)
before publishing its own [connected
status](https://github.com/itsoltech/canopy/blob/12a6346b262c50e2d8fbabfcb63689bffcf75822/apps/gateway/src/computers/runtime-frames.ts#L316-L321).
A [queues its
welcome](https://github.com/itsoltech/canopy/blob/12a6346b262c50e2d8fbabfcb63689bffcf75822/apps/gateway/src/computers/runtime-frames.ts#L284-L288)
before that status write; completion across the two independent gateways
is asynchronous.

Let the online helper wait for a specified peer/store, and wait for both
sides before reading their final versions. Add a controlled barrier
around B's metadata write and force the B → A dial after listener
startup. The test now proves A can be connected while B still holds the
old version, releases B, then waits for B's own connected commit. It
retains the trust, protocol, version and upgraded-capability assertions.
No sleeps, larger timeouts or assertion retries were added to hide the
ordering.

Evidence from the original failures: [attempt 1 / job
131276846769](https://github.com/itsoltech/canopy/actions/runs/43245418155/job/131276846769),
[attempt 2 / job
131286358670](https://github.com/itsoltech/canopy/actions/runs/43245418155/job/131286358670),
both at `linked-pairing-recovery.test.ts:267`.

Validation on the authorized file only, sequentially with
`TMPDIR=/var/tmp nice -n 19 bun run check:tmp`:

- Complete file: **10 passed**, temp directory clean.
- Forced-order scenario with `--rerun-each 10`: **10 passed**, temp
directory clean.
- Changed-file lint, formatting and `git diff --check` passed.

Required CI validation: two complete consecutive green attempts for the
same head, rerunning the entire workflow once after the first green
result. This is pending; local repetition is not counted as CI evidence.

Related: #573
nixuuu added a commit that referenced this pull request Nov 12, 2026
The pairing suite could leave a deliberately persisted
`pairing_required` untouched when restoring the original peer. Its
shared fixture starts the runtime before the listener
(`tests/integration/support/computers.ts:42`), so a startup dial races
the listener's first address announcement. That announcement retires
sockets and aborts dials
(`apps/gateway/src/computers/runtime-lan.ts:51`). The suite's single
reconnect tick can observe the closing incoming connection and skip
dialing (`apps/gateway/src/computers/runtime-connection.ts:149`); its
next automatic retry is deliberately 60 seconds away, beyond the
5-second assertion window.

This is fixture timing. The #579 failure occurs in `restoreB()`, after
the test intentionally sets `pairing_required`, not in shared setup or a
previous test. The failed job shows two expected `server_pin_mismatch`
probes followed by an aborted startup connection and no subsequent
successful handshake. Self-heal writes `connected` only after a
successful pinned handshake
(`apps/gateway/src/computers/runtime-frames.ts:316–321`). There is no
evidence here of that write being overwritten.

Pause dialing during fixture startup until its listener and initial
address publication have completed. Explicit ticks then establish links,
and shared setup/recovery wait for each gateway's own committed
connected status. Preserve the cross-version metadata barrier, remove
its route-deletion workaround, and extend the persisted-state recovery
case with a barrier holding listener startup open.

Validation:
- With the previous startup helper, the controlled barrier fails
deterministically: expected zero startup dials, received one.
- Five consecutive complete file runs with `TMPDIR=/var/tmp nice -n 19
bun run check:tmp ./tests/integration/linked-pairing-recovery.test.ts`:
**10 passed, 0 failed each time** (50 test executions), each about 4.4
seconds; every temp-directory check passed.
- Changed-file formatting, lint and `git diff --check` pass. No other
local tests run.
- Pending: two complete consecutive green CI attempts on the same head,
rerunning the entire workflow once.

Related: #573
Related: #575
Related: #579
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant