Continue work on Cthulhu Remote.
This commit is contained in:
1 parent
63e84e9ac7
commit
0c74038c49
16 files changed
+2896
-30
No files matched your search
@@ -83,6 +83,68 @@ The complete Remote race suite and Tentacles `make check` passed after the
|
||||
storage changes. Connection UI and local trust/Remember key actions still need
|
||||
integration. This is another prerequisite, not a usable Remote release.
|
||||
|
||||
Seventh implementation increment (2026-11-03): a source-library coordinator now
|
||||
binds explicit Connect/Disconnect attempts to public Go SDK lease operations and
|
||||
lifecycle events. It requires a reader-issued pending action before opening a
|
||||
lease, opens before networking, heartbeats during TLS/join, and cancels the relay
|
||||
on revoke, replacement, SDK EOF, membership or transport failure. Cleanup orders
|
||||
heartbeat completion before lease close; failed close blocks further connections.
|
||||
The complete Remote race suite and repository `make check` passed, including an
|
||||
actual SDK pipe fixture against a synthetic host. See
|
||||
[the coordinator contract and verification limits](remote/lifecycle.md).
|
||||
No reader code changed. Desktop payloads are counted and discarded; production
|
||||
consent, connection UI, typed desktop services and all live release gates remain
|
||||
open. This completes the library's explicit-connection foundation only.
|
||||
|
||||
Eighth implementation increment (2026-11-03): unwired public-SDK form handlers
|
||||
now provide certificate inspection/review and explicit saved-key actions.
|
||||
Inspection sends no application bytes and closes its socket; Copy fingerprint
|
||||
does not approve trust, and Trust once returns an endpoint-bound pin for a fresh
|
||||
authenticated connection. A changed certificate shows both fingerprints and
|
||||
rotation before join fails without disclosing the channel key. Remember/Forget
|
||||
use the existing secure storage and an empty masked entry. Cancellation and
|
||||
terminal-action reuse are checked. Endpoint validation now rejects control
|
||||
characters and invalid UTF-8. See [the handler contract](remote/security-ui.md).
|
||||
The complete Remote race suite and repository `make check` passed, including
|
||||
nine new test functions with private TLS and filesystem fixtures. The latter
|
||||
also checks existing Hello World, Wormhole and Battery Status host workflows.
|
||||
Production local-origin authorization, command registration, connection UI,
|
||||
persistent-pin UI, saved-key loading for Connect and desktop delivery remain
|
||||
pending. The Phase C trust/Remember-key item and all release gates stay open.
|
||||
|
||||
Ninth implementation increment (2026-11-03): a single connection-library workflow
|
||||
now combines the coordinator, masked key entry, explicit saved-key loading,
|
||||
nested Remember/Forget, background certificate inspection, Copy/Trust once and
|
||||
connection status/Disconnect. It claims one pending reader action, cancels setup
|
||||
on replacement/SDK loss and scopes cleanup to its original epoch. Loading a key
|
||||
or approving a certificate never connects automatically. The complete Remote
|
||||
race suite and `make check` passed; focused workflow race tests also passed ten
|
||||
repetitions after an inspection/cleanup race was corrected. A separate test
|
||||
process exercises the actual SDK form/lease IPC, storage and private TLS relay
|
||||
together. See [the workflow and readiness boundary](remote/connection-ui.md).
|
||||
Production consent/input provenance, endpoint/role selection, persistent-pin UI,
|
||||
lock/handoff revocation and desktop services remain unimplemented. No reader code
|
||||
changed. There is still no runnable Remote command or live desktop test; all
|
||||
release gates remain open.
|
||||
|
||||
Tenth implementation increment (2026-11-03): the reader now has a core consent
|
||||
procedure with unchecked per-session grants and single-use, session-bound
|
||||
approval tickets. Production managers require its focus/lock policy; I38lock
|
||||
secure input and XTerm handoff cancel outstanding dialogs, actions and lease
|
||||
contexts without waiting for session workers. Failed package preparation cannot
|
||||
leave an older consent dialog able to authorize access. Sensitive Tentacle forms
|
||||
use separate XI2 capture that rejects XTEST/SendEvent/unknown sources, reconstructs
|
||||
local modifier state and cancels on device hierarchy changes. Ordinary forms
|
||||
retain their existing path. See [reader authorization and its acceptance limits](../cthulhu/docs/tentacle-remote-authorization.md).
|
||||
Host/wire/interaction and focused app race suites, both SDK process fixtures,
|
||||
ten private input experiments, six native input race tests, the existing internal
|
||||
UI harness, vet, reader build, shellcheck, build-script tests and `make check`
|
||||
passed. The full host race suite took about 124 seconds. Xvfb proves injected
|
||||
approval rejection, not successful physical keyboard approval; virtual evdev and
|
||||
malicious same-user clients remain outside that guarantee. No connection command
|
||||
is registered and no desktop service exists. Physical-source acceptance,
|
||||
connection command integration and the existing live release gates remain open.
|
||||
|
||||
## 1. Intended result and recommended approach
|
||||
|
||||
Build a native Go Tentacle named **Remote**, with package ID `remote`, in this
|
||||
@@ -614,7 +676,10 @@ do not claim them from a design diagram.
|
||||
queues. Extend host harness with an inert session-service implementation.
|
||||
- [x] Add core lease state/revocation and Go/Python SDK conformance fixtures.
|
||||
- [ ] Integrate verified local consent and lock/handoff revocation with production
|
||||
reader owners. The core-only authorizer currently has no production caller.
|
||||
reader owners. Core consent, policy-bound managers and I38lock/XTerm revocation
|
||||
are implemented; XI2 injected-approval rejection is privately tested. Physical
|
||||
source acceptance and connection-command registration remain pending; see
|
||||
[the authorization increment](../cthulhu/docs/tentacle-remote-authorization.md).
|
||||
- [x] Update registry/install/update grant persistence and access descriptions.
|
||||
Existing Hello World, Wormhole and Battery Status actual-host checks passed.
|
||||
- [ ] Add production first-use consent and per-session access controls.
|
||||
@@ -630,10 +695,16 @@ tested; existing Tentacles still install, register, run, disable and update.
|
||||
|
||||
### Phase C: External transport and speech milestone
|
||||
|
||||
- [ ] Add `remote/src` state/codec/transport with explicit Connect/Disconnect.
|
||||
- [x] Add `remote/src` state/codec/transport with explicit Connect/Disconnect.
|
||||
The library coordinator uses reader-issued actions and public SDK leases;
|
||||
production connection UI and desktop delivery remain separate open items.
|
||||
- [x] Add secure settings and separate explicit saved-key storage, with no
|
||||
startup networking or persisted session consent.
|
||||
- [ ] Add the local CA/pin trust and Remember key UI workflows.
|
||||
Library certificate-review and masked Remember/Forget handlers now integrate
|
||||
with Connect, explicit saved-key loading and status/Disconnect. Verified local
|
||||
input origin, endpoint/role selection, persistent-pin UI and production wiring
|
||||
remain open. See [the connection workflow](remote/connection-ui.md).
|
||||
- [ ] Add core output observation and incoming remote presentation with origin
|
||||
tracking, cancel order and lock/handoff revocation.
|
||||
- [ ] Demonstrate controlled Cthulhu speech to NVDA and NVDA speech to controlling
|
||||
|
||||
+34
-11
@@ -3,7 +3,7 @@
|
||||
Remote will connect Cthulhu to an NVDA Remote protocol-v2 relay, as either a
|
||||
controller or a controlled computer. The first implementation increment is a
|
||||
tested Go relay library in `src/`. It is not yet a runnable or installable
|
||||
Tentacle. There is no manifest, catalog entry, connection UI or desktop access.
|
||||
Tentacle. There is no manifest, catalog entry, production connection UI or desktop access.
|
||||
|
||||
Implemented:
|
||||
|
||||
@@ -19,13 +19,25 @@ Implemented:
|
||||
- Validated settings and separate, explicit saved-key storage with endpoint-bound
|
||||
pins, owner-only files, symlink/hardlink rejection and atomic replacement.
|
||||
Storage does no network I/O; see [storage.md](storage.md).
|
||||
- A coordinator using public Go SDK leases and lifecycle events for explicit
|
||||
connection attempts, heartbeats, revocation and ordered failure cleanup.
|
||||
It requires reader-issued approval, never retries and performs no desktop
|
||||
effects; see [lifecycle.md](lifecycle.md).
|
||||
- Explicit certificate inspection with no application data, fingerprint review
|
||||
with Copy/Trust once/Cancel, and masked Remember/Forget key form handlers.
|
||||
A single library connection workflow now combines them with explicit saved-key
|
||||
loading, Connect and status/Disconnect. Setup cancellation follows pending
|
||||
approval lifetime; stale forms cannot disconnect a newer epoch. These have
|
||||
private SDK-process coverage, but no production connection registration.
|
||||
The reader authorization prerequisite is described below. See [security-ui.md](security-ui.md) and
|
||||
[connection-ui.md](connection-ui.md).
|
||||
|
||||
The adjacent reader now also supports secret entries in transient Tentacle forms:
|
||||
masked speech/Braille editing, copy/cut denial, explicit paste and cancellation
|
||||
without returning values. Persistent preference pages reject secret entries.
|
||||
This prerequisite is covered by both SDKs and a private Xorg form harness; it
|
||||
does not yet provide Remote's connection UI. Credential storage is now supplied
|
||||
by the separate library described above.
|
||||
does not yet provide Remote's production connection UI. Credential storage and
|
||||
the combined connection workflow are supplied by the library described above.
|
||||
|
||||
A subsequent [private Xorg feasibility increment](../../cthulhu/docs/testing/remote-input-feasibility.md)
|
||||
demonstrates exclusive capture and independent test-helper cleanup after writer
|
||||
@@ -44,10 +56,16 @@ acceptance remain pending; this is not yet Remote Braille support.
|
||||
The reader now also implements opt-in protocol 1.1 lifecycle IPC, both SDK clients,
|
||||
explicit install grants, and expiring core-issued leases. See
|
||||
[the session contract](../../cthulhu/docs/tentacle-sessions.md). Private conformance
|
||||
and GTK tests cover this foundation. There is no production consent issuer or
|
||||
reader desktop service yet; this library is not connected to those leases.
|
||||
and GTK tests cover this foundation. The library coordinator now consumes these
|
||||
leases through the public Go SDK, with private synthetic-host/TLS coverage.
|
||||
A subsequent [reader authorization increment](../../cthulhu/docs/tentacle-remote-authorization.md)
|
||||
adds core consent, lock/handoff cancellation and local-only sensitive forms.
|
||||
Injected approval is rejected in private XI2 tests; physical-keyboard approval and
|
||||
connection-command registration remain unverified/unimplemented respectively.
|
||||
There is no reader desktop service yet.
|
||||
|
||||
This implements relay data handling and storage only. Parsing a key, speech fragment or
|
||||
This implements relay data handling, storage, connection lifecycle and library
|
||||
forms. Parsing a key, speech fragment or
|
||||
Braille gesture does not execute it. Network readiness is not consent. The
|
||||
reader must supply locally authorized leases and recheck them when effects are
|
||||
delivered. See [protocol.md](protocol.md) for the wire contract and
|
||||
@@ -63,15 +81,20 @@ make check
|
||||
```
|
||||
|
||||
Tests create private loopback TLS listeners and in-memory test certificates.
|
||||
Security-form tests use synthetic submissions, not real keyboard input.
|
||||
They do not connect to public relays, the active reader, an accessibility bus,
|
||||
the desktop display or a clipboard. Fixtures are independently written examples
|
||||
the desktop display or a clipboard. The coordinator also uses the actual Go SDK
|
||||
over private pipes against a synthetic lifecycle host. A separate workflow test
|
||||
process exercises actual SDK form/lease IPC, storage and private relay TLS together.
|
||||
Fixtures are independently written examples
|
||||
based on source review, **not captured NVDA sessions**. There is no live desktop
|
||||
test to run for this increment.
|
||||
|
||||
Pending: actual NVDA/add-on/Orca interoperability, production local consent and
|
||||
reader session integration, speech delivery/export, exclusive keyboard capture,
|
||||
injection provenance and reader-death recovery, clipboard permission, connection/trust UI
|
||||
and saved-key UI actions, virtual Braille integration, physical displays and packaging. The
|
||||
Pending: actual NVDA/add-on/Orca interoperability, physical-source approval and
|
||||
connection-command integration, reader desktop services, speech delivery/export, exclusive keyboard capture,
|
||||
injection provenance and reader-death recovery, clipboard permission,
|
||||
endpoint/role selection and production connection UI integration, persistent-pin
|
||||
management, virtual Braille integration, physical displays and packaging. The
|
||||
full remote-control release must not be advertised until those gates pass.
|
||||
|
||||
## Relay trust
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
# Remote connection workflow
|
||||
|
||||
The connection library now combines certificate review, saved-key actions and
|
||||
the coordinator in one workflow. This remains **test-only wiring**: no production
|
||||
command, manifest or reader consent issuer exists. Remote is not ready for live
|
||||
desktop testing. The maintained Tentacles `master` matched `origin/master` at
|
||||
`63e84e9` after fetch on 2026-11-03; existing uncommitted work was preserved.
|
||||
No reader files or installed programs changed.
|
||||
|
||||
## Workflow ownership
|
||||
|
||||
`new_connection_workflow` accepts an already-selected, validated endpoint, an
|
||||
optional open settings store and an action received by the coordinator from the
|
||||
public SDK. It claims that action for one workflow and copies the reader's
|
||||
role/grants and endpoint trust. Caller-modified role/grants are ignored. Opening
|
||||
the workflow neither reads a saved key nor opens a network connection.
|
||||
|
||||
The production owner must supply endpoint/role selection, verify local input
|
||||
origin and cancel the workflow context on closure, lock/handoff or retirement.
|
||||
The workflow does not manufacture consent from a command or `Submission`. Its
|
||||
`remote-connection` continuation is registered only in a private test peer.
|
||||
The owner must serialize the currently displayed form's submissions; this
|
||||
library supplies no proof that a submission came from that form or a local key.
|
||||
|
||||
Pending approval has a context that ends on replacement, matching revocation,
|
||||
consumption, disconnect or SDK loss. A replacement cancels setup and inspection.
|
||||
The reader remains authoritative for action expiry at `remote.open`; the
|
||||
protocol currently supplies no event for expiry of an unopened action. Merely
|
||||
keeping a form open does not extend approval. An expired action cannot connect.
|
||||
|
||||
The workflow's `done` barrier includes its inspection worker. Cancelling it
|
||||
initiates coordinator cleanup; wait separately on the coordinator's Disconnect
|
||||
barrier before disposing the SDK session/store. Cleanup is scoped to the original
|
||||
epoch: closing an old form cannot retire a newer approval or connection.
|
||||
|
||||
## Explicit actions
|
||||
|
||||
- **Connect relay** validates the entered key, or uses a key previously loaded
|
||||
by **Use saved key**, and starts the coordinator. Install grants and a form
|
||||
are insufficient: the reader must still accept `remote.open` before dialing.
|
||||
- **Use saved key** loads only the selected host/port's credential. It does not
|
||||
connect, copy it or prefill an entry. A typed key overrides it for that attempt.
|
||||
- **Remember or forget a key** opens the existing masked form. Completion or its
|
||||
Cancel button returns to Connect. A remembered key still requires explicit
|
||||
loading; Forget also discards the workflow's previously loaded key.
|
||||
- **Inspect relay certificate** discards a loaded key and runs the bounded
|
||||
key-free probe in a worker. **Refresh inspection status** presents its result.
|
||||
Inspection failure never changes trust or starts a connection.
|
||||
- **Copy fingerprint** requests exactly that clipboard write. **Trust once**
|
||||
returns to Connect with an endpoint-bound pin. It neither persists the pin nor
|
||||
connects. Connect performs fresh TLS authentication before sending the key.
|
||||
- **Disconnect** cancels the original attempt. Status distinguishes opening,
|
||||
connecting, waiting, peer membership, cleanup and failure. Every status states
|
||||
that desktop services are unavailable. **Disconnect and close**, Escape/form
|
||||
cancellation or owner cancellation retires the workflow.
|
||||
|
||||
Entries are always empty and masked. Responses and status omit channel keys and
|
||||
server/RPC error text. Loaded keys are released on Connect, inspection, saved-key
|
||||
actions and teardown; transient pins are released on Connect/teardown. This is
|
||||
reference cleanup, not guaranteed secure memory erasure. Unknown action names
|
||||
and duplicate Connect submissions cannot start another attempt. Completed
|
||||
nested workflows return to Connect rather than repeating a storage action.
|
||||
|
||||
## Verification and readiness
|
||||
|
||||
From the Tentacles repository, with private loopback sockets permitted:
|
||||
|
||||
```sh
|
||||
GOCACHE=/tmp/cthulhu-cache GOPROXY=off go test -race ./remote/src -run '^TestConnectionWorkflow' -count=1 -timeout=60s
|
||||
GOCACHE=/tmp/cthulhu-cache GOPROXY=off go test -race ./remote/src -count=1 -timeout=60s
|
||||
make check GOPROXY=off
|
||||
```
|
||||
|
||||
The workflow tests cover both roles, explicit saved-key use, secret-free replies,
|
||||
endpoint/permission failures, one-use approval, nested Remember/Forget, key-free
|
||||
inspection, Copy/Trust once, fresh pinned TLS, cancellation during stalled TLS,
|
||||
replacement/SDK EOF and old status controls against a newer connection. A
|
||||
separate executable speaks the real Go SDK over OS pipes to a synthetic host;
|
||||
it exercises the form continuations, saved-key storage, certificate review and
|
||||
relay join/close together. The fixtures grant synthetic approval and submit
|
||||
synthetic values. They do not prove local input origin or accessible form
|
||||
navigation. The focused race tests passed ten repetitions after correcting an
|
||||
inspection/cleanup race; the complete race suite and `make check` also passed.
|
||||
|
||||
Before production registration, resolve reader-owned consent/input provenance,
|
||||
endpoint/role selection, persistent-pin management and lock/handoff revocation.
|
||||
Then test these actual forms with Tab/Shift+Tab, list navigation, masked editing,
|
||||
Copy, Cancel and failed storage, including cancellation during inspection/join.
|
||||
Recheck ordinary Tentacle forms, CA and pin connections, certificate rotation,
|
||||
Hello World, Wormhole and Battery Status. Reader desktop services, real NVDA/Orca
|
||||
interoperability, audible speech, physical keyboard/Braille and packaging remain
|
||||
separate gates. Passing these private checks does not make Remote installable.
|
||||
@@ -19,7 +19,7 @@ are relative to the adjacent `cthulhu` checkout.
|
||||
| Go SDK | `ServeSession` and `SessionClient` provide 1.1 calls/events; legacy Serve remains unchanged. Real-process tests include blocked pipes and command concurrency. |
|
||||
| Python SDK | `serve(session_client=...)` provides the same 1.1 lifecycle contract and conformance fixtures as Go, with a cancellable nonblocking pipe transport. |
|
||||
| Installation | Installer, registry, discovery-to-package checks, local launch and command host now carry 1.1 install grants. Grants do not create session consent. |
|
||||
| Updates/access | Install/update confirmations disclose grant direction and fresh local approval; disable/failure cancels leases. Updates revoke access before download, including failed preparation. Production consent, lock/handoff and desktop owner integration remain pending. |
|
||||
| Updates/access | Install/update confirmations disclose grant direction and fresh local approval; disable/failure cancels leases. Updates revoke access before download, including failed preparation. Core consent and I38lock/XTerm policy cancellation now exist; physical-source acceptance, command registration and desktop owners remain pending. |
|
||||
| Secret controls | Transient entries now support `secret: true`, with masked editing/speech/Braille, copy/cut denial and no values on cancellation. Persistent preference pages reject secrets. Private Xorg/SDK tests cover this prerequisite; a Remote connection UI, audible speech and physical Braille acceptance remain pending. See [the contract](../../cthulhu/docs/tentacle-secret-entries.md). |
|
||||
| Input | `internal/platform/xorg/listener.go` uses XRecord observation. That does not consume desktop keys. A private prototype now demonstrates exclusive capture and helper EOF/watchdog cleanup; production ownership, trusted origin and physical collisions remain unresolved. See [the feasibility record](../../cthulhu/docs/testing/remote-input-feasibility.md). |
|
||||
| Braille | `internal/braille/client.go` writes text/overlay dots through a helper. Shared viewport/cell-mask feasibility tests now demonstrate translated virtual cells and independent routing without a physical display. Virtual table/cursor policy, helper IPC and raw receiving remain open. See [the evidence](../../cthulhu/docs/testing/remote-braille-feasibility.md). |
|
||||
@@ -39,13 +39,28 @@ must never mint consent.
|
||||
table/cursor policy and implement isolated helper integration. These remaining
|
||||
feasibility gates are not assumptions established by the relay library.
|
||||
2. The [protocol 1.1 lifecycle foundation](../../cthulhu/docs/tentacle-sessions.md)
|
||||
now exists through both SDKs and installation. Complete production local
|
||||
consent, lock/handoff revocation and typed desktop operations; no child request
|
||||
may create approval. The internal authorizer currently has only test callers.
|
||||
now exists through both SDKs and installation. The reader's
|
||||
[authorization increment](../../cthulhu/docs/tentacle-remote-authorization.md)
|
||||
adds core consent, policy-bound production managers, I38lock/XTerm cancellation
|
||||
and separate XI2 sensitive forms. Private tests establish XTEST rejection;
|
||||
successful physical-source approval is still unverified. Register the
|
||||
connection command and complete typed desktop operations; no child request
|
||||
may create approval. The core consent procedure remains unregistered.
|
||||
3. Use the secret-entry support and [secure storage](storage.md) for host-issued
|
||||
connection, certificate-review and explicit saved-key actions. Integrate the relay
|
||||
coordinator so all transport/session failures revoke the current lease and
|
||||
close the connection before any retry or local Resume action.
|
||||
connection, certificate-review and explicit saved-key actions. The
|
||||
[library coordinator](lifecycle.md) now connects public SDK lifecycle events
|
||||
and lease calls to relay cancellation and ordered close. Integrate it with
|
||||
production local consent and UI; it currently has private fixture callers
|
||||
only, discards desktop payloads and never retries or resumes automatically.
|
||||
[Certificate and saved-key form handlers](security-ui.md) now provide explicit
|
||||
certificate inspection, Copy/Trust once/Cancel and masked Remember/Forget
|
||||
workflows, but have no production wiring until the reader can verify local
|
||||
input origin.
|
||||
The [connection-library workflow](connection-ui.md) now combines these forms
|
||||
with Connect, explicit saved-key loading, status and epoch-scoped Disconnect.
|
||||
It cancels pending setup/inspection on lifecycle loss and has a separate SDK
|
||||
process fixture. Endpoint/role selection, persistent-pin UI, verified local
|
||||
input origin and all production registration remain pending.
|
||||
4. Add policy-resolved output observation and remote presentation with origin
|
||||
ownership, secure-input/lock/handoff exclusion and local status priority.
|
||||
5. Complete keyboard recovery, explicit clipboard transfer and virtual/raw
|
||||
@@ -64,6 +79,21 @@ adds real filesystem tests for atomic replacement, endpoint scoping, permissions
|
||||
links, FIFO rejection, locking, malformed/oversized files and secret-free errors.
|
||||
Neither increment installs Remote or establishes live desktop acceptance.
|
||||
|
||||
The coordinator increment passed the complete Remote race suite and repository
|
||||
`make check`. It covers both roles, heartbeat during stalled TLS, revoke/open
|
||||
races, peer changes, SDK EOF and immediate socket cancellation independent of
|
||||
an in-flight heartbeat. An actual Go SDK pipe fixture talks to a synthetic
|
||||
lifecycle host. It does not exercise production consent or desktop effects;
|
||||
see [the exact contract and remaining gates](lifecycle.md).
|
||||
|
||||
The following security-form increment adds private tests for certificate
|
||||
inspection without application data, changed-pin review, fresh pin-authenticated
|
||||
join, certificate rotation, cancellation and one-use review. Filesystem fixtures
|
||||
exercise explicit Remember/Forget, secret-free responses and failed/cancelled
|
||||
actions preserving existing keys. These are synthetic form submissions, not
|
||||
production local consent or real keyboard/clipboard acceptance. See
|
||||
[the security-form contract](security-ui.md).
|
||||
|
||||
The Braille feasibility increment passed both default and brlapi-tagged Braille
|
||||
package suites with the race detector, tagged vet and a helper build. Eight new
|
||||
tests exercise shared cell masks and real liblouis viewports without opening
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
# Remote connection coordinator
|
||||
|
||||
Implemented as a source-library increment on 2026-11-03, based on Tentacles
|
||||
`63e84e9` and the public Go SDK in reader `573d15d`. The Tentacles branch matched
|
||||
`origin/master` after fetch. The reader revision was inspected locally; its
|
||||
remote branch was not refreshed for this increment. No reader code changed.
|
||||
|
||||
`src/coordinator.go` joins the existing relay transport and membership machine
|
||||
to the reader's protocol 1.1 lifecycle API. It supplies no connection dialog,
|
||||
desktop effects, executable or package. There is still no production issuer of
|
||||
the reader approvals it requires.
|
||||
|
||||
## Ownership and explicit connection
|
||||
|
||||
The coordinator owns one SDK `Events()` consumer for its entire lifetime. Its
|
||||
parent context must belong to the Tentacle process session. Event-stream EOF
|
||||
also cancels it. Do not run a second event consumer alongside it.
|
||||
|
||||
Core `remote.action` events populate a one-element approval channel for
|
||||
UI orchestration. A newer event replaces an unread approval and stops any old
|
||||
connection. The coordinator stores its own copy of the approved role/grants.
|
||||
Neither receiving an approval nor reading settings starts networking.
|
||||
|
||||
The subsequent [connection workflow](connection-ui.md) claims a pending action
|
||||
once and uses its cancellation context for forms and key-free inspection. That
|
||||
context ends on replacement, matching revocation, consumption, disconnect or SDK
|
||||
loss. `disconnect_epoch` retires only the original epoch, so stale form cleanup
|
||||
cannot revoke a newer action or connection. This does not create local consent
|
||||
or replace the reader's expiry check.
|
||||
|
||||
An explicit `connect` call must provide the matching pending action token and
|
||||
epoch, an endpoint with any already-approved pin, and a channel key. It validates
|
||||
and freezes TLS options, consumes the pending approval once and schedules a
|
||||
background attempt. Repeated/concurrent calls are refused. Failed attempts do
|
||||
not restore the approval or retry; a new core action is required.
|
||||
|
||||
The worker calls public SDK `remote.open` before dialing. The reader checks token
|
||||
expiry, role and grants. Denial makes no relay connection. The returned lease
|
||||
must have the expected epoch and a 32-character identifier. Reader-facing
|
||||
`controller`/`controlled` roles map to relay `master`/`slave` roles internally.
|
||||
|
||||
Snapshots distinguish opening a lease, connecting, waiting for a peer, and ready
|
||||
relay membership. **Ready means one opposite-role relay peer, not active desktop
|
||||
control.** Known desktop payloads are validated, counted and discarded without
|
||||
retention. No output/input queue or effect callback is exposed by this increment.
|
||||
|
||||
## Liveness and teardown
|
||||
|
||||
The worker sends `remote.heartbeat` each second, including while TLS/join is
|
||||
pending. Heartbeats and the final close use strictly increasing per-lease
|
||||
sequence numbers. The following stop the relay lifetime:
|
||||
|
||||
- Explicit Disconnect, coordinator close or parent-context cancellation.
|
||||
- A matching-epoch `remote.revoked`, a replacement action or SDK event EOF.
|
||||
- Heartbeat failure, TLS/join/read failure, malformed relay messages, invalid
|
||||
role/origin or any terminal membership change.
|
||||
|
||||
The socket context is cancelled immediately and peer readiness is cleared before
|
||||
waiting for cleanup RPCs. The worker finishes an in-flight heartbeat, then requests
|
||||
`remote.close`; each call has a two-second deadline. It deliberately does not
|
||||
cancel a healthy SDK call during ordinary Disconnect: SDK call cancellation
|
||||
retires the entire Tentacle process session. Reader-side lease expiry remains
|
||||
independent if communication fails. These bounds are not physical-key recovery
|
||||
evidence, and no keyboard service uses this worker yet.
|
||||
|
||||
`disconnect()` returns a completion barrier. No new connection is admitted until
|
||||
the old close finishes. A failed close or invalid lease reply makes the
|
||||
coordinator unavailable for the rest of its lifetime. A fresh process/SDK session
|
||||
is needed; there is no implicit resume, lease recreation or network retry.
|
||||
`close()` additionally stops the event consumer; its `done` channel and the
|
||||
Disconnect barrier allow callers to await both owners.
|
||||
|
||||
Statuses and errors retain no channel key, action token, certificate, server
|
||||
diagnostic, RPC message or received desktop content. The current attempt needs
|
||||
the supplied key for TLS/join only; it is not saved for reconnection. Clearing a
|
||||
Go variable does not promise secure memory erasure. Storage and future local
|
||||
Remember key/trust actions retain their separate contract.
|
||||
|
||||
## Verification and remaining gates
|
||||
|
||||
Run from this repository (private loopback sockets must be allowed):
|
||||
|
||||
```sh
|
||||
GOCACHE=/tmp/cthulhu-cache GOPROXY=off go test -race ./remote/src -count=1 -timeout=60s
|
||||
make check
|
||||
```
|
||||
|
||||
Both passed for this increment. Coordinator fixtures exercise approval denial,
|
||||
token reuse/stale epochs, copied role/grants, both roles, payload discard, peer
|
||||
departure, explicit fresh reconnection, revoke during open, heartbeat during a
|
||||
stalled TLS handshake, SDK EOF, replacement approval, parent cancellation,
|
||||
socket closure during a stalled heartbeat, cleanup ordering and failed-close
|
||||
admission. A pipe fixture uses the actual public Go SDK for negotiation,
|
||||
action/revocation events, open and close against a synthetic host.
|
||||
|
||||
The original pipe fixture runs in-process; the later connection-workflow fixture
|
||||
also exercises a separate SDK process. Neither replaces the reader's existing
|
||||
real-child-process SDK/authorizer tests or establish production consent. `make
|
||||
check` also verifies existing metadata, command registration and actual-host
|
||||
invocation for Hello World, Wormhole and Battery Status. Review the new source
|
||||
and these contracts before submission; neither command installs or replaces the
|
||||
active reader.
|
||||
|
||||
Next: production local consent and lock/handoff integration, endpoint/role
|
||||
selection and registration of the library forms, persistent-pin UI, typed reader
|
||||
output/presentation services and their effect
|
||||
ownership. Xorg provenance/collision safety and virtual/raw Braille remain open.
|
||||
There is no new live workflow to test yet. Audible speech, physical input and
|
||||
Braille, real NVDA/Orca sessions and installed-package behavior remain separate
|
||||
acceptance gates in the parent plan.
|
||||
+12
-9
@@ -107,11 +107,12 @@ cleanup does not wait for writer admission. Concurrent writes cannot interleave
|
||||
frames; their relative order is unspecified, so the session owner must sequence
|
||||
speech/cancel and key transitions before submitting them.
|
||||
|
||||
The future coordinator must close the transport immediately when `session`
|
||||
returns a terminal error, revoke the core lease on transport failure, and reject
|
||||
late network-worker results. The current tests exercise these layers separately;
|
||||
there is not yet a running Tentacle/coordinator. Transport write capacity does
|
||||
not replace the proposed separate host control/input/output queues.
|
||||
The [library coordinator](lifecycle.md) now closes the transport on terminal
|
||||
session errors, requests core lease closure on failure and rejects cancelled
|
||||
worker results. Private fixtures test those layers together using the public Go
|
||||
SDK. There is still no running Tentacle or production consent issuer. Desktop
|
||||
payloads are counted and discarded; transport write capacity does not replace
|
||||
the proposed separate host control/input/output queues.
|
||||
|
||||
## Timeouts, trust and liveness
|
||||
|
||||
@@ -123,8 +124,9 @@ authentication/trust failures require a fresh explicit attempt.
|
||||
CA mode uses normal system roots and hostname/IP checks. Pin mode accepts only
|
||||
the exact SHA-256 leaf certificate digest previously approved for that exact
|
||||
host string and port, replacing CA/name validation for that endpoint. Even a
|
||||
CA-valid replacement certificate fails an existing pin. Pin approval, display,
|
||||
fingerprint discovery and persistence are not implemented; callers cannot obtain
|
||||
CA-valid replacement certificate fails an existing pin. Endpoint-bound pin
|
||||
persistence is implemented in [storage.md](storage.md); local approval/display
|
||||
UI and fingerprint discovery remain unimplemented. Callers cannot obtain
|
||||
consent merely by constructing a pin. There is no plaintext or generic insecure
|
||||
mode. Host names are separate from ports; bare IPv6 literals use `JoinHostPort`.
|
||||
|
||||
@@ -133,6 +135,7 @@ initial read deadline is six minutes; receiving a complete next frame resets it.
|
||||
TCP keepalive requests idle 10 seconds, interval 3 seconds and three probes.
|
||||
These are development transport settings, **not a proven desktop recovery
|
||||
bound**. A relay process can hang while its kernel still acknowledges probes;
|
||||
the separate core one-second heartbeat/three-second lease expiry and remote-peer
|
||||
liveness design remain required. Idle/dead relay trials, abrupt network loss,
|
||||
the coordinator now sends one-second core heartbeats and relies on independent
|
||||
three-second reader lease expiry. Remote-peer liveness beyond relay membership
|
||||
remains unresolved. Idle/dead relay trials, abrupt network loss,
|
||||
IPv6 connections and installed-package behavior have not been verified.
|
||||
@@ -0,0 +1,123 @@
|
||||
# Remote certificate review and saved-key form handlers
|
||||
|
||||
Implemented as a source-library increment on 2026-11-03, on Tentacles `master`
|
||||
at `63e84e9` with the existing coordinator work preserved. The maintained remote
|
||||
branch matched that revision when checked. This uses the adjacent reader's
|
||||
public Go SDK at `573d15d`; no reader files changed.
|
||||
|
||||
These are **library handlers**, not production connection controls. The later
|
||||
[connection workflow](connection-ui.md) combines them with the coordinator,
|
||||
explicit saved-key loading, Connect and status/Disconnect in private fixtures.
|
||||
There is no executable, command registration or local input-origin authorizer
|
||||
in this increment. A synthetic `Submission` cannot prove that a person chose an
|
||||
action locally. Production wiring must wait for that reader-owned check,
|
||||
including rejection of remote/injected approval actions.
|
||||
|
||||
## Certificate inspection and review
|
||||
|
||||
`probe_certificate` takes an endpoint and a workflow context, with no channel
|
||||
key argument. The caller must explicitly start this background operation; it
|
||||
must not be an automatic fallback after a CA, hostname or pin failure. The
|
||||
inspection socket deliberately bypasses certificate authentication, completes
|
||||
TLS within the existing 15-second dial/handshake bound, sends no application
|
||||
bytes and closes. Cancellation interrupts a stalled handshake.
|
||||
|
||||
The result retains only endpoint identity, the observed SHA-256 leaf-certificate
|
||||
digest, any previous pin digest and workflow lifetime. Server-supplied certificate
|
||||
subject/issuer strings never enter the form. Inspection saves, copies and logs
|
||||
no certificate, fingerprint or channel key.
|
||||
|
||||
The public SDK form provides navigable details and three buttons:
|
||||
|
||||
- **Copy fingerprint** returns a host clipboard request for the observed digest.
|
||||
It keeps the review open and does not approve trust. There is no direct
|
||||
clipboard access, automatic copy or fingerprint-file write.
|
||||
- **Trust once** consumes the review and returns an endpoint pinned to that
|
||||
exact certificate, host and port. It does not save/replace a stored pin or mint
|
||||
a reader action/lease. The future connection owner must use this endpoint for
|
||||
one explicit coordinator attempt and discard it afterward.
|
||||
- **Cancel**, form cancellation or an already-cancelled workflow/handler context
|
||||
consumes the review without returning an approved endpoint.
|
||||
|
||||
Details explain independent fingerprint verification, the checks an exact pin
|
||||
replaces (CA, hostname and expiry), relay visibility of session contents and the
|
||||
lack of authenticated human identity. A changed certificate shows both old and
|
||||
new fingerprints. Reading/activating a details row cannot approve it.
|
||||
Concurrent/repeated terminal submissions cannot consume a review twice.
|
||||
|
||||
The inspection socket is never reused for a session. The existing transport
|
||||
performs a fresh TLS handshake and verifies the exact approved pin **before**
|
||||
sending protocol/version or channel-key bytes. Rotation between review and join
|
||||
fails authentication without disclosing the key. Normal connections still use
|
||||
CA/hostname validation or an already-approved pin; no trust fallback was added
|
||||
to the transport or coordinator.
|
||||
|
||||
## Explicit saved-key actions
|
||||
|
||||
`new_key_actions` freezes an already-selected endpoint for a workflow and an open
|
||||
`settingsStore`. Form creation neither loads a saved key nor connects. Its entry
|
||||
is empty, transient and secret, with a 512-character UI bound; submission also
|
||||
enforces the transport's stricter 512-byte UTF-8 key limit. Forget and Cancel do
|
||||
not require entry text.
|
||||
|
||||
**Remember key** explicitly stores a validated submitted key using existing
|
||||
endpoint-bound owner-only atomic storage. Invalid input returns a fresh empty
|
||||
secret form and a generic correction message. **Forget saved key** removes the
|
||||
store's single saved-key slot; the form explains that this includes a key saved
|
||||
for another endpoint and does not disconnect an active session or erase disk
|
||||
history. A storage error reports failure rather than success. Neither action
|
||||
returns a key in presentation, form text or clipboard requests.
|
||||
|
||||
Remember/Forget consume their workflow once a valid storage action is admitted;
|
||||
cancelled workflows cannot subsequently save/delete. Cancellation after admission
|
||||
does not roll back a filesystem operation that has already started. Settings
|
||||
and existing pins are untouched. The caller must keep the store open through
|
||||
handler completion and cancel the workflow on form closure, local approval
|
||||
replacement, lock/handoff or process-session retirement. Use a workflow context,
|
||||
not the short-lived context of the RPC that opens a form.
|
||||
|
||||
The standalone continuations are named `remote-review-certificate` and
|
||||
`remote-saved-key`; the combined workflow routes both through its
|
||||
`remote-connection` continuation. None is registered in production. Their owner
|
||||
must serialize workflows,
|
||||
cancel superseded ones and supply verified local-origin submissions before any
|
||||
production registration. No persistent settings-page secret or saved session
|
||||
consent is introduced.
|
||||
|
||||
## Verification and remaining integration
|
||||
|
||||
From the Tentacles repository, with private loopback sockets allowed:
|
||||
|
||||
```sh
|
||||
GOCACHE=/tmp/cthulhu-cache GOPROXY=off go test -race ./remote/src -count=1 -timeout=60s
|
||||
make check
|
||||
```
|
||||
|
||||
Both passed for this increment, including nine new test functions and their
|
||||
subcases. `git diff --check` also passed.
|
||||
|
||||
The focused suite covers no application bytes during inspection, changed-pin
|
||||
disclosure, explicit copy, cancellation, one-use/concurrent review consumption,
|
||||
fresh authenticated join and certificate rotation between review and join.
|
||||
Saved-key fixtures cover masked empty controls, explicit storage, endpoint
|
||||
isolation, secret-free replies, invalid keys, cancellation and failed Remember/
|
||||
Forget with preservation of existing credentials. Endpoint validation now also
|
||||
rejects control characters and invalid UTF-8 before constructing forms or dialing.
|
||||
The complete Remote race suite includes existing CA/pin, framing, membership,
|
||||
storage and coordinator regressions. `make check` additionally checks vet and
|
||||
existing Hello World, Wormhole and Battery Status actual-host workflows.
|
||||
|
||||
These fixtures call library handlers with synthetic submissions. They do not
|
||||
establish real form traversal, local input origin, audible masking, physical
|
||||
Braille, clipboard ownership or a production Remote workflow. There is no new
|
||||
live command to test yet. Once wired, review both fingerprint variants with
|
||||
Tab/Shift+Tab and list navigation; verify that Copy alone changes the clipboard,
|
||||
Cancel saves nothing, secret editing stays masked, and Remember/Forget failures
|
||||
are announced. Recheck ordinary Tentacle forms and CA/pin connections, including
|
||||
certificate rotation. The reader's existing secret-entry native harness remains
|
||||
prerequisite evidence rather than acceptance of these new forms.
|
||||
|
||||
Still pending: production local consent and input provenance, endpoint/role
|
||||
selection and command registration, persistent-pin review UI,
|
||||
lock/handoff integration, desktop services and all live interoperability/release
|
||||
gates. The Phase C trust/Remember-key checkbox in the parent plan remains open.
|
||||
@@ -0,0 +1,281 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
package remote
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
sdk "git.stormux.org/storm/cthulhu/sdk/go/tentacle"
|
||||
)
|
||||
|
||||
// A test-only executable peer. The parent supplies synthetic approval over real
|
||||
// SDK process pipes; no production command can instantiate this workflow yet.
|
||||
func TestConnectionWorkflowSDKPeer(t *testing.T) {
|
||||
if os.Args[len(os.Args)-1] != "remote-workflow-peer" {
|
||||
return
|
||||
}
|
||||
host, portText, err := net.SplitHostPort(os.Getenv("CTHULHU_REMOTE_TEST_ADDRESS"))
|
||||
port, portErr := strconv.Atoi(portText)
|
||||
if err != nil || portErr != nil || host != "127.0.0.1" {
|
||||
os.Exit(2)
|
||||
}
|
||||
store, err := openSettingsStore(os.Getenv("CTHULHU_REMOTE_TEST_STORE"))
|
||||
if err != nil {
|
||||
os.Exit(2)
|
||||
}
|
||||
client := sdk.NewSessionClient()
|
||||
c := newCoordinator(context.Background(), client)
|
||||
var workflow *connectionWorkflow
|
||||
var mu sync.Mutex
|
||||
commands := []sdk.Command{
|
||||
{ID: "remote-test-open", Title: "Private Remote workflow", Presentation: true, Interaction: true,
|
||||
Handle: func(ctx context.Context, _ json.RawMessage) (any, error) {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
select {
|
||||
case action := <-c.actions:
|
||||
var err error
|
||||
workflow, err = new_connection_workflow(c.ctx, c, action, endpoint{host: host, port: port}, store)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return workflow.form(), nil
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
}},
|
||||
{ID: "remote-connection", Title: "Private Remote continuation", Presentation: true, Interaction: true,
|
||||
Handle: func(ctx context.Context, data json.RawMessage) (any, error) {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
var submission sdk.Submission
|
||||
if workflow == nil || json.Unmarshal(data, &submission) != nil {
|
||||
return nil, sdk.ErrProtocol
|
||||
}
|
||||
return workflow.submit(ctx, submission)
|
||||
}},
|
||||
}
|
||||
err = sdk.ServeSession(os.Stdin, os.Stdout, commands, nil, client)
|
||||
barrier := c.disconnect()
|
||||
c.close()
|
||||
<-barrier
|
||||
<-c.done
|
||||
mu.Lock()
|
||||
if workflow != nil {
|
||||
workflow.close()
|
||||
<-workflow.done
|
||||
}
|
||||
mu.Unlock()
|
||||
store.close()
|
||||
if err != nil {
|
||||
os.Exit(1)
|
||||
}
|
||||
os.Exit(0)
|
||||
}
|
||||
|
||||
func TestConnectionWorkflowPublicSDKProcess(t *testing.T) {
|
||||
certificate, _ := testCertificate(t, false)
|
||||
probed := make(chan struct{})
|
||||
joined := make(chan struct{})
|
||||
var serverMu sync.Mutex
|
||||
connections := 0
|
||||
target := testRelay(t, certificate, func(connection net.Conn) {
|
||||
serverMu.Lock()
|
||||
connections++
|
||||
count := connections
|
||||
serverMu.Unlock()
|
||||
if count == 1 {
|
||||
data, _ := io.ReadAll(connection)
|
||||
if len(data) != 0 {
|
||||
t.Error("process certificate inspection sent application data")
|
||||
}
|
||||
close(probed)
|
||||
return
|
||||
}
|
||||
if relayHandshake(t, connection, controller) == nil {
|
||||
return
|
||||
}
|
||||
_, _ = io.WriteString(connection, "{\"type\":\"channel_joined\",\"channel\":\"synthetic-fixture\",\"clients\":[]}\n")
|
||||
close(joined)
|
||||
_, _ = io.Copy(io.Discard, connection)
|
||||
})
|
||||
testBinary, err := os.Executable()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(t.Context(), 15*time.Second)
|
||||
defer cancel()
|
||||
process := exec.CommandContext(ctx, testBinary, "-test.run=^TestConnectionWorkflowSDKPeer$", "--", "remote-workflow-peer")
|
||||
process.Env = append(os.Environ(),
|
||||
"CTHULHU_REMOTE_TEST_ADDRESS="+net.JoinHostPort(target.host, strconv.Itoa(target.port)),
|
||||
"CTHULHU_REMOTE_TEST_STORE="+t.TempDir()+"/remote")
|
||||
var stderr bytes.Buffer
|
||||
process.Stderr = &stderr
|
||||
input, err := process.StdinPipe()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
output, err := process.StdoutPipe()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := process.Start(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
input.Close()
|
||||
process.Process.Kill()
|
||||
process.Wait()
|
||||
})
|
||||
var writerMu sync.Mutex
|
||||
send := func(value any) error {
|
||||
writerMu.Lock()
|
||||
defer writerMu.Unlock()
|
||||
return json.NewEncoder(input).Encode(value)
|
||||
}
|
||||
replies := make(chan json.RawMessage, 16)
|
||||
leaseCalls := make(chan string, 16)
|
||||
hostDone := make(chan struct{})
|
||||
go func() {
|
||||
defer close(hostDone)
|
||||
defer close(replies)
|
||||
decoder := json.NewDecoder(output)
|
||||
for {
|
||||
var frame struct {
|
||||
ID string `json:"id"`
|
||||
Method string `json:"method"`
|
||||
Params json.RawMessage `json:"params"`
|
||||
Result json.RawMessage `json:"result"`
|
||||
Error json.RawMessage `json:"error"`
|
||||
}
|
||||
if decoder.Decode(&frame) != nil {
|
||||
return
|
||||
}
|
||||
if frame.Method == "" {
|
||||
if len(frame.Error) != 0 {
|
||||
t.Error("SDK command returned an error")
|
||||
}
|
||||
replies <- frame.Result
|
||||
continue
|
||||
}
|
||||
leaseCalls <- frame.Method
|
||||
result := any(struct{}{})
|
||||
if frame.Method == "remote.open" {
|
||||
var open sdk.RemoteOpen
|
||||
if json.Unmarshal(frame.Params, &open) != nil || open.Epoch != 1 || open.Role != "controller" {
|
||||
t.Error("invalid SDK lease request")
|
||||
return
|
||||
}
|
||||
result = sdk.RemoteLease{Lease: strings.Repeat("b", 32), Epoch: open.Epoch}
|
||||
}
|
||||
if send(map[string]any{"jsonrpc": "2.0", "id": frame.ID, "result": result}) != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
nextReply := func() json.RawMessage {
|
||||
t.Helper()
|
||||
select {
|
||||
case reply, ok := <-replies:
|
||||
if !ok {
|
||||
t.Fatal("SDK process stopped before its reply")
|
||||
}
|
||||
return reply
|
||||
case <-ctx.Done():
|
||||
t.Fatal("SDK workflow timed out")
|
||||
return nil
|
||||
}
|
||||
}
|
||||
if err := send(map[string]any{"jsonrpc": "2.0", "id": "1", "method": "initialize", "params": map[string]any{
|
||||
"protocol": map[string]int{"major": 1, "minor": 1}, "session": "fixture",
|
||||
"apis": []string{"commands", "presentation", "interaction", "session-events", "remote-access"},
|
||||
"capabilities": []string{"presentation", "interaction", "remote-present"},
|
||||
}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var registration struct {
|
||||
Commands []sdk.Command `json:"commands"`
|
||||
}
|
||||
if json.Unmarshal(nextReply(), ®istration) != nil || len(registration.Commands) != 2 {
|
||||
t.Fatal("missing SDK workflow registration")
|
||||
}
|
||||
if err := send(map[string]any{"jsonrpc": "2.0", "method": "initialized", "params": map[string]string{"session": "fixture"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := send(map[string]any{"jsonrpc": "2.0", "method": "session.event", "params": sdk.SessionEvent{
|
||||
Kind: "remote.action", Sequence: 1, Epoch: 1, Action: strings.Repeat("a", 32), Role: "controller", Grants: []string{"remote-present"},
|
||||
}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
id := 1
|
||||
invoke := func(command, activated, key string) sdk.Interaction {
|
||||
t.Helper()
|
||||
id++
|
||||
if err := send(map[string]any{"jsonrpc": "2.0", "id": strconv.Itoa(id), "method": "command.invoke", "params": map[string]any{
|
||||
"command": command, "arguments": sdk.Submission{Activated: activated, Values: map[string]sdk.Value{"channel-key": {Text: key}}},
|
||||
}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var result sdk.Interaction
|
||||
if json.Unmarshal(nextReply(), &result) != nil {
|
||||
t.Fatal("invalid SDK interaction result")
|
||||
}
|
||||
assertSecretAbsent(t, result, "synthetic-fixture")
|
||||
return result
|
||||
}
|
||||
if result := invoke("remote-test-open", "", ""); result.Form == nil || result.Form.Title != "Connect Remote relay" {
|
||||
t.Fatal("SDK did not open connection controls")
|
||||
}
|
||||
invoke("remote-connection", "saved-key-actions", "")
|
||||
invoke("remote-connection", "remember-key", "synthetic-fixture")
|
||||
invoke("remote-connection", "inspect-certificate", "")
|
||||
awaitDone(t, probed)
|
||||
for result := invoke("remote-connection", "refresh", ""); result.Form.Title != "Review Remote relay certificate"; result = invoke("remote-connection", "refresh", "") {
|
||||
if ctx.Err() != nil {
|
||||
t.Fatal("SDK did not present inspected certificate")
|
||||
}
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
if result := invoke("remote-connection", "copy-fingerprint", ""); result.Clipboard == nil {
|
||||
t.Fatal("SDK lost explicit fingerprint copy")
|
||||
}
|
||||
invoke("remote-connection", "trust-once", "")
|
||||
invoke("remote-connection", "load-key", "")
|
||||
select {
|
||||
case method := <-leaseCalls:
|
||||
t.Fatal("SDK opened a lease before explicit Connect", method)
|
||||
default:
|
||||
}
|
||||
invoke("remote-connection", "connect", "")
|
||||
awaitDone(t, joined)
|
||||
invoke("remote-connection", "disconnect", "")
|
||||
for _, expected := range []string{"remote.open", "remote.close"} {
|
||||
select {
|
||||
case method := <-leaseCalls:
|
||||
if method != expected {
|
||||
t.Fatal("unexpected lease operation", method)
|
||||
}
|
||||
case <-ctx.Done():
|
||||
t.Fatal("missing lease operation", expected)
|
||||
}
|
||||
}
|
||||
if result := invoke("remote-connection", "cancel", ""); !result.Done {
|
||||
t.Fatal("SDK did not close the workflow")
|
||||
}
|
||||
input.Close()
|
||||
awaitDone(t, hostDone)
|
||||
if err := process.Wait(); err != nil {
|
||||
t.Fatalf("SDK workflow process failed: %v\n%s", err, stderr.String())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,317 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
package remote
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"strconv"
|
||||
"sync"
|
||||
|
||||
sdk "git.stormux.org/storm/cthulhu/sdk/go/tentacle"
|
||||
)
|
||||
|
||||
// connectionWorkflow joins the library forms and coordinator for one selected
|
||||
// endpoint and reader action. It is NOT a local-origin authorizer. Production
|
||||
// registration still requires reader-owned consent and trusted submissions.
|
||||
// The owner must cancel ctx on form closure, lock/handoff or process retirement.
|
||||
type connectionWorkflow struct {
|
||||
mu sync.Mutex
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
done chan struct{}
|
||||
setupCtx context.Context
|
||||
owner *coordinator
|
||||
action sdk.SessionEvent
|
||||
target endpoint
|
||||
store *settingsStore
|
||||
mode string // credentials, inspecting, certificate, saved-key, status, finished
|
||||
notice string
|
||||
key string // Explicitly loaded only; never placed back into a form.
|
||||
review *certificateReview
|
||||
keys *keyActions
|
||||
probeDone chan struct{}
|
||||
}
|
||||
|
||||
func new_connection_workflow(ctx context.Context, owner *coordinator, action sdk.SessionEvent, target endpoint, store *settingsStore) (*connectionWorkflow, error) {
|
||||
if _, err := target.tlsConfig(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return nil, errLease
|
||||
}
|
||||
approval, setupCtx, err := owner.claim_approval(action)
|
||||
if err != nil {
|
||||
return nil, errLease
|
||||
}
|
||||
if target.pin != nil {
|
||||
pin := *target.pin
|
||||
target.pin = &pin
|
||||
}
|
||||
if target.roots != nil {
|
||||
target.roots = target.roots.Clone()
|
||||
}
|
||||
lifetime, cancel := context.WithCancel(owner.ctx)
|
||||
w := &connectionWorkflow{ctx: lifetime, cancel: cancel, done: make(chan struct{}), setupCtx: setupCtx,
|
||||
owner: owner, action: approval, target: target, store: store, mode: "credentials"}
|
||||
stopParent := context.AfterFunc(ctx, cancel)
|
||||
go func() {
|
||||
defer close(w.done)
|
||||
defer stopParent()
|
||||
select {
|
||||
case <-setupCtx.Done():
|
||||
w.mu.Lock()
|
||||
// connect consumes setup approval while holding this same mutex;
|
||||
// only its status controls may outlive that consumption.
|
||||
if w.mode != "status" {
|
||||
w.finish_locked()
|
||||
}
|
||||
w.mu.Unlock()
|
||||
case <-lifetime.Done():
|
||||
}
|
||||
<-lifetime.Done()
|
||||
w.mu.Lock()
|
||||
w.finish_locked()
|
||||
probeDone := w.probeDone
|
||||
w.mu.Unlock()
|
||||
if probeDone != nil {
|
||||
<-probeDone
|
||||
}
|
||||
}()
|
||||
return w, nil
|
||||
}
|
||||
|
||||
func (w *connectionWorkflow) finish_locked() {
|
||||
w.mode, w.key, w.review, w.keys = "finished", "", nil, nil
|
||||
w.target.pin = nil
|
||||
w.cancel()
|
||||
w.owner.disconnect_epoch(w.action.Epoch)
|
||||
}
|
||||
|
||||
func (w *connectionWorkflow) close() { w.cancel() }
|
||||
|
||||
func (w *connectionWorkflow) form() sdk.Interaction {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
return w.form_locked()
|
||||
}
|
||||
|
||||
func (w *connectionWorkflow) form_locked() sdk.Interaction {
|
||||
var result sdk.Interaction
|
||||
address := net.JoinHostPort(w.target.host, strconv.Itoa(w.target.port))
|
||||
details := sdk.Element{ID: "details", Label: "Connection details", Kind: sdk.List, Items: []sdk.ListItem{
|
||||
{ID: "endpoint", Label: "Relay: " + address},
|
||||
{ID: "role", Label: "Approved role: " + w.action.Role},
|
||||
{ID: "privacy", Label: "The relay can read the channel key and session contents. A channel key does not verify the other person's identity."},
|
||||
{ID: "scope", Label: "Relay testing only. Speech, keyboard, clipboard transfer and Braille services are unavailable."},
|
||||
}}
|
||||
switch w.mode {
|
||||
case "credentials":
|
||||
trust := "Normal certificate and hostname validation."
|
||||
if w.target.pin != nil {
|
||||
trust = "An explicitly approved certificate pin is required for this relay."
|
||||
}
|
||||
details.Items = append(details.Items, sdk.ListItem{ID: "trust", Label: trust})
|
||||
if w.key != "" {
|
||||
details.Items = append(details.Items, sdk.ListItem{ID: "loaded-key", Label: "A saved key was explicitly loaded. Leave Channel key empty to use it, or enter a replacement for this attempt."})
|
||||
}
|
||||
elements := []sdk.Element{details,
|
||||
{ID: "channel-key", Label: "Channel key", Kind: sdk.Entry, Secret: true, MaxLength: 512},
|
||||
{ID: "connect", Label: "Connect relay", Kind: sdk.Button},
|
||||
{ID: "inspect-certificate", Label: "Inspect relay certificate", Kind: sdk.Button},
|
||||
}
|
||||
if w.store != nil {
|
||||
elements = append(elements,
|
||||
sdk.Element{ID: "load-key", Label: "Use saved key", Kind: sdk.Button},
|
||||
sdk.Element{ID: "saved-key-actions", Label: "Remember or forget a key", Kind: sdk.Button})
|
||||
}
|
||||
elements = append(elements, sdk.Element{ID: "cancel", Label: "Cancel", Kind: sdk.Button})
|
||||
result.Form = &sdk.Form{Title: "Connect Remote relay", Elements: elements}
|
||||
case "inspecting":
|
||||
details.Items = append(details.Items, sdk.ListItem{ID: "inspection", Label: "Inspecting the certificate without sending a channel key. No connection will start automatically."})
|
||||
result.Form = &sdk.Form{Title: "Inspecting Remote certificate", Elements: []sdk.Element{details,
|
||||
{ID: "refresh", Label: "Refresh inspection status", Kind: sdk.Button},
|
||||
{ID: "cancel", Label: "Cancel", Kind: sdk.Button},
|
||||
}}
|
||||
case "certificate":
|
||||
result = w.review.form()
|
||||
case "saved-key":
|
||||
result = w.keys.form()
|
||||
case "status":
|
||||
status := w.owner.snapshot()
|
||||
text := "This connection attempt has ended. Fresh local approval is required to connect again."
|
||||
if status.epoch == w.action.Epoch {
|
||||
text = connection_status_text(status)
|
||||
}
|
||||
details.Items = append(details.Items, sdk.ListItem{ID: "status", Label: text})
|
||||
result.Form = &sdk.Form{Title: "Remote relay status", Elements: []sdk.Element{details,
|
||||
{ID: "refresh", Label: "Refresh connection status", Kind: sdk.Button},
|
||||
{ID: "disconnect", Label: "Disconnect", Kind: sdk.Button},
|
||||
{ID: "cancel", Label: "Disconnect and close", Kind: sdk.Button},
|
||||
}}
|
||||
default:
|
||||
return security_message("Remote connection workflow closed.")
|
||||
}
|
||||
// Nested forms always return through this instance's owner, never through
|
||||
// the standalone handlers or a newly selected endpoint.
|
||||
result.Next = "remote-connection"
|
||||
if w.notice != "" {
|
||||
result.Presentation = security_message(w.notice).Presentation
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func connection_status_text(status connectionStatus) string {
|
||||
switch status.state {
|
||||
case "opening":
|
||||
return "Requesting the reader lease."
|
||||
case "connecting":
|
||||
return "Connecting and authenticating the relay."
|
||||
case "waiting":
|
||||
return "Connected to the relay; waiting for one opposite-role peer. Desktop services are unavailable."
|
||||
case "ready":
|
||||
return "One opposite-role peer has joined. Desktop services are unavailable."
|
||||
case "stopping":
|
||||
return "Disconnecting and releasing the reader lease."
|
||||
case "failed":
|
||||
switch {
|
||||
case errors.Is(status.err, errTrust):
|
||||
return "Certificate verification failed. No channel key was sent. A fresh local connection action is required; certificate inspection is never automatic."
|
||||
case errors.Is(status.err, errLease):
|
||||
return "Reader approval is unavailable or was revoked. Fresh local approval is required."
|
||||
default:
|
||||
return "Relay connection failed or the peer changed. Fresh local approval is required."
|
||||
}
|
||||
default:
|
||||
return "Disconnected. Fresh local approval is required to connect again."
|
||||
}
|
||||
}
|
||||
|
||||
// Inspection is explicit and runs outside the command deadline. Only Refresh
|
||||
// presents its result; neither completion nor Trust once starts a connection.
|
||||
func (w *connectionWorkflow) inspect_locked() {
|
||||
w.key, w.notice, w.mode = "", "", "inspecting"
|
||||
done := make(chan struct{})
|
||||
w.probeDone = done
|
||||
probeCtx, cancel := context.WithCancel(w.setupCtx)
|
||||
stop := context.AfterFunc(w.ctx, cancel)
|
||||
target := w.target
|
||||
go func() {
|
||||
defer close(done)
|
||||
defer cancel()
|
||||
defer stop()
|
||||
review, err := probe_certificate(probeCtx, target)
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
if w.mode != "inspecting" || w.ctx.Err() != nil || w.setupCtx.Err() != nil {
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
w.mode, w.notice = "credentials", "Certificate inspection failed. No trust was changed and no channel key was sent."
|
||||
return
|
||||
}
|
||||
// The probe's short-lived context ends here. The review belongs to the
|
||||
// still-pending approval and workflow, not the worker/command lifetime.
|
||||
review.lifetime = w.setupCtx
|
||||
w.review, w.mode = review, "certificate"
|
||||
}()
|
||||
}
|
||||
|
||||
func (w *connectionWorkflow) submit(ctx context.Context, value sdk.Submission) (sdk.Interaction, error) {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
if w.ctx.Err() != nil || ctx.Err() != nil || w.mode == "finished" || w.mode != "status" && w.setupCtx.Err() != nil {
|
||||
w.finish_locked()
|
||||
return security_message("Remote connection approval ended. Start a fresh local connection action."), nil
|
||||
}
|
||||
if value.Cancelled {
|
||||
w.finish_locked()
|
||||
return w.form_locked(), nil
|
||||
}
|
||||
w.notice = ""
|
||||
if value.Activated == "cancel" && w.mode != "certificate" && w.mode != "saved-key" {
|
||||
w.finish_locked()
|
||||
return w.form_locked(), nil
|
||||
}
|
||||
switch w.mode {
|
||||
case "credentials":
|
||||
switch value.Activated {
|
||||
case "connect":
|
||||
key := value.Values["channel-key"].Text
|
||||
if key == "" {
|
||||
key = w.key
|
||||
}
|
||||
if !validChannelKey(key) {
|
||||
w.notice = "Enter a valid channel key or explicitly load a saved key."
|
||||
break
|
||||
}
|
||||
err := w.owner.connect(w.action, w.target, key)
|
||||
w.key = ""
|
||||
w.target.pin = nil
|
||||
if err != nil {
|
||||
w.finish_locked()
|
||||
return security_message("The connection could not start. Fresh local approval is required."), nil
|
||||
}
|
||||
w.mode = "status"
|
||||
case "load-key":
|
||||
w.key = ""
|
||||
if w.store == nil {
|
||||
break
|
||||
}
|
||||
key, err := w.store.loadKey(w.target)
|
||||
if err != nil {
|
||||
w.notice = "The saved channel key could not be loaded."
|
||||
} else if key == "" {
|
||||
w.notice = "No saved key is available for this relay."
|
||||
} else {
|
||||
w.key, w.notice = key, "Saved key loaded for this relay. Choose Connect relay to use it."
|
||||
}
|
||||
case "inspect-certificate":
|
||||
w.inspect_locked()
|
||||
case "saved-key-actions":
|
||||
w.key = ""
|
||||
if w.store == nil {
|
||||
break
|
||||
}
|
||||
keys, err := new_key_actions(w.setupCtx, w.target, w.store)
|
||||
if err != nil {
|
||||
w.notice = "Saved-key actions are unavailable."
|
||||
} else {
|
||||
w.keys, w.mode = keys, "saved-key"
|
||||
}
|
||||
}
|
||||
case "certificate":
|
||||
approved, result, err := w.review.submit(ctx, value)
|
||||
if err != nil || result.Done {
|
||||
w.review, w.mode = nil, "credentials"
|
||||
w.notice = result.Speech
|
||||
if err != nil {
|
||||
w.notice = "Certificate review ended without approval."
|
||||
} else if approved.host != "" {
|
||||
w.target = approved
|
||||
w.notice = "Certificate approved for this attempt only. Enter a channel key and choose Connect relay."
|
||||
}
|
||||
} else {
|
||||
result.Next = "remote-connection"
|
||||
return result, nil
|
||||
}
|
||||
case "saved-key":
|
||||
result, err := w.keys.submit(ctx, value)
|
||||
if err != nil || result.Done {
|
||||
w.keys, w.mode = nil, "credentials"
|
||||
w.notice = result.Speech
|
||||
if err != nil {
|
||||
w.notice = "Saved-key action ended."
|
||||
}
|
||||
} else {
|
||||
result.Next = "remote-connection"
|
||||
return result, nil
|
||||
}
|
||||
case "status":
|
||||
if value.Activated == "disconnect" {
|
||||
w.owner.disconnect_epoch(w.action.Epoch)
|
||||
}
|
||||
}
|
||||
return w.form_locked(), nil
|
||||
}
|
||||
@@ -0,0 +1,361 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
package remote
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
sdk "git.stormux.org/storm/cthulhu/sdk/go/tentacle"
|
||||
)
|
||||
|
||||
func workflowFixture(t *testing.T, c *coordinator, action sdk.SessionEvent, target endpoint, store *settingsStore) *connectionWorkflow {
|
||||
t.Helper()
|
||||
w, err := new_connection_workflow(t.Context(), c, action, target, store)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { w.close(); awaitDone(t, w.done) })
|
||||
return w
|
||||
}
|
||||
|
||||
func workflowSubmit(t *testing.T, w *connectionWorkflow, activated, key string) sdk.Interaction {
|
||||
t.Helper()
|
||||
result, err := w.submit(t.Context(), sdk.Submission{Activated: activated, Values: map[string]sdk.Value{"channel-key": {Text: key}}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func assertSecretAbsent(t *testing.T, result sdk.Interaction, secret string) {
|
||||
t.Helper()
|
||||
encoded, err := json.Marshal(result)
|
||||
if err != nil || strings.Contains(string(encoded), secret) {
|
||||
t.Fatal("response contains a channel key or could not be encoded")
|
||||
}
|
||||
if result.Form != nil {
|
||||
for _, element := range result.Form.Elements {
|
||||
if element.ID == "channel-key" && (!element.Secret || element.Text != "") {
|
||||
t.Fatal("channel-key entry is unmasked or prefilled")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestConnectionWorkflowBindsReaderActionAndFreezesTrust(t *testing.T) {
|
||||
c, f := fixtureCoordinator(t, nil)
|
||||
target := endpoint{host: "relay.invalid", port: 6837}
|
||||
if _, err := new_connection_workflow(t.Context(), c, sdk.SessionEvent{}, target, nil); err != errLease {
|
||||
t.Fatal("setup without a reader action", err)
|
||||
}
|
||||
action := approve(t, c, f, 1, "controller")
|
||||
pin := &certificatePin{host: target.host, port: target.port, sha256: [32]byte{1}}
|
||||
target.pin = pin
|
||||
action.Role, action.Grants[0] = "controlled", "keyboard-inject"
|
||||
w := workflowFixture(t, c, action, target, nil)
|
||||
pin.sha256 = [32]byte{2}
|
||||
if w.action.Role != "controller" || w.action.Grants[0] != "remote-present" || w.target.pin.sha256 != [32]byte{1} {
|
||||
t.Fatal("caller changed the selected role, grants or certificate")
|
||||
}
|
||||
if _, err := new_connection_workflow(t.Context(), c, action, target, nil); err != errLease {
|
||||
t.Fatal("multiple workflows claimed one action", err)
|
||||
}
|
||||
result := w.form()
|
||||
encoded, _ := json.Marshal(result)
|
||||
if result.Form == nil || result.Next != "remote-connection" || !strings.Contains(string(encoded), "services are unavailable") {
|
||||
t.Fatal("missing form, continuation or service limitation")
|
||||
}
|
||||
workflowSubmit(t, w, "connect", strings.Repeat("猫", 200))
|
||||
select {
|
||||
case call := <-f.calls:
|
||||
t.Fatal("invalid key started a connection", call.method)
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
func TestConnectionWorkflowSavedKeyIsLoadedOnlyExplicitly(t *testing.T) {
|
||||
c, f := fixtureCoordinator(t, nil)
|
||||
store, path, value := settingsFixture(t)
|
||||
target, _ := value.endpoint()
|
||||
key := "synthetic-saved-private-key"
|
||||
if err := store.rememberKey(target, key); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
w := workflowFixture(t, c, approve(t, c, f, 1, "controller"), target, store)
|
||||
assertSecretAbsent(t, w.form(), key)
|
||||
if w.key != "" {
|
||||
t.Fatal("opening a form loaded credentials")
|
||||
}
|
||||
result := workflowSubmit(t, w, "load-key", "ignored-private-entry")
|
||||
assertSecretAbsent(t, result, key)
|
||||
assertSecretAbsent(t, result, "ignored-private-entry")
|
||||
if w.key != key || result.Clipboard != nil {
|
||||
t.Fatal("explicit load failed or requested clipboard access")
|
||||
}
|
||||
select {
|
||||
case call := <-f.calls:
|
||||
t.Fatal("loading a key connected", call.method)
|
||||
default:
|
||||
}
|
||||
// Forget through the nested workflow clears the in-memory selection too.
|
||||
workflowSubmit(t, w, "saved-key-actions", "")
|
||||
result = workflowSubmit(t, w, "forget-key", "")
|
||||
assertSecretAbsent(t, result, key)
|
||||
if w.key != "" || w.mode != "credentials" {
|
||||
t.Fatal("Forget retained the loaded key or failed to return to Connect")
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(path, "channel-key.toml")); !os.IsNotExist(err) {
|
||||
t.Fatal("Forget did not remove the saved key")
|
||||
}
|
||||
workflowSubmit(t, w, "load-key", "")
|
||||
if w.key != "" {
|
||||
t.Fatal("missing key was reported as loaded")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConnectionWorkflowConnectUsesLoadedKeyWithoutEcho(t *testing.T) {
|
||||
for _, roleName := range []string{"controller", "controlled"} {
|
||||
t.Run(roleName, func(t *testing.T) {
|
||||
c, f := fixtureCoordinator(t, nil)
|
||||
certificate, roots := testCertificate(t, true)
|
||||
r := controller
|
||||
if roleName == "controlled" {
|
||||
r = controlled
|
||||
}
|
||||
joined := make(chan struct{})
|
||||
target := testRelay(t, certificate, func(connection net.Conn) {
|
||||
if relayHandshake(t, connection, r) == nil {
|
||||
return
|
||||
}
|
||||
_, _ = io.WriteString(connection, "{\"type\":\"channel_joined\",\"channel\":\"synthetic-fixture\",\"clients\":[]}\n")
|
||||
close(joined)
|
||||
_, _ = io.Copy(io.Discard, connection)
|
||||
})
|
||||
target.roots = roots
|
||||
store, _, _ := settingsFixture(t)
|
||||
if err := store.rememberKey(target, "synthetic-fixture"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
w := workflowFixture(t, c, approve(t, c, f, 1, roleName), target, store)
|
||||
workflowSubmit(t, w, "load-key", "")
|
||||
result := workflowSubmit(t, w, "connect", "")
|
||||
assertSecretAbsent(t, result, "synthetic-fixture")
|
||||
awaitDone(t, joined)
|
||||
nextCall(t, f, "remote.open")
|
||||
awaitStatus(t, c, func(s connectionStatus) bool { return s.state == "waiting" })
|
||||
result = workflowSubmit(t, w, "refresh", "")
|
||||
encoded, _ := json.Marshal(result)
|
||||
if !strings.Contains(string(encoded), "waiting for one opposite-role peer") || !strings.Contains(string(encoded), "Desktop services are unavailable") {
|
||||
t.Fatal("status advertised desktop control or omitted waiting state")
|
||||
}
|
||||
if w.key != "" {
|
||||
t.Fatal("connect retained a saved key")
|
||||
}
|
||||
workflowSubmit(t, w, "connect", "synthetic-second-attempt") // Old duplicate submission.
|
||||
workflowSubmit(t, w, "disconnect", "")
|
||||
nextCall(t, f, "remote.close")
|
||||
awaitStatus(t, c, func(s connectionStatus) bool { return s.state == "closed" })
|
||||
select {
|
||||
case call := <-f.calls:
|
||||
t.Fatal("duplicate Connect reused approval", call.method)
|
||||
default:
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestConnectionWorkflowLoadEndpointMismatchAndFailure(t *testing.T) {
|
||||
for _, mode := range []string{"other endpoint", "unsafe credential", "closed store"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
c, f := fixtureCoordinator(t, nil)
|
||||
store, path, value := settingsFixture(t)
|
||||
target, _ := value.endpoint()
|
||||
if err := store.rememberKey(target, "synthetic-private-key"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
switch mode {
|
||||
case "other endpoint":
|
||||
target.host = "other.invalid"
|
||||
case "unsafe credential":
|
||||
if err := os.Chmod(filepath.Join(path, "channel-key.toml"), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
case "closed store":
|
||||
store.close()
|
||||
}
|
||||
w := workflowFixture(t, c, approve(t, c, f, 1, "controller"), target, store)
|
||||
result := workflowSubmit(t, w, "load-key", "")
|
||||
assertSecretAbsent(t, result, "synthetic-private-key")
|
||||
if w.key != "" || result.Speech == "" {
|
||||
t.Fatal("load failed silently or crossed endpoint/permission boundary")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestConnectionWorkflowInspectionRequiresExplicitConnect(t *testing.T) {
|
||||
c, f := fixtureCoordinator(t, nil)
|
||||
certificate, _ := testCertificate(t, false)
|
||||
var connections atomic.Int32
|
||||
probeBytes := make(chan int, 1)
|
||||
target := testRelay(t, certificate, func(connection net.Conn) {
|
||||
if connections.Add(1) == 1 {
|
||||
data, _ := io.ReadAll(connection)
|
||||
probeBytes <- len(data)
|
||||
return
|
||||
}
|
||||
if relayHandshake(t, connection, controller) == nil {
|
||||
return
|
||||
}
|
||||
_, _ = io.WriteString(connection, "{\"type\":\"channel_joined\",\"channel\":\"synthetic-fixture\",\"clients\":[]}\n")
|
||||
_, _ = io.Copy(io.Discard, connection)
|
||||
})
|
||||
w := workflowFixture(t, c, approve(t, c, f, 1, "controller"), target, nil)
|
||||
result := workflowSubmit(t, w, "inspect-certificate", "must-not-survive-inspection")
|
||||
assertSecretAbsent(t, result, "must-not-survive-inspection")
|
||||
awaitDone(t, w.probeDone)
|
||||
select {
|
||||
case count := <-probeBytes:
|
||||
if count != 0 {
|
||||
t.Fatal("inspection sent a channel key")
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("inspection did not close")
|
||||
}
|
||||
result = workflowSubmit(t, w, "copy-fingerprint", "")
|
||||
digest := sha256.Sum256(certificate.Certificate[0])
|
||||
if result.Clipboard == nil || len(*result.Clipboard) != 64 || w.target.pin != nil || result.Next != "remote-connection" {
|
||||
t.Fatal("copy approved trust or lost continuation")
|
||||
}
|
||||
result = workflowSubmit(t, w, "trust-once", "")
|
||||
if w.target.pin == nil || w.target.pin.sha256 != digest || result.Form == nil || w.mode != "credentials" {
|
||||
t.Fatal("review did not return to explicit Connect")
|
||||
}
|
||||
if connections.Load() != 1 {
|
||||
t.Fatal("trust action automatically connected")
|
||||
}
|
||||
select {
|
||||
case call := <-f.calls:
|
||||
t.Fatal("trust action opened a lease", call.method)
|
||||
default:
|
||||
}
|
||||
workflowSubmit(t, w, "connect", "synthetic-fixture")
|
||||
nextCall(t, f, "remote.open")
|
||||
awaitStatus(t, c, func(s connectionStatus) bool { return s.state == "waiting" })
|
||||
if connections.Load() != 2 {
|
||||
t.Fatal("Connect reused inspection socket")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConnectionWorkflowStalledInspectionCancelledByLifecycle(t *testing.T) {
|
||||
for _, mode := range []string{"form close", "parent cancel", "replacement", "SDK EOF"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
c, f := fixtureCoordinator(t, nil)
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { listener.Close() })
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
defer cancel()
|
||||
w, err := new_connection_workflow(ctx, c, approve(t, c, f, 1, "controller"), endpoint{host: "127.0.0.1", port: listener.Addr().(*net.TCPAddr).Port}, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { w.close(); awaitDone(t, w.done) })
|
||||
workflowSubmit(t, w, "inspect-certificate", "")
|
||||
connection, err := listener.Accept()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer connection.Close()
|
||||
closed := make(chan struct{})
|
||||
go func() { _, _ = io.Copy(io.Discard, connection); close(closed) }()
|
||||
switch mode {
|
||||
case "form close":
|
||||
_, _ = w.submit(t.Context(), sdk.Submission{Cancelled: true})
|
||||
case "parent cancel":
|
||||
cancel()
|
||||
case "replacement":
|
||||
approve(t, c, f, 2, "controller")
|
||||
case "SDK EOF":
|
||||
close(f.events)
|
||||
}
|
||||
awaitDone(t, w.probeDone)
|
||||
awaitDone(t, w.done)
|
||||
awaitDone(t, closed)
|
||||
if result := workflowSubmit(t, w, "trust-once", ""); !result.Done {
|
||||
t.Fatal("retired inspection could be approved")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestConnectionWorkflowCancellationPreventsSavedKeyEffects(t *testing.T) {
|
||||
for _, mode := range []string{"form", "handler", "replacement"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
c, f := fixtureCoordinator(t, nil)
|
||||
store, path, value := settingsFixture(t)
|
||||
target, _ := value.endpoint()
|
||||
w := workflowFixture(t, c, approve(t, c, f, 1, "controller"), target, store)
|
||||
workflowSubmit(t, w, "saved-key-actions", "")
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
defer cancel()
|
||||
submission := sdk.Submission{Activated: "remember-key", Values: map[string]sdk.Value{"channel-key": {Text: "synthetic-private-key"}}}
|
||||
switch mode {
|
||||
case "form":
|
||||
submission.Cancelled = true
|
||||
case "handler":
|
||||
cancel()
|
||||
case "replacement":
|
||||
approve(t, c, f, 2, "controller")
|
||||
}
|
||||
result, _ := w.submit(ctx, submission)
|
||||
if !result.Done {
|
||||
t.Fatal("cancelled action retained a form")
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(path, "channel-key.toml")); !os.IsNotExist(err) {
|
||||
t.Fatal("cancelled workflow saved credentials")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestConnectionWorkflowOldStatusCannotDisconnectNewEpoch(t *testing.T) {
|
||||
c, f := fixtureCoordinator(t, nil)
|
||||
certificate, roots := testCertificate(t, true)
|
||||
target := testRelay(t, certificate, func(connection net.Conn) {
|
||||
if relayHandshake(t, connection, controller) == nil {
|
||||
return
|
||||
}
|
||||
_, _ = io.WriteString(connection, "{\"type\":\"channel_joined\",\"channel\":\"synthetic-fixture\",\"clients\":[]}\n")
|
||||
_, _ = io.Copy(io.Discard, connection)
|
||||
})
|
||||
target.roots = roots
|
||||
old := workflowFixture(t, c, approve(t, c, f, 1, "controller"), target, nil)
|
||||
workflowSubmit(t, old, "connect", "synthetic-fixture")
|
||||
nextCall(t, f, "remote.open")
|
||||
awaitStatus(t, c, func(s connectionStatus) bool { return s.state == "waiting" })
|
||||
fresh := approve(t, c, f, 2, "controller")
|
||||
nextCall(t, f, "remote.close")
|
||||
awaitStatus(t, c, func(s connectionStatus) bool { return s.state == "failed" })
|
||||
w := workflowFixture(t, c, fresh, target, nil)
|
||||
workflowSubmit(t, w, "connect", "synthetic-fixture")
|
||||
nextCall(t, f, "remote.open")
|
||||
awaitStatus(t, c, func(s connectionStatus) bool { return s.epoch == 2 && s.state == "waiting" })
|
||||
workflowSubmit(t, old, "disconnect", "")
|
||||
workflowSubmit(t, old, "cancel", "")
|
||||
if status := c.snapshot(); status.epoch != 2 || status.state != "waiting" {
|
||||
t.Fatal("old status controls disconnected a new connection", status)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,372 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
package remote
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"slices"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
sdk "git.stormux.org/storm/cthulhu/sdk/go/tentacle"
|
||||
)
|
||||
|
||||
var errLease = errors.New("remote reader access unavailable or revoked")
|
||||
|
||||
// sessionClient is the public SDK boundary, also used by private fixtures. The
|
||||
// coordinator must be the only Events consumer for the process session.
|
||||
type sessionClient interface {
|
||||
Call(context.Context, string, any, any) error
|
||||
Events() <-chan sdk.SessionEvent
|
||||
}
|
||||
|
||||
var _ sessionClient = (*sdk.SessionClient)(nil)
|
||||
|
||||
type connectionStatus struct {
|
||||
state string // idle, opening, connecting, waiting, ready, stopping, closed, failed
|
||||
epoch uint64
|
||||
peer int
|
||||
ignored uint64
|
||||
err error // Local constant errors only; never RPC/server diagnostic text.
|
||||
}
|
||||
|
||||
type connectionAttempt struct {
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
done chan struct{}
|
||||
epoch uint64
|
||||
err error // Protected by coordinator.mu.
|
||||
}
|
||||
|
||||
// coordinator joins reader consent and relay lifetime; it performs no desktop
|
||||
// effects. A fresh core action AND an explicit connect call are required for
|
||||
// every attempt. It never loads credentials, saves trust, or retries a network.
|
||||
type coordinator struct {
|
||||
client sessionClient
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
done chan struct{}
|
||||
actions chan sdk.SessionEvent
|
||||
|
||||
mu sync.Mutex
|
||||
pending sdk.SessionEvent
|
||||
pendingCtx context.Context
|
||||
pendingStop context.CancelFunc
|
||||
setupClaimed bool
|
||||
active *connectionAttempt
|
||||
status connectionStatus
|
||||
unavailable bool // Failed close cannot be followed by another connection.
|
||||
}
|
||||
|
||||
func newCoordinator(ctx context.Context, client sessionClient) *coordinator {
|
||||
lifetime, cancel := context.WithCancel(ctx)
|
||||
c := &coordinator{client: client, ctx: lifetime, cancel: cancel, done: make(chan struct{}), actions: make(chan sdk.SessionEvent, 1), status: connectionStatus{state: "idle"}}
|
||||
go c.read_events()
|
||||
return c
|
||||
}
|
||||
|
||||
// actions carries approval metadata, not an instruction to connect. A newer
|
||||
// action supersedes an unread one. Copy slices so callers cannot alter consent.
|
||||
func (c *coordinator) read_events() {
|
||||
defer close(c.done)
|
||||
defer close(c.actions)
|
||||
defer c.cancel()
|
||||
defer func() {
|
||||
c.mu.Lock()
|
||||
c.unavailable = true
|
||||
c.clear_pending_locked()
|
||||
c.stop_locked(errLease)
|
||||
c.mu.Unlock()
|
||||
}()
|
||||
for {
|
||||
select {
|
||||
case <-c.ctx.Done():
|
||||
return
|
||||
case event, ok := <-c.client.Events():
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
c.mu.Lock()
|
||||
switch event.Kind {
|
||||
case "remote.action":
|
||||
c.stop_locked(errLease)
|
||||
c.clear_pending_locked()
|
||||
c.pending = event
|
||||
c.pendingCtx, c.pendingStop = context.WithCancel(c.ctx)
|
||||
c.pending.Grants = slices.Clone(event.Grants)
|
||||
event.Grants = slices.Clone(event.Grants)
|
||||
select {
|
||||
case <-c.actions:
|
||||
default:
|
||||
}
|
||||
c.actions <- event
|
||||
case "remote.revoked":
|
||||
if event.Epoch == c.pending.Epoch {
|
||||
c.clear_pending_locked()
|
||||
}
|
||||
// Epoch matching also handles revoke racing remote.open's reply.
|
||||
if c.active != nil && event.Epoch == c.active.epoch {
|
||||
c.stop_locked(errLease)
|
||||
}
|
||||
}
|
||||
c.mu.Unlock()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *coordinator) snapshot() connectionStatus {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
return c.status
|
||||
}
|
||||
|
||||
func (c *coordinator) clear_pending_locked() {
|
||||
if c.pendingStop != nil {
|
||||
c.pendingStop()
|
||||
}
|
||||
c.pending, c.pendingCtx, c.pendingStop = sdk.SessionEvent{}, nil, nil
|
||||
c.setupClaimed = false
|
||||
}
|
||||
|
||||
// claim_approval binds one setup workflow to an action received from the SDK.
|
||||
// The lifetime ends on replacement, consumption, disconnect or session loss.
|
||||
// Role/grants in the caller's copy are never authoritative.
|
||||
func (c *coordinator) claim_approval(action sdk.SessionEvent) (sdk.SessionEvent, context.Context, error) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if c.ctx.Err() != nil || c.unavailable || c.active != nil || c.setupClaimed || c.pending.Action == "" || action.Action != c.pending.Action || action.Epoch != c.pending.Epoch {
|
||||
return sdk.SessionEvent{}, nil, errLease
|
||||
}
|
||||
approval := c.pending
|
||||
approval.Grants = slices.Clone(approval.Grants)
|
||||
c.setupClaimed = true
|
||||
return approval, c.pendingCtx, nil
|
||||
}
|
||||
|
||||
// connect returns after scheduling bounded background work. Only a token from
|
||||
// this SDK's event stream can consume pending approval; the stored role/grants
|
||||
// are authoritative. endpoint already contains any explicit local trust choice.
|
||||
func (c *coordinator) connect(action sdk.SessionEvent, e endpoint, key string) error {
|
||||
if _, err := e.tlsConfig(); err != nil {
|
||||
return err
|
||||
}
|
||||
if !validChannelKey(key) {
|
||||
return errProtocol
|
||||
}
|
||||
// Freeze caller-owned TLS options before handing them to a worker.
|
||||
if e.pin != nil {
|
||||
pin := *e.pin
|
||||
e.pin = &pin
|
||||
}
|
||||
if e.roots != nil {
|
||||
e.roots = e.roots.Clone()
|
||||
}
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if c.ctx.Err() != nil || c.unavailable || c.active != nil || c.pending.Action == "" || action.Action != c.pending.Action || action.Epoch != c.pending.Epoch {
|
||||
return errLease
|
||||
}
|
||||
approval := c.pending
|
||||
c.clear_pending_locked() // Single-use even if open or TLS fails.
|
||||
ctx, cancel := context.WithCancel(c.ctx)
|
||||
a := &connectionAttempt{ctx: ctx, cancel: cancel, done: make(chan struct{}), epoch: approval.Epoch}
|
||||
c.active, c.status = a, connectionStatus{state: "opening", epoch: a.epoch}
|
||||
go c.run(a, approval, e, key)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *coordinator) stop_locked(err error) {
|
||||
if c.active != nil {
|
||||
if c.active.ctx.Err() == nil {
|
||||
c.active.err = err
|
||||
}
|
||||
c.active.cancel() // Socket cancellation never waits for reader RPC cleanup.
|
||||
c.status.state, c.status.peer = "stopping", 0
|
||||
}
|
||||
}
|
||||
|
||||
// disconnect starts immediate relay cancellation and returns a completion
|
||||
// barrier. A new connection is refused until lease-close cleanup has finished.
|
||||
func (c *coordinator) disconnect() <-chan struct{} {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
c.clear_pending_locked()
|
||||
if c.active == nil {
|
||||
done := make(chan struct{})
|
||||
close(done)
|
||||
return done
|
||||
}
|
||||
c.stop_locked(nil)
|
||||
return c.active.done
|
||||
}
|
||||
|
||||
// A stale form must never disconnect a newer approval or connection. Unlike
|
||||
// disconnect, this operation retires only the workflow's original epoch.
|
||||
func (c *coordinator) disconnect_epoch(epoch uint64) <-chan struct{} {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if epoch != 0 && c.pending.Epoch == epoch {
|
||||
c.clear_pending_locked()
|
||||
}
|
||||
if c.active != nil && c.active.epoch == epoch {
|
||||
c.stop_locked(nil)
|
||||
return c.active.done
|
||||
}
|
||||
done := make(chan struct{})
|
||||
close(done)
|
||||
return done
|
||||
}
|
||||
|
||||
// close ends the event owner too. Callers may wait on done and disconnect's
|
||||
// barrier before disposing the process session; neither path needs the relay.
|
||||
func (c *coordinator) close() { c.cancel() }
|
||||
|
||||
func (c *coordinator) update(a *connectionAttempt, s *session) bool {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if a.ctx.Err() != nil {
|
||||
return false
|
||||
}
|
||||
c.status.state, c.status.peer, c.status.ignored = s.state, s.peer.ID, s.ignored
|
||||
return true
|
||||
}
|
||||
|
||||
// Never cancel a healthy SDK call just to disconnect the relay: SDK call
|
||||
// cancellation deliberately retires the entire Tentacle process session. Calls
|
||||
// finish within two seconds independently; all lease operations are serialized.
|
||||
func (c *coordinator) call(method string, params, result any) error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
defer cancel()
|
||||
if c.client.Call(ctx, method, params, result) != nil {
|
||||
return errLease
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *coordinator) run(a *connectionAttempt, approval sdk.SessionEvent, e endpoint, key string) {
|
||||
var lease sdk.RemoteLease
|
||||
var conn *relayConn
|
||||
var sequence uint64
|
||||
var heartbeatDone chan struct{}
|
||||
var failure error
|
||||
defer func() {
|
||||
// Stop relay and heartbeat admission before serializing the final close.
|
||||
c.mu.Lock()
|
||||
c.stop_locked(failure)
|
||||
c.mu.Unlock()
|
||||
if conn != nil {
|
||||
conn.close()
|
||||
}
|
||||
if heartbeatDone != nil {
|
||||
<-heartbeatDone
|
||||
}
|
||||
closeFailed := false
|
||||
if lease.Lease != "" {
|
||||
sequence++
|
||||
closeFailed = c.call("remote.close", sdk.RemoteOperation{Lease: lease.Lease, Epoch: a.epoch, Sequence: sequence}, nil) != nil
|
||||
}
|
||||
c.mu.Lock()
|
||||
if a.err != nil {
|
||||
failure = a.err
|
||||
}
|
||||
if closeFailed {
|
||||
c.unavailable, failure = true, errLease
|
||||
}
|
||||
c.status.state, c.status.peer, c.status.err = "closed", 0, failure
|
||||
if failure != nil {
|
||||
c.status.state = "failed"
|
||||
}
|
||||
c.active = nil
|
||||
close(a.done)
|
||||
c.mu.Unlock()
|
||||
}()
|
||||
if a.ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
if err := c.call("remote.open", sdk.RemoteOpen{Action: approval.Action, Epoch: approval.Epoch, Role: approval.Role, Grants: approval.Grants}, &lease); err != nil {
|
||||
failure = err
|
||||
return
|
||||
}
|
||||
if len(lease.Lease) != 32 || lease.Epoch != a.epoch {
|
||||
failure = errLease
|
||||
c.mu.Lock()
|
||||
c.unavailable = true
|
||||
c.mu.Unlock()
|
||||
return
|
||||
}
|
||||
if a.ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
r := controller
|
||||
if approval.Role == "controlled" {
|
||||
r = controlled
|
||||
}
|
||||
s, err := newSession(r, a.epoch)
|
||||
if err != nil {
|
||||
failure = err
|
||||
return
|
||||
}
|
||||
c.mu.Lock()
|
||||
if a.ctx.Err() == nil {
|
||||
c.status.state = "connecting"
|
||||
}
|
||||
c.mu.Unlock()
|
||||
heartbeatDone = make(chan struct{})
|
||||
go func() {
|
||||
defer close(heartbeatDone)
|
||||
ticker := time.NewTicker(time.Second)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-a.ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
if a.ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
sequence++
|
||||
if c.call("remote.heartbeat", sdk.RemoteOperation{Lease: lease.Lease, Epoch: a.epoch, Sequence: sequence}, nil) != nil {
|
||||
c.mu.Lock()
|
||||
c.stop_locked(errLease)
|
||||
c.mu.Unlock()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
var joined message
|
||||
conn, joined, failure = connect(a.ctx, e, r, key)
|
||||
key = "" // Do not retain credentials for any reconnect path.
|
||||
if failure != nil {
|
||||
if a.ctx.Err() != nil {
|
||||
failure = nil
|
||||
}
|
||||
return
|
||||
}
|
||||
if _, failure = s.accept(a.epoch, joined); failure != nil || !c.update(a, s) {
|
||||
return
|
||||
}
|
||||
for a.ctx.Err() == nil {
|
||||
m, err := conn.read()
|
||||
if err != nil {
|
||||
if a.ctx.Err() == nil {
|
||||
failure = err
|
||||
}
|
||||
return
|
||||
}
|
||||
accepted, err := s.accept(a.epoch, m)
|
||||
if err != nil {
|
||||
failure = err
|
||||
return
|
||||
}
|
||||
// Desktop services are not implemented. Retain no payload and expose no
|
||||
// effect queue which could be mistaken for delivery-time authorization.
|
||||
if accepted && s.ignored != ^uint64(0) {
|
||||
s.ignored++
|
||||
}
|
||||
if !c.update(a, s) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,500 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
package remote
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
sdk "git.stormux.org/storm/cthulhu/sdk/go/tentacle"
|
||||
)
|
||||
|
||||
type readerCall struct {
|
||||
method string
|
||||
params any
|
||||
}
|
||||
|
||||
type fixtureClient struct {
|
||||
events chan sdk.SessionEvent
|
||||
calls chan readerCall
|
||||
hook func(context.Context, string, any, any) error
|
||||
}
|
||||
|
||||
func (f *fixtureClient) Events() <-chan sdk.SessionEvent { return f.events }
|
||||
|
||||
func (f *fixtureClient) Call(ctx context.Context, method string, params, result any) error {
|
||||
f.calls <- readerCall{method, params}
|
||||
if f.hook != nil {
|
||||
return f.hook(ctx, method, params, result)
|
||||
}
|
||||
if method == "remote.open" {
|
||||
*result.(*sdk.RemoteLease) = sdk.RemoteLease{Lease: strings.Repeat("b", 32), Epoch: params.(sdk.RemoteOpen).Epoch}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func fixtureCoordinator(t *testing.T, hook func(context.Context, string, any, any) error) (*coordinator, *fixtureClient) {
|
||||
t.Helper()
|
||||
f := &fixtureClient{events: make(chan sdk.SessionEvent, 8), calls: make(chan readerCall, 32), hook: hook}
|
||||
c := newCoordinator(t.Context(), f)
|
||||
t.Cleanup(func() {
|
||||
barrier := c.disconnect()
|
||||
c.close()
|
||||
awaitDone(t, barrier)
|
||||
awaitDone(t, c.done)
|
||||
})
|
||||
return c, f
|
||||
}
|
||||
|
||||
func awaitDone(t *testing.T, done <-chan struct{}) {
|
||||
t.Helper()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("cleanup did not finish")
|
||||
}
|
||||
}
|
||||
|
||||
func nextCall(t *testing.T, f *fixtureClient, method string) readerCall {
|
||||
t.Helper()
|
||||
select {
|
||||
case call := <-f.calls:
|
||||
if call.method != method {
|
||||
t.Fatalf("got %s, want %s", call.method, method)
|
||||
}
|
||||
return call
|
||||
case <-time.After(4 * time.Second):
|
||||
t.Fatalf("missing %s", method)
|
||||
return readerCall{}
|
||||
}
|
||||
}
|
||||
|
||||
func approve(t *testing.T, c *coordinator, f *fixtureClient, epoch uint64, role string) sdk.SessionEvent {
|
||||
t.Helper()
|
||||
grant := "remote-present"
|
||||
if role == "controlled" {
|
||||
grant = "output-observe"
|
||||
}
|
||||
f.events <- sdk.SessionEvent{Sequence: epoch, Kind: "remote.action", Action: strings.Repeat("a", 32), Epoch: epoch, Role: role, Grants: []string{grant}}
|
||||
select {
|
||||
case event := <-c.actions:
|
||||
return event
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("missing action")
|
||||
return sdk.SessionEvent{}
|
||||
}
|
||||
}
|
||||
|
||||
func awaitStatus(t *testing.T, c *coordinator, predicate func(connectionStatus) bool) connectionStatus {
|
||||
t.Helper()
|
||||
deadline := time.NewTimer(4 * time.Second)
|
||||
defer deadline.Stop()
|
||||
ticker := time.NewTicker(time.Millisecond)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
status := c.snapshot()
|
||||
if predicate(status) {
|
||||
return status
|
||||
}
|
||||
select {
|
||||
case <-deadline.C:
|
||||
t.Fatalf("unexpected status: %+v", status)
|
||||
case <-ticker.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCoordinatorRequiresFreshReaderAction(t *testing.T) {
|
||||
c, f := fixtureCoordinator(t, nil)
|
||||
e := endpoint{host: "localhost", port: 6837}
|
||||
if err := c.connect(sdk.SessionEvent{}, e, "synthetic-fixture"); err != errLease {
|
||||
t.Fatal("connected without action", err)
|
||||
}
|
||||
action := approve(t, c, f, 1, "controller")
|
||||
wrong := action
|
||||
wrong.Epoch++
|
||||
if err := c.connect(wrong, e, "synthetic-fixture"); err != errLease {
|
||||
t.Fatal("accepted stale token", err)
|
||||
}
|
||||
awaitDone(t, c.disconnect())
|
||||
if err := c.connect(action, e, "synthetic-fixture"); err != errLease {
|
||||
t.Fatal("disconnect retained unused approval", err)
|
||||
}
|
||||
select {
|
||||
case call := <-f.calls:
|
||||
t.Fatal("unexpected reader request", call.method)
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
func TestCoordinatorDenialMakesNoRelayConnection(t *testing.T) {
|
||||
c, f := fixtureCoordinator(t, func(context.Context, string, any, any) error {
|
||||
return errors.New("private RPC content must not escape")
|
||||
})
|
||||
action := approve(t, c, f, 1, "controller")
|
||||
cert, _ := testCertificate(t, true)
|
||||
connected := make(chan struct{}, 1)
|
||||
e := testRelay(t, cert, func(net.Conn) { connected <- struct{}{} })
|
||||
if err := c.connect(action, e, "synthetic-fixture"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
nextCall(t, f, "remote.open")
|
||||
status := awaitStatus(t, c, func(s connectionStatus) bool { return s.state == "failed" })
|
||||
if status.err != errLease {
|
||||
t.Fatal("exposed upstream error", status.err)
|
||||
}
|
||||
if err := c.connect(action, e, "synthetic-fixture"); err != errLease {
|
||||
t.Fatal("retried consumed consent", err)
|
||||
}
|
||||
select {
|
||||
case <-connected:
|
||||
t.Fatal("network before consent")
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
func TestCoordinatorMembershipFailureAndExplicitReconnect(t *testing.T) {
|
||||
cert, roots := testCertificate(t, true)
|
||||
for _, roleName := range []string{"controller", "controlled"} {
|
||||
t.Run(roleName, func(t *testing.T) {
|
||||
c, f := fixtureCoordinator(t, nil)
|
||||
action := approve(t, c, f, 1, roleName)
|
||||
depart := make(chan struct{})
|
||||
var once sync.Once
|
||||
t.Cleanup(func() { once.Do(func() { close(depart) }) })
|
||||
r, peerRole, effect := controller, "slave", `{"type":"speak","origin":7,"sequence":["private fixture"]}`
|
||||
if roleName == "controlled" {
|
||||
r, peerRole, effect = controlled, "master", `{"type":"key","origin":7,"vk_code":65,"extended":false,"pressed":true}`
|
||||
}
|
||||
e := testRelay(t, cert, func(conn net.Conn) {
|
||||
if relayHandshake(t, conn, r) == nil {
|
||||
return
|
||||
}
|
||||
_, _ = io.WriteString(conn, `{"type":"channel_joined","channel":"synthetic-fixture","clients":[{"id":7,"connection_type":"`+peerRole+`"}]}`+"\n"+effect+"\n")
|
||||
select {
|
||||
case <-depart:
|
||||
case <-time.After(5 * time.Second):
|
||||
return
|
||||
}
|
||||
_, _ = io.WriteString(conn, "{\"type\":\"client_left\",\"user_id\":7}\n")
|
||||
_, _ = io.Copy(io.Discard, conn)
|
||||
})
|
||||
e.roots = roots
|
||||
// Caller mutation cannot change the role or approved grants.
|
||||
action.Role, action.Grants[0] = "untrusted", "keyboard-inject"
|
||||
if err := c.connect(action, e, "synthetic-fixture"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
open := nextCall(t, f, "remote.open").params.(sdk.RemoteOpen)
|
||||
if open.Role != roleName || open.Grants[0] == "keyboard-inject" {
|
||||
t.Fatal("caller changed approval")
|
||||
}
|
||||
awaitStatus(t, c, func(s connectionStatus) bool { return s.state == "ready" && s.ignored == 1 })
|
||||
if err := c.connect(action, e, "synthetic-fixture"); err != errLease {
|
||||
t.Fatal("concurrent connect", err)
|
||||
}
|
||||
once.Do(func() { close(depart) })
|
||||
closed := nextCall(t, f, "remote.close").params.(sdk.RemoteOperation)
|
||||
if closed.Epoch != 1 || closed.Sequence != 1 {
|
||||
t.Fatal("bad close ownership", closed)
|
||||
}
|
||||
awaitStatus(t, c, func(s connectionStatus) bool { return s.state == "failed" })
|
||||
if err := c.connect(action, e, "synthetic-fixture"); err != errLease {
|
||||
t.Fatal("reconnected automatically", err)
|
||||
}
|
||||
fresh := approve(t, c, f, 2, roleName)
|
||||
if err := c.connect(fresh, e, "synthetic-fixture"); err != nil {
|
||||
t.Fatal("fresh local action refused", err)
|
||||
}
|
||||
nextCall(t, f, "remote.open")
|
||||
nextCall(t, f, "remote.close")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCoordinatorRevokedDuringOpen(t *testing.T) {
|
||||
opened, release := make(chan struct{}), make(chan struct{})
|
||||
c, f := fixtureCoordinator(t, func(ctx context.Context, method string, params, result any) error {
|
||||
if method == "remote.open" {
|
||||
close(opened)
|
||||
select {
|
||||
case <-release:
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
*result.(*sdk.RemoteLease) = sdk.RemoteLease{Lease: strings.Repeat("b", 32), Epoch: 1}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
action := approve(t, c, f, 1, "controller")
|
||||
if err := c.connect(action, endpoint{host: "localhost", port: 6837}, "synthetic-fixture"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
awaitDone(t, opened)
|
||||
f.events <- sdk.SessionEvent{Kind: "remote.revoked", Epoch: 1, Lease: strings.Repeat("b", 32)}
|
||||
awaitStatus(t, c, func(s connectionStatus) bool { return s.state == "stopping" })
|
||||
close(release)
|
||||
nextCall(t, f, "remote.open")
|
||||
nextCall(t, f, "remote.close")
|
||||
status := awaitStatus(t, c, func(s connectionStatus) bool { return s.state == "failed" })
|
||||
if status.err != errLease {
|
||||
t.Fatal(status.err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCoordinatorHeartbeatWhileTLSStalls(t *testing.T) {
|
||||
for _, finish := range []string{"disconnect", "heartbeat failure", "SDK EOF", "replacement", "parent cancel"} {
|
||||
t.Run(finish, func(t *testing.T) {
|
||||
c, f := fixtureCoordinator(t, nil)
|
||||
if finish == "heartbeat failure" {
|
||||
f.hook = func(_ context.Context, method string, params, result any) error {
|
||||
if method == "remote.open" {
|
||||
*result.(*sdk.RemoteLease) = sdk.RemoteLease{Lease: strings.Repeat("b", 32), Epoch: 1}
|
||||
}
|
||||
if method == "remote.heartbeat" {
|
||||
return errLease
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
action := approve(t, c, f, 1, "controller")
|
||||
cert, _ := testCertificate(t, true)
|
||||
connected, closed := make(chan struct{}), make(chan struct{})
|
||||
e := testRelay(t, cert, func(conn net.Conn) {
|
||||
close(connected)
|
||||
// Do not start TLS: consume raw bytes and wait for socket EOF.
|
||||
_, _ = io.Copy(io.Discard, conn.(*tls.Conn).NetConn())
|
||||
close(closed)
|
||||
})
|
||||
if err := c.connect(action, e, "synthetic-fixture"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
nextCall(t, f, "remote.open")
|
||||
awaitDone(t, connected)
|
||||
heartbeat := nextCall(t, f, "remote.heartbeat").params.(sdk.RemoteOperation)
|
||||
if heartbeat.Sequence != 1 || heartbeat.Epoch != 1 {
|
||||
t.Fatal("bad heartbeat", heartbeat)
|
||||
}
|
||||
switch finish {
|
||||
case "disconnect":
|
||||
awaitDone(t, c.disconnect())
|
||||
case "SDK EOF":
|
||||
close(f.events)
|
||||
case "replacement":
|
||||
approve(t, c, f, 2, "controller")
|
||||
case "parent cancel":
|
||||
c.close()
|
||||
}
|
||||
awaitDone(t, closed)
|
||||
closeCall := nextCall(t, f, "remote.close").params.(sdk.RemoteOperation)
|
||||
if closeCall.Sequence != 2 {
|
||||
t.Fatal("close raced heartbeat", closeCall)
|
||||
}
|
||||
awaitStatus(t, c, func(s connectionStatus) bool { return s.state == "failed" || s.state == "closed" })
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCoordinatorFailedCloseBlocksNewConsent(t *testing.T) {
|
||||
c, f := fixtureCoordinator(t, func(_ context.Context, method string, params, result any) error {
|
||||
if method == "remote.open" {
|
||||
*result.(*sdk.RemoteLease) = sdk.RemoteLease{Lease: strings.Repeat("b", 32), Epoch: 1}
|
||||
}
|
||||
if method == "remote.close" {
|
||||
return errLease
|
||||
}
|
||||
return nil
|
||||
})
|
||||
action := approve(t, c, f, 1, "controller")
|
||||
cert, _ := testCertificate(t, false)
|
||||
e := testRelay(t, cert, func(conn net.Conn) { _, _ = io.Copy(io.Discard, conn) })
|
||||
if err := c.connect(action, e, "synthetic-fixture"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
nextCall(t, f, "remote.open")
|
||||
nextCall(t, f, "remote.close")
|
||||
awaitStatus(t, c, func(s connectionStatus) bool { return s.state == "failed" })
|
||||
fresh := approve(t, c, f, 2, "controller")
|
||||
if err := c.connect(fresh, e, "synthetic-fixture"); err != errLease {
|
||||
t.Fatal("failed close allowed reconnect", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCoordinatorDisconnectWaitsForHeartbeatWithoutCancellingSDK(t *testing.T) {
|
||||
heartbeatStarted, heartbeatRelease := make(chan struct{}), make(chan struct{})
|
||||
var releaseOnce sync.Once
|
||||
t.Cleanup(func() { releaseOnce.Do(func() { close(heartbeatRelease) }) })
|
||||
c, f := fixtureCoordinator(t, func(ctx context.Context, method string, params, result any) error {
|
||||
if method == "remote.open" {
|
||||
*result.(*sdk.RemoteLease) = sdk.RemoteLease{Lease: strings.Repeat("b", 32), Epoch: 1}
|
||||
}
|
||||
if method == "remote.heartbeat" {
|
||||
close(heartbeatStarted)
|
||||
select {
|
||||
case <-heartbeatRelease:
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
t.Error("disconnect cancelled an in-flight SDK call")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
action := approve(t, c, f, 1, "controller")
|
||||
cert, roots := testCertificate(t, true)
|
||||
closed := make(chan struct{})
|
||||
e := testRelay(t, cert, func(conn net.Conn) {
|
||||
if relayHandshake(t, conn, controller) == nil {
|
||||
return
|
||||
}
|
||||
_, _ = io.WriteString(conn, "{\"type\":\"channel_joined\",\"channel\":\"synthetic-fixture\",\"clients\":[]}\n")
|
||||
_, _ = io.Copy(io.Discard, conn)
|
||||
close(closed)
|
||||
})
|
||||
e.roots = roots
|
||||
if err := c.connect(action, e, "synthetic-fixture"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
nextCall(t, f, "remote.open")
|
||||
awaitStatus(t, c, func(s connectionStatus) bool { return s.state == "waiting" && s.peer == 0 })
|
||||
awaitDone(t, heartbeatStarted)
|
||||
barrier := c.disconnect()
|
||||
awaitDone(t, closed) // Relay closes before the blocked heartbeat completes.
|
||||
select {
|
||||
case <-barrier:
|
||||
t.Fatal("cleanup completed before heartbeat")
|
||||
default:
|
||||
}
|
||||
if status := c.snapshot(); status.state != "stopping" || status.peer != 0 {
|
||||
t.Fatal("stale readiness during cleanup", status)
|
||||
}
|
||||
fresh := approve(t, c, f, 2, "controller")
|
||||
if err := c.connect(fresh, e, "synthetic-fixture"); err != errLease {
|
||||
t.Fatal("new connection raced unfinished close", err)
|
||||
}
|
||||
releaseOnce.Do(func() { close(heartbeatRelease) })
|
||||
nextCall(t, f, "remote.heartbeat")
|
||||
nextCall(t, f, "remote.close")
|
||||
awaitDone(t, barrier)
|
||||
}
|
||||
|
||||
// Exercise the actual public SDK framing, replies and event stream over owned
|
||||
// pipes. The host here is a synthetic lifecycle peer, not a production consent
|
||||
// issuer; core authorizer conformance is tested separately in the reader.
|
||||
func TestCoordinatorPublicSDKPipes(t *testing.T) {
|
||||
hostInput, childOutput := io.Pipe()
|
||||
childInput, hostOutput := io.Pipe()
|
||||
client := sdk.NewSessionClient()
|
||||
sdkDone, hostDone := make(chan struct{}), make(chan struct{})
|
||||
go func() {
|
||||
defer close(sdkDone)
|
||||
commands := []sdk.Command{{ID: "status", Title: "Status", Handle: func(context.Context, json.RawMessage) (any, error) { return nil, nil }}}
|
||||
_ = sdk.ServeSession(childInput, childOutput, commands, nil, client)
|
||||
}()
|
||||
var writerMu sync.Mutex
|
||||
send := func(value any) error {
|
||||
writerMu.Lock()
|
||||
defer writerMu.Unlock()
|
||||
return json.NewEncoder(hostOutput).Encode(value)
|
||||
}
|
||||
registered := make(chan struct{})
|
||||
calls := make(chan string, 8)
|
||||
go func() {
|
||||
defer close(hostDone)
|
||||
decoder := json.NewDecoder(bufio.NewReader(hostInput))
|
||||
var registration map[string]any
|
||||
if decoder.Decode(®istration) != nil {
|
||||
return
|
||||
}
|
||||
close(registered)
|
||||
for {
|
||||
var request struct {
|
||||
ID string `json:"id"`
|
||||
Method string `json:"method"`
|
||||
Params json.RawMessage `json:"params"`
|
||||
}
|
||||
if decoder.Decode(&request) != nil {
|
||||
return
|
||||
}
|
||||
calls <- request.Method
|
||||
result := any(map[string]any{})
|
||||
if request.Method == "remote.open" {
|
||||
var open sdk.RemoteOpen
|
||||
if json.Unmarshal(request.Params, &open) != nil || open.Role != "controller" {
|
||||
return
|
||||
}
|
||||
result = sdk.RemoteLease{Lease: strings.Repeat("b", 32), Epoch: open.Epoch}
|
||||
}
|
||||
if send(map[string]any{"jsonrpc": "2.0", "id": request.ID, "result": result}) != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
t.Cleanup(func() {
|
||||
hostInput.Close()
|
||||
hostOutput.Close()
|
||||
awaitDone(t, sdkDone)
|
||||
awaitDone(t, hostDone)
|
||||
})
|
||||
initialize := `{"jsonrpc":"2.0","id":"1","method":"initialize","params":{"protocol":{"major":1,"minor":1},"session":"fixture","apis":["commands","session-events","remote-access"],"capabilities":["remote-present"]}}`
|
||||
if _, err := io.WriteString(hostOutput, initialize+"\n"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
awaitDone(t, registered)
|
||||
if err := send(map[string]any{"jsonrpc": "2.0", "method": "initialized", "params": map[string]string{"session": "fixture"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c := newCoordinator(t.Context(), client)
|
||||
t.Cleanup(func() {
|
||||
barrier := c.disconnect()
|
||||
c.close()
|
||||
awaitDone(t, barrier)
|
||||
awaitDone(t, c.done)
|
||||
})
|
||||
action := sdk.SessionEvent{Kind: "remote.action", Sequence: 1, Epoch: 4, Action: strings.Repeat("a", 32), Role: "controller", Grants: []string{"remote-present"}}
|
||||
if err := send(map[string]any{"jsonrpc": "2.0", "method": "session.event", "params": action}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
select {
|
||||
case action = <-c.actions:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("SDK did not deliver approval")
|
||||
}
|
||||
cert, roots := testCertificate(t, true)
|
||||
e := testRelay(t, cert, func(conn net.Conn) {
|
||||
if relayHandshake(t, conn, controller) == nil {
|
||||
return
|
||||
}
|
||||
_, _ = io.WriteString(conn, "{\"type\":\"channel_joined\",\"channel\":\"synthetic-fixture\",\"clients\":[]}\n{\"type\":\"client_joined\",\"client\":{\"id\":7,\"connection_type\":\"slave\"}}\n")
|
||||
_, _ = io.Copy(io.Discard, conn)
|
||||
})
|
||||
e.roots = roots
|
||||
if err := c.connect(action, e, "synthetic-fixture"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
awaitStatus(t, c, func(s connectionStatus) bool { return s.state == "ready" })
|
||||
// Stale revocations cannot close the current connection.
|
||||
if err := send(map[string]any{"jsonrpc": "2.0", "method": "session.event", "params": sdk.SessionEvent{Kind: "remote.revoked", Sequence: 2, Epoch: 3, Lease: strings.Repeat("b", 32), Reason: "closed"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
awaitDone(t, c.disconnect())
|
||||
if status := c.snapshot(); status.state != "closed" || status.err != nil {
|
||||
t.Fatal("normal disconnect", status)
|
||||
}
|
||||
if method := <-calls; method != "remote.open" {
|
||||
t.Fatal(method)
|
||||
}
|
||||
if method := <-calls; method != "remote.close" {
|
||||
t.Fatal(method)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
package remote
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"strconv"
|
||||
"sync"
|
||||
|
||||
sdk "git.stormux.org/storm/cthulhu/sdk/go/tentacle"
|
||||
)
|
||||
|
||||
func security_message(text string) sdk.Interaction {
|
||||
return sdk.Interaction{Presentation: sdk.Presentation{Speech: text, Braille: text}, Done: true}
|
||||
}
|
||||
|
||||
func (review *certificateReview) form() sdk.Interaction {
|
||||
address := net.JoinHostPort(review.target.host, strconv.Itoa(review.target.port))
|
||||
details := []sdk.ListItem{
|
||||
{ID: "endpoint", Label: "Relay: " + address},
|
||||
{ID: "fingerprint", Label: "Observed SHA-256 fingerprint: " + review.fingerprint},
|
||||
{ID: "verify", Label: "Verify this fingerprint independently with the relay operator before trusting it."},
|
||||
{ID: "checks", Label: "Trust once replaces CA, hostname and expiry checks for this exact certificate on this relay host and port."},
|
||||
{ID: "privacy", Label: "The relay can read the channel key and session contents. The channel key does not verify a helper's identity."},
|
||||
}
|
||||
if review.previous != "" && review.previous != review.fingerprint {
|
||||
details = append([]sdk.ListItem{{ID: "changed", Label: "The certificate has changed. This connection is stopped."},
|
||||
{ID: "previous", Label: "Previously approved SHA-256 fingerprint: " + review.previous}}, details...)
|
||||
}
|
||||
return sdk.Interaction{Form: &sdk.Form{Title: "Review Remote relay certificate", Elements: []sdk.Element{
|
||||
{ID: "details", Label: "Certificate and relay trust details", Kind: sdk.List, Items: details},
|
||||
{ID: "copy-fingerprint", Label: "Copy fingerprint", Kind: sdk.Button},
|
||||
{ID: "trust-once", Label: "Trust once", Kind: sdk.Button},
|
||||
{ID: "cancel", Label: "Cancel", Kind: sdk.Button},
|
||||
}}, Next: "remote-review-certificate"}
|
||||
}
|
||||
|
||||
// submit returns an endpoint only on explicit Trust once. Copy fingerprint
|
||||
// requests a host clipboard write, never a direct clipboard backend call. Trust
|
||||
// is session-only: it neither saves a pin nor creates a reader action/lease.
|
||||
func (review *certificateReview) submit(ctx context.Context, value sdk.Submission) (endpoint, sdk.Interaction, error) {
|
||||
review.mu.Lock()
|
||||
defer review.mu.Unlock()
|
||||
if review.finished || review.lifetime.Err() != nil || ctx.Err() != nil {
|
||||
review.finished = true
|
||||
return endpoint{}, sdk.Interaction{}, errTrust
|
||||
}
|
||||
if value.Cancelled || value.Activated == "cancel" {
|
||||
review.finished = true
|
||||
return endpoint{}, security_message("Certificate review cancelled."), nil
|
||||
}
|
||||
switch value.Activated {
|
||||
case "copy-fingerprint":
|
||||
result := review.form()
|
||||
fingerprint := review.fingerprint
|
||||
result.Clipboard = &fingerprint
|
||||
return endpoint{}, result, nil
|
||||
case "trust-once":
|
||||
review.finished = true
|
||||
approved := review.target
|
||||
pin := *approved.pin
|
||||
approved.pin = &pin
|
||||
return approved, security_message("Relay certificate approved for one connection attempt."), nil
|
||||
default:
|
||||
// Reading/activating a details row is not an approval.
|
||||
return endpoint{}, review.form(), nil
|
||||
}
|
||||
}
|
||||
|
||||
// keyActions is a single form workflow for an already-selected endpoint. The
|
||||
// caller owns the store and must keep it open until all handlers finish. Neither
|
||||
// form creation nor submission loads an existing key or connects to the relay.
|
||||
// As with certificateReview, production callers need verified local actions.
|
||||
type keyActions struct {
|
||||
mu sync.Mutex
|
||||
lifetime context.Context
|
||||
target endpoint
|
||||
store *settingsStore
|
||||
finished bool
|
||||
}
|
||||
|
||||
func new_key_actions(ctx context.Context, target endpoint, store *settingsStore) (*keyActions, error) {
|
||||
if _, err := target.tlsConfig(); err != nil || store == nil {
|
||||
return nil, errSettings
|
||||
}
|
||||
return &keyActions{lifetime: ctx, target: endpoint{host: target.host, port: target.port}, store: store}, nil
|
||||
}
|
||||
|
||||
func (actions *keyActions) form() sdk.Interaction {
|
||||
address := net.JoinHostPort(actions.target.host, strconv.Itoa(actions.target.port))
|
||||
return sdk.Interaction{Form: &sdk.Form{Title: "Remote saved channel key", Elements: []sdk.Element{
|
||||
{ID: "details", Label: "Saved-key details", Kind: sdk.List, Items: []sdk.ListItem{
|
||||
{ID: "endpoint", Label: "Remember a key only for relay " + address},
|
||||
{ID: "storage", Label: "Remember stores the key in a private local file. Session-only keys need not be saved."},
|
||||
{ID: "forget-details", Label: "Forget removes the saved key, including a key saved for another relay. It does not erase disk history or disconnect a session."},
|
||||
}},
|
||||
{ID: "channel-key", Label: "Channel key to remember", Kind: sdk.Entry, Secret: true, MaxLength: 512},
|
||||
{ID: "remember-key", Label: "Remember key", Kind: sdk.Button},
|
||||
{ID: "forget-key", Label: "Forget saved key", Kind: sdk.Button},
|
||||
{ID: "cancel", Label: "Cancel", Kind: sdk.Button},
|
||||
}}, Next: "remote-saved-key"}
|
||||
}
|
||||
|
||||
func (actions *keyActions) submit(ctx context.Context, value sdk.Submission) (sdk.Interaction, error) {
|
||||
actions.mu.Lock()
|
||||
defer actions.mu.Unlock()
|
||||
if actions.finished || actions.lifetime.Err() != nil || ctx.Err() != nil {
|
||||
actions.finished = true
|
||||
return sdk.Interaction{}, errSettings
|
||||
}
|
||||
if value.Cancelled || value.Activated == "cancel" {
|
||||
actions.finished = true
|
||||
return security_message("Saved-key action cancelled."), nil
|
||||
}
|
||||
switch value.Activated {
|
||||
case "remember-key":
|
||||
key := value.Values["channel-key"].Text
|
||||
if !validChannelKey(key) {
|
||||
result := actions.form()
|
||||
result.Presentation = security_message("Enter a valid channel key before choosing Remember key.").Presentation
|
||||
return result, nil
|
||||
}
|
||||
actions.finished = true
|
||||
if err := actions.store.rememberKey(actions.target, key); err != nil {
|
||||
return security_message("Channel key could not be remembered."), nil
|
||||
}
|
||||
return security_message("Channel key remembered for the selected relay."), nil
|
||||
case "forget-key":
|
||||
actions.finished = true
|
||||
if err := actions.store.forgetKey(); err != nil {
|
||||
return security_message("Saved channel key could not be forgotten."), nil
|
||||
}
|
||||
return security_message("Saved channel key forgotten."), nil
|
||||
default:
|
||||
return actions.form(), nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,374 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
package remote
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"crypto/tls"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
sdk "git.stormux.org/storm/cthulhu/sdk/go/tentacle"
|
||||
)
|
||||
|
||||
func TestCertificateProbeDisclosesNoApplicationBytes(t *testing.T) {
|
||||
certificate, _ := testCertificate(t, false) // Neither CA nor hostname trusted.
|
||||
observed := make(chan int, 1)
|
||||
target := testRelay(t, certificate, func(connection net.Conn) {
|
||||
data, _ := io.ReadAll(connection)
|
||||
observed <- len(data)
|
||||
})
|
||||
oldPin := &certificatePin{host: target.host, port: target.port, sha256: [32]byte{1}}
|
||||
target.pin = oldPin
|
||||
review, err := probe_certificate(t.Context(), target)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
select {
|
||||
case count := <-observed:
|
||||
if count != 0 {
|
||||
t.Fatal("certificate probe sent application data")
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("certificate probe did not close its socket")
|
||||
}
|
||||
digest := sha256.Sum256(certificate.Certificate[0])
|
||||
if review.fingerprint != hex.EncodeToString(digest[:]) {
|
||||
t.Fatal("wrong certificate fingerprint")
|
||||
}
|
||||
form := review.form()
|
||||
encoded, _ := json.Marshal(form)
|
||||
if form.Clipboard != nil || !strings.Contains(string(encoded), "certificate has changed") || !strings.Contains(string(encoded), hex.EncodeToString(oldPin.sha256[:])) {
|
||||
t.Fatal("changed pin not disclosed, or automatic clipboard request")
|
||||
}
|
||||
if strings.Contains(string(encoded), certificate.Leaf.Subject.CommonName) {
|
||||
t.Fatal("untrusted certificate subject entered UI")
|
||||
}
|
||||
// Mutating the original pin cannot change the observed review or approval.
|
||||
oldPin.sha256 = [32]byte{2}
|
||||
approved, copied, err := review.submit(t.Context(), sdk.Submission{Activated: "copy-fingerprint"})
|
||||
if err != nil || approved.host != "" || copied.Clipboard == nil || *copied.Clipboard != review.fingerprint || copied.Done {
|
||||
t.Fatal("copy action changed trust or completed review", err)
|
||||
}
|
||||
approved, _, err = review.submit(t.Context(), sdk.Submission{Activated: "fingerprint"})
|
||||
if err != nil || approved.host != "" {
|
||||
t.Fatal("reading details approved a certificate")
|
||||
}
|
||||
approved, result, err := review.submit(t.Context(), sdk.Submission{Activated: "trust-once"})
|
||||
if err != nil || !result.Done || approved.pin.sha256 != digest || approved.host != target.host || approved.port != target.port || target.pin.sha256 == digest {
|
||||
t.Fatal("approval changed endpoint identity or original trust", err)
|
||||
}
|
||||
if _, _, err := review.submit(t.Context(), sdk.Submission{Activated: "trust-once"}); !errors.Is(err, errTrust) {
|
||||
t.Fatal("certificate review was reusable")
|
||||
}
|
||||
}
|
||||
|
||||
func TestReviewedCertificateAuthenticatedAgainBeforeJoin(t *testing.T) {
|
||||
certificate, _ := testCertificate(t, false)
|
||||
var mutex sync.Mutex
|
||||
attempt := 0
|
||||
target := testRelay(t, certificate, func(connection net.Conn) {
|
||||
mutex.Lock()
|
||||
attempt++
|
||||
current := attempt
|
||||
mutex.Unlock()
|
||||
if current == 1 {
|
||||
data, _ := io.ReadAll(connection)
|
||||
if len(data) != 0 {
|
||||
t.Error("probe disclosed application data")
|
||||
}
|
||||
return
|
||||
}
|
||||
if relayHandshake(t, connection, controller) == nil {
|
||||
return
|
||||
}
|
||||
_, _ = io.WriteString(connection, "{\"type\":\"channel_joined\",\"channel\":\"synthetic-fixture\",\"clients\":[]}\n")
|
||||
_, _ = io.Copy(io.Discard, connection)
|
||||
})
|
||||
review, err := probe_certificate(t.Context(), target)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
approved, _, err := review.submit(t.Context(), sdk.Submission{Activated: "trust-once"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
connection, _, err := connect(t.Context(), approved, controller, "synthetic-fixture")
|
||||
if err != nil {
|
||||
t.Fatal("reviewed certificate failed fresh TLS authentication", err)
|
||||
}
|
||||
connection.close()
|
||||
}
|
||||
|
||||
func TestCertificateReviewCancellationAndConcurrentApproval(t *testing.T) {
|
||||
for _, mode := range []string{"cancel", "cancelled", "lifetime", "handler"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
lifetime, cancel := context.WithCancel(t.Context())
|
||||
defer cancel()
|
||||
review := &certificateReview{lifetime: lifetime, target: endpoint{host: "relay.invalid", port: 6837, pin: &certificatePin{sha256: [32]byte{1}}}}
|
||||
value := sdk.Submission{Activated: "trust-once"}
|
||||
ctx := t.Context()
|
||||
switch mode {
|
||||
case "cancel":
|
||||
value.Activated = "cancel"
|
||||
case "cancelled":
|
||||
value.Cancelled = true
|
||||
case "lifetime":
|
||||
cancel()
|
||||
case "handler":
|
||||
var stop context.CancelFunc
|
||||
ctx, stop = context.WithCancel(ctx)
|
||||
stop()
|
||||
}
|
||||
approved, _, _ := review.submit(ctx, value)
|
||||
if approved.host != "" {
|
||||
t.Fatal("cancelled review returned trust")
|
||||
}
|
||||
if _, _, err := review.submit(t.Context(), sdk.Submission{Activated: "trust-once"}); err == nil {
|
||||
t.Fatal("cancelled review could be approved later")
|
||||
}
|
||||
})
|
||||
}
|
||||
review := &certificateReview{lifetime: t.Context(), target: endpoint{host: "relay.invalid", pin: &certificatePin{sha256: [32]byte{1}}}}
|
||||
results := make(chan bool, 2)
|
||||
for range 2 {
|
||||
go func() {
|
||||
_, _, err := review.submit(t.Context(), sdk.Submission{Activated: "trust-once"})
|
||||
results <- err == nil
|
||||
}()
|
||||
}
|
||||
if first, second := <-results, <-results; first == second {
|
||||
t.Fatal("concurrent submissions did not consume review exactly once")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCertificateProbeCancellation(t *testing.T) {
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer listener.Close()
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
defer cancel()
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := probe_certificate(ctx, endpoint{host: "127.0.0.1", port: listener.Addr().(*net.TCPAddr).Port})
|
||||
done <- err
|
||||
}()
|
||||
connection, err := listener.Accept()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer connection.Close()
|
||||
cancel()
|
||||
select {
|
||||
case err := <-done:
|
||||
if !errors.Is(err, context.Canceled) {
|
||||
t.Fatal("probe did not report cancellation", err)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("stalled TLS probe ignored cancellation")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCertificateChangeAfterReviewDoesNotDiscloseKey(t *testing.T) {
|
||||
first, _ := testCertificate(t, true)
|
||||
changed, _ := testCertificate(t, true)
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { listener.Close() })
|
||||
observed := make(chan int, 2)
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
for _, certificate := range []tls.Certificate{first, changed} {
|
||||
raw, err := listener.Accept()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
raw.SetDeadline(time.Now().Add(3 * time.Second))
|
||||
connection := tls.Server(raw, &tls.Config{Certificates: []tls.Certificate{certificate}, MinVersion: tls.VersionTLS12})
|
||||
data, _ := io.ReadAll(connection)
|
||||
observed <- len(data)
|
||||
raw.Close()
|
||||
}
|
||||
}()
|
||||
t.Cleanup(func() { listener.Close(); <-done })
|
||||
target := endpoint{host: "127.0.0.1", port: listener.Addr().(*net.TCPAddr).Port}
|
||||
review, err := probe_certificate(t.Context(), target)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
approved, _, err := review.submit(t.Context(), sdk.Submission{Activated: "trust-once"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
connection, _, err := connect(t.Context(), approved, controller, "synthetic-private-key")
|
||||
if connection != nil || !errors.Is(err, errTrust) {
|
||||
t.Fatal("certificate changed between probe and join was accepted", err)
|
||||
}
|
||||
for range 2 {
|
||||
select {
|
||||
case count := <-observed:
|
||||
if count != 0 {
|
||||
t.Fatal("probe or failed authentication disclosed application data")
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("probe or failed authentication socket remained open")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSavedKeyActionsAreExplicitAndSecret(t *testing.T) {
|
||||
store, path, value := settingsFixture(t)
|
||||
target, _ := value.endpoint()
|
||||
if err := store.save(value); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
actions, err := new_key_actions(t.Context(), target, store)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
form := actions.form()
|
||||
entry := form.Form.Elements[1]
|
||||
if entry.Kind != sdk.Entry || !entry.Secret || entry.Text != "" || entry.Required || form.Clipboard != nil {
|
||||
t.Fatal("key form exposes or unnecessarily requires a secret")
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(path, "channel-key.toml")); !os.IsNotExist(err) {
|
||||
t.Fatal("creating a form saved a key")
|
||||
}
|
||||
key := "synthetic-private-猫-key"
|
||||
submission := sdk.Submission{Activated: "remember-key", Values: map[string]sdk.Value{"channel-key": {Text: key}}}
|
||||
result, err := actions.submit(t.Context(), submission)
|
||||
encoded, _ := json.Marshal(result)
|
||||
if err != nil || !result.Done || strings.Contains(string(encoded), key) {
|
||||
t.Fatal("Remember failed or echoed the key", err)
|
||||
}
|
||||
stored, err := store.loadKey(target)
|
||||
if err != nil || stored != key {
|
||||
t.Fatal("explicit key was not stored")
|
||||
}
|
||||
ordinary, err := os.ReadFile(filepath.Join(path, "settings.toml"))
|
||||
if err != nil || strings.Contains(string(ordinary), key) {
|
||||
t.Fatal("key entered ordinary settings")
|
||||
}
|
||||
if _, err := actions.submit(t.Context(), submission); err == nil {
|
||||
t.Fatal("Remember action was reusable")
|
||||
}
|
||||
// Another endpoint never receives the saved key in its form. Forget is
|
||||
// explicitly global because the storage contract has one saved-key slot.
|
||||
other := endpoint{host: "other.invalid", port: 6837}
|
||||
forget, _ := new_key_actions(t.Context(), other, store)
|
||||
encoded, _ = json.Marshal(forget.form())
|
||||
if strings.Contains(string(encoded), key) {
|
||||
t.Fatal("saved key entered a later form")
|
||||
}
|
||||
result, err = forget.submit(t.Context(), sdk.Submission{Activated: "forget-key"})
|
||||
if err != nil || !result.Done {
|
||||
t.Fatal("Forget failed", err)
|
||||
}
|
||||
if stored, err := store.loadKey(target); err != nil || stored != "" {
|
||||
t.Fatal("forgotten key remains")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSavedKeyCancellationValidationAndStorageFailure(t *testing.T) {
|
||||
for _, mode := range []string{"cancel", "lifetime", "handler", "invalid", "failure", "details"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
store, path, value := settingsFixture(t)
|
||||
target, _ := value.endpoint()
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
defer cancel()
|
||||
actions, _ := new_key_actions(ctx, target, store)
|
||||
key := "synthetic-private-key"
|
||||
submission := sdk.Submission{Activated: "remember-key", Values: map[string]sdk.Value{"channel-key": {Text: key}}}
|
||||
handlerContext := t.Context()
|
||||
switch mode {
|
||||
case "cancel":
|
||||
submission.Cancelled = true
|
||||
case "lifetime":
|
||||
cancel()
|
||||
case "handler":
|
||||
var stop context.CancelFunc
|
||||
handlerContext, stop = context.WithCancel(handlerContext)
|
||||
stop()
|
||||
case "invalid":
|
||||
submission.Values["channel-key"] = sdk.Value{Text: strings.Repeat("猫", 200)} // Exceeds byte limit.
|
||||
case "failure":
|
||||
store.close()
|
||||
case "details":
|
||||
submission.Activated = "endpoint"
|
||||
}
|
||||
result, _ := actions.submit(handlerContext, submission)
|
||||
encoded, _ := json.Marshal(result)
|
||||
if strings.Contains(string(encoded), key) || result.Clipboard != nil {
|
||||
t.Fatal("key leaked through response")
|
||||
}
|
||||
if mode == "failure" && result.Speech != "Channel key could not be remembered." {
|
||||
t.Fatal("storage failure was not reported")
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(path, "channel-key.toml")); !os.IsNotExist(err) {
|
||||
t.Fatal("key stored without a valid completed Remember action")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestForgetKeyCancellationAndFailurePreserveSavedKey(t *testing.T) {
|
||||
for _, mode := range []string{"cancel", "lifetime", "failure"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
store, path, value := settingsFixture(t)
|
||||
target, _ := value.endpoint()
|
||||
if err := store.rememberKey(target, "synthetic-retained-key"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before, err := os.ReadFile(filepath.Join(path, "channel-key.toml"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
defer cancel()
|
||||
actions, _ := new_key_actions(ctx, target, store)
|
||||
submission := sdk.Submission{Activated: "forget-key", Cancelled: mode == "cancel"}
|
||||
if mode == "lifetime" {
|
||||
cancel()
|
||||
}
|
||||
if mode == "failure" {
|
||||
store.close()
|
||||
}
|
||||
result, _ := actions.submit(t.Context(), submission)
|
||||
if mode == "failure" && result.Speech != "Saved channel key could not be forgotten." {
|
||||
t.Fatal("Forget failure was not reported")
|
||||
}
|
||||
after, err := os.ReadFile(filepath.Join(path, "channel-key.toml"))
|
||||
if err != nil || string(before) != string(after) {
|
||||
t.Fatal("cancelled or failed Forget changed stored key")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSecurityFormsRejectInvalidEndpoints(t *testing.T) {
|
||||
store, _, _ := settingsFixture(t)
|
||||
for _, host := range []string{"relay\x1b.invalid", "relay\x7f.invalid", "relay\x85.invalid", "relay\xff.invalid", "relay\n.invalid"} {
|
||||
target := endpoint{host: host, port: 6837}
|
||||
if _, err := new_key_actions(t.Context(), target, store); err == nil {
|
||||
t.Fatal("invalid UI host accepted")
|
||||
}
|
||||
if _, err := probe_certificate(t.Context(), target); err == nil {
|
||||
t.Fatal("invalid probe host accepted")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,8 @@ import (
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -56,7 +58,7 @@ type endpoint struct {
|
||||
}
|
||||
|
||||
func (e endpoint) tlsConfig() (*tls.Config, error) {
|
||||
if e.host == "" || len(e.host) > 253 || strings.TrimSpace(e.host) != e.host || strings.ContainsAny(e.host, "/\\@\x00\r\n\t []") || e.port < 1 || e.port > 65535 {
|
||||
if e.host == "" || len(e.host) > 253 || !utf8.ValidString(e.host) || strings.IndexFunc(e.host, unicode.IsControl) >= 0 || strings.TrimSpace(e.host) != e.host || strings.ContainsAny(e.host, "/\\@ []") || e.port < 1 || e.port > 65535 {
|
||||
return nil, errEndpoint
|
||||
}
|
||||
// Colons are accepted only in bare IPv6 literals; JoinHostPort adds brackets.
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
package remote
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"crypto/tls"
|
||||
"encoding/hex"
|
||||
"net"
|
||||
"strconv"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// certificateReview owns a single local review workflow. Its context must be
|
||||
// the workflow lifetime, not a short command RPC. The future UI owner must cancel
|
||||
// it on approval replacement, form closure, lock/handoff or process shutdown.
|
||||
// A Submission is not proof of local input origin; these handlers must not be
|
||||
// wired to production commands until the reader can establish that origin.
|
||||
type certificateReview struct {
|
||||
mu sync.Mutex
|
||||
lifetime context.Context
|
||||
target endpoint
|
||||
fingerprint string
|
||||
previous string
|
||||
finished bool
|
||||
}
|
||||
|
||||
// probe_certificate is an explicit, unauthenticated certificate inspection. It
|
||||
// takes no channel key and writes no application bytes. Never call it as an
|
||||
// automatic fallback from connect: CA or pin failure must stop that attempt.
|
||||
// Normal CA/pin authentication is repeated on a NEW connection after review.
|
||||
func probe_certificate(ctx context.Context, target endpoint) (*certificateReview, error) {
|
||||
config, err := target.tlsConfig()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Only this inspection socket bypasses authentication. It closes immediately
|
||||
// after TLS and cannot be returned as an authenticated relay connection.
|
||||
config.InsecureSkipVerify = true
|
||||
config.VerifyConnection = nil
|
||||
probeContext, cancel := context.WithTimeout(ctx, dialTimeout)
|
||||
defer cancel()
|
||||
raw, err := (&net.Dialer{}).DialContext(probeContext, "tcp", net.JoinHostPort(target.host, strconv.Itoa(target.port)))
|
||||
if err != nil {
|
||||
return nil, networkError(ctx, err)
|
||||
}
|
||||
defer raw.Close()
|
||||
connection := tls.Client(raw, config)
|
||||
if err := connection.HandshakeContext(probeContext); err != nil {
|
||||
return nil, networkError(ctx, err)
|
||||
}
|
||||
certificates := connection.ConnectionState().PeerCertificates
|
||||
if len(certificates) == 0 {
|
||||
return nil, errTrust
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
digest := sha256.Sum256(certificates[0].Raw)
|
||||
review := &certificateReview{lifetime: ctx, fingerprint: hex.EncodeToString(digest[:])}
|
||||
if target.pin != nil {
|
||||
review.previous = hex.EncodeToString(target.pin.sha256[:])
|
||||
}
|
||||
// Retain endpoint identity and the observed digest only. No server-controlled
|
||||
// subject/issuer text, certificates, keys or caller-owned TLS pointers survive.
|
||||
review.target = endpoint{host: target.host, port: target.port, pin: &certificatePin{host: target.host, port: target.port, sha256: digest}}
|
||||
return review, nil
|
||||
}
|
||||
Reference in new issue
Block a user