Skip to content

Let a gateway serve through a relay (part R2a of #266) - #800

Merged
Varuas37 merged 6 commits into
mainfrom
claude/project-thread-v7mu39
Oct 13, 2026
Merged

Varuas37 merged 6 commits into
mainfrom
claude/project-thread-v7mu39

Conversation

@Varuas37

@Varuas37 Varuas37 commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Before: the relay from R1 (#788) runs, but no gateway uses it. A gateway can only be reached by dialing its native listener directly.

After: a gateway with native.relay: "host:port" in config.json registers with that relay under its own key and stays registered. Each reader the relay joins to it is served exactly as a direct reader would be: the same TLS pinned to the gateway's key, which the relay cannot read. Relayed readers come in on four permits of their own, so however many a relay sends, direct readers are still admitted. Readers don't dial the relay yet. That is R2b.

How.

  • relay/gateway/application.rs (ThroughRelay) keeps the registration:
    • It dials and proves the key, then answers pings.
    • It registers again after a wait that doubles from 1 s to 60 s. The wait starts over after a registration that lasted a minute.
    • It drops a registration that hears nothing for two ping intervals. This is how a laptop waking from sleep finds its old connection dead without waiting on TCP.
    • For each Incoming{t} it takes a relay permit, dials Accept{K, t}, and hands the stream on only after Joined. With no permit free, nothing is dialed, and the relay answers that reader NoAnswer.
    • Every wait is on the injected Timer. A key that can't make its proof stops registering, because trying again can't change that.
    • Dialing, the key and permits are ports, so the application imports no infrastructure.
  • relay/gateway/infrastructure.rs holds the concrete pieces:
    • TcpRelayDial, with nodelay and keepalive.
    • IdentityKey, which wraps the native identity.
    • RelayedAccept, the listener's one EnrollmentAccept. It selects over the TCP accept and the joined readers' channel, and both branches are cancel-safe. With no relay configured the channel is closed, and that branch is disabled.
  • NativeEnrollmentConnections gains a relay Pool of 4:
    • relay_permit() hands out a permit, and start_relayed admits a connection on it in place of a connection permit.
    • close, the wake sweep (relay_wake_report) and shutdown cover the new pool. A permit held by an accept still under way wakes the drain when it is dropped.
  • Accepted::Relayed(stream, permit) is the new accept outcome. It leaves the accept backoff alone, because it says nothing about the listening socket.
  • RelayAddress validates host:port: an IPv6 host goes in brackets, and the whole is at most 255 bytes. Unlike listenAddress, it may be a host name, looked up at each dial.
  • Composition starts the registration with the listener and stops it in signal_stop. join waits for it before the listener's drain.
  • read_frame, next_frame and write_frame move to relay/wire.rs, which the relay and the gateway share.
  • env_serve's redial is not reused, because env_serve builds only on Unix and the gateway runs everywhere.
sequenceDiagram
    participant L as Native listener
    participant G as Gateway relay task
    participant R as Relay
    participant P as Reader
    G->>R: Serve K, then Proof over the challenge
    R->>G: Registered
    P->>R: Connect K
    R->>G: Incoming t
    G->>G: take a relay permit, else drop t
    G->>R: Accept K t on a new connection
    R->>G: Joined
    G->>L: the stream and its relay permit
    P->>L: TLS pinned to K, served as a direct reader
    loop every ping interval
        R->>G: Ping
        G->>R: Pong
    end
Loading

The design doc's slice table now splits R2 into R2a (this PR), R2b (the reader's race of direct and relay, plus peer.relay) and R2c (end to end). New rows RL15 to RL17 cover the gateway's side.

Tests

  • tests/relay/gateway.rs (8 tests, manual timer), against the real R1 relay and a scripted one:
    • A reader is joined, and bytes cross both ways.
    • Pings are answered, and a reader past the pool is not dialed for.
    • An accept leg hands its stream on only after Joined, and the bytes after it stay on the stream.
    • An accept leg that is never joined gives its permit back at the join deadline.
    • A silent registration is made again after the first wait.
    • The wait doubles after each refusal.
    • A key that can't prove stops.
    • Stop ends the registration and its accept legs.
  • native_listener_serves_relayed_connections_on_their_own_permits:
    • A relayed device gets its Hello answered.
    • A direct device is still answered with all four relay permits held.
    • The drain waits for relay permits still held.
  • a_gateway_with_a_relay_answers_a_reader_that_reaches_only_the_relay: a real relay over TCP, a real gateway started by composition, and a reader that completes TLS pinned to the gateway's key through the relay and is answered.
  • native_relay_is_host_and_port: which relay values are accepted and which refused.
  • Ran locally: cargo fmt --all, clippy with -D warnings for nessa-server on Linux and for the six crates on x86_64-pc-windows-gnu, and node scripts/check-architecture.mjs.

Scripted gateway checks

Not applicable. This changes no UI, ACP or MCP behavior, and the gateway behaves as before unless native.relay is set.

Part of #266.

🤖 Generated with Claude Code

https://claude.ai/code/session_01EL5rzp9FLsixdtkMSbgffp


Generated by Claude Code

Summary by CodeRabbit

  • New Features
    • Native pairing can now be configured to use a relay, enabling readers to connect through it while preserving direct connections.
    • Relay connections have a separate capacity limit from direct connections.
    • Relay addresses are validated when configured.
  • Bug Fixes
    • If a configured relay is unavailable, direct connections remain available.

A gateway with native.relay set registers with the relay under its own
key, keeps the registration with a doubling backoff, drops it after two
silent ping intervals, and accepts each reader the relay announces on a
relay permit from a pool of four. Joined readers reach the native
listener as a second source in its one listening socket, so a relay
fault never ends the listener and relayed readers never take the
permits direct readers need.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EL5rzp9FLsixdtkMSbgffp
@coderabbitai

coderabbitai Bot commented Oct 13, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

Note

Currently processing new changes in this PR. This may take a few minutes, please wait...

⚙️ Run configuration
  • Configuration used: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 3f0e06a1-2fc5-40f0-a053-d700b4e258ca
📥 Commits

Reviewing files that changed from the base of the PR and between a90f502 and f16fdc6.

📒 Files selected for processing (2)
  • crates/nessa-server/src/relay/gateway/application.rs
  • crates/nessa-server/src/relay/gateway/infrastructure.rs
 _____________________________________
< Please step away from the keyboard! >
 -------------------------------------
  \
   \   (\__/)
       (•ㅅ•)
       /   づ

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: c5bd7077-fbf9-466e-b87d-c78a0e0f64d4
📥 Commits

Reviewing files that changed from the base of the PR and between 6ae0a11 and a90f502.

📒 Files selected for processing (20)
  • crates/nessa-server/src/composition/native_pairing.rs
  • crates/nessa-server/src/composition/runtime_config.rs
  • crates/nessa-server/src/device_pairing/infrastructure/connection.rs
  • crates/nessa-server/src/device_pairing/infrastructure/listener.rs
  • crates/nessa-server/src/device_pairing/infrastructure/mod.rs
  • crates/nessa-server/src/relay/application.rs
  • crates/nessa-server/src/relay/gateway/application.rs
  • crates/nessa-server/src/relay/gateway/infrastructure.rs
  • crates/nessa-server/src/relay/gateway/mod.rs
  • crates/nessa-server/src/relay/mod.rs
  • crates/nessa-server/src/relay/wire.rs
  • crates/nessa-server/src/timer/mod.rs
  • crates/nessa-server/tests/composition/native_pairing.rs
  • crates/nessa-server/tests/composition/paired_environment.rs
  • crates/nessa-server/tests/composition/peer_reading.rs
  • crates/nessa-server/tests/composition/read_only_online/fixtures/gateway.rs
  • crates/nessa-server/tests/device_pairing/infrastructure/listener.rs
  • crates/nessa-server/tests/relay/gateway.rs
  • crates/nessa-server/tests/relay/relay.rs
  • docs/design/auth/relay.md
💤 Files with no reviewable changes (1)
  • crates/nessa-server/src/timer/mod.rs

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 1 remain after this review.

📝 Walkthrough

The change adds optional relay support to native gateway pairing. It validates relay addresses, registers the gateway with a relay using its identity proof, admits up to four relayed readers, and sends joined streams to the enrollment listener. It also adds retry, shutdown, and integration-test coverage.

Changes: Native Gateway Relay Support

Layer / File(s) Summary
Relay frame I/O
crates/nessa-server/src/relay/{application.rs,mod.rs,wire.rs}, crates/nessa-server/tests/relay/relay.rs
Relay frame reading and writing now use shared wire helpers. The relay application delegates frame writes to write_frame and uses the shared frame-reading functions.
Relay permits and listener dispatch
crates/nessa-server/src/device_pairing/infrastructure/{connection.rs,listener.rs,mod.rs}, crates/nessa-server/src/relay/gateway/infrastructure.rs, crates/nessa-server/tests/device_pairing/infrastructure/listener.rs, crates/nessa-server/tests/relay/gateway.rs
A separate pool provides four relay permits. The listener dispatches relayed connections with their permits. Shutdown closes the relay pool and waits for its permits to drain.
Gateway registration and accept flow
crates/nessa-server/src/relay/gateway/*, crates/nessa-server/src/timer/mod.rs, crates/nessa-server/tests/relay/gateway.rs, docs/design/auth/relay.md
ThroughRelay registers with the relay, handles challenges and reader tokens, and transfers joined streams and permits to the listener. Registration failures retry with capped backoff; a key that cannot produce a proof ends serving. The relay design document updates its status, slice plan, and listed outcomes.
Native pairing configuration and lifecycle
crates/nessa-server/src/composition/{native_pairing.rs,runtime_config.rs}, crates/nessa-server/tests/composition/{native_pairing.rs,paired_environment.rs,peer_reading.rs,read_only_online/fixtures/gateway.rs}
NativeConfig gains an optional validated relay address. Native pairing creates and runs the relay service when configured, signals it during shutdown, and joins its task. Composition tests cover reachable and unreachable relays; other native test configurations explicitly set relay to None.

Priority: ➖ Normal

Estimated code review effort: 4 (Complex) | ~60 minutes

Change: Feature

Sequence Diagram(s)

sequenceDiagram
  participant Gateway
  participant Relay
  participant IdentityKey
  participant NativeEnrollmentConnections
  participant EnrollmentListener
  Gateway->>Relay: register with Serve frame
  Relay->>Gateway: send challenge
  Gateway->>IdentityKey: prove challenge
  IdentityKey-->>Gateway: return proof
  Gateway->>Relay: send proof
  Relay->>Gateway: confirm registration
  Relay->>Gateway: send incoming reader token
  Gateway->>NativeEnrollmentConnections: request relay permit
  Gateway->>Relay: accept reader and await Joined
  Relay-->>Gateway: return joined reader stream
  Gateway->>EnrollmentListener: deliver stream and permit
Loading

Suggested reviewers: claude

Merge Risk: ⚪ Minimal · up to a90f5

No actionable issue is established for the optional relay-serving change; it is mergeable after normal checks.

Security architecture risk: 🟡 Moderate · up to a90f5

Relay access preserves the existing identity and authorization checks. However, a hostile relay may cause memory growth that also affects direct gateway service, despite the separate connection limit. Actual production exposure remains unconfirmed.

Retained concerns

  • Medium · security · inferred: The new registration loop prioritizes incoming frames over collecting completed Accept-leg tasks. A malicious relay can continuously send Incoming frames and rapidly fail the resulting legs, returning permits while completed tasks remain tracked in the JoinSet. The four-permit limit bounds active admissions, not retained task entries. Because any incoming frame refreshes the silence deadline, this pattern need not trigger registration recovery. Accumulating task metadata could exhaust the gateway process and affect direct readers as well. Registration termination releases the set, but sustained hostile traffic has no independent tracking bound.
Security review details

Security Blast Radius

  • inferred — The retained concern affects gateways configured to connect to an attacker-controlled relay or an intercepted relay connection. It requires control of relay-facing frames, not a paired-device credential. Potential memory exhaustion affects the shared gateway process, including direct service; the traced path does not establish privilege gain, payload disclosure, or cross-gateway authorization.

Security Findings and Attack Paths

  • inferred — A hostile endpoint can complete the registration exchange, continuously announce tokens, and immediately fail Accept connections. Permits become reusable, but the biased frame branch can starve completed-task collection. Incoming traffic also refreshes the silence deadline. This creates an introduced task-retention denial-of-service path; exhaustion and its traffic threshold were not experimentally verified.

Trust Boundaries and Controls

  • observed — The existing relay verifies registration proof, associates waiting tokens with a gateway key, rejects cross-key or missing tokens, and consumes a valid token once under a lock. These controls predate this PR. They govern routing, not privileged access: joined streams still undergo native TLS and device authorization.

Resilience and Maintainability Implications

  • observed — Relay permits separately bound active relay admission and are included in shutdown drain checks. Authorized product or environment sessions transfer to their existing shared pools. Registration-scoped Accept legs end when registration stops, while delivered connections remain owned by the native connection lifecycle. These controls support normal cleanup but do not independently bound retained completion entries.

Hardening Proposals

  • proposed — Guarantee completed-leg collection independently of incoming-frame readiness and bound total tracked tasks, including completed entries, rather than relying only on active permits. Validate this containment property with sustained hostile frames and rapidly failing Accept legs while checking direct-service availability.
Pre-merge checks · Passed 4 · Failed 1

Failed Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 62.35% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 85 functions across 18 files. (1 skipped:… Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks (4 passed)
Check name Status Explanation
Title check Passed The title clearly and concisely describes the primary change: enabling a gateway to serve through a relay. It also identifies the related R2a scope.
Description check Passed The description provides a detailed summary, implementation notes, test coverage, validation commands, scope boundaries, and the required scripted gateway checks section. It correctly marks scripted c…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Docstring Coverage

Explanation

Docstring coverage is 62.35% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 85 functions across 18 files. (1 skipped: 1 unsupported.)

  • Fix all pre-merge checks with AI
✨ Finishing Touches
📝 Generate docstrings
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Comment @coderabbitai help to get the list of available commands.

…s waits (part R2a of #266)

A dial that fails with InvalidInput (a host name that resolves to
nothing) is now retried like any failure; only the key's own proof stops
registering. A dropped stop sender is a stop, as for the listener, and a
Pong write no longer holds up stop. Tests now cover the backoff starting
over after a lasting registration, a refused dial being retried, the
relay pool apart from a full connection pool, and a relay out of reach
leaving direct readers served.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EL5rzp9FLsixdtkMSbgffp
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EL5rzp9FLsixdtkMSbgffp
@Varuas37
Varuas37 marked this pull request as ready for review October 13, 2026 02:15

@greptile-apps greptile-apps Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Your trial has ended. Reactivate Greptile to resume code reviews.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 13, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-13T02:20:57.816965Z a90f502 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a90f5025ad

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@greptile-apps greptile-apps Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Your trial has ended. Reactivate Greptile to resume code reviews.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants