Documentation
¶
Overview ¶
Package relay drives the binary's outbound long-lived connection to the relay: opens the WSS via internal/transport and exposes inbound frames as protocol.RoutingEnvelope values via Frames(). The binary↔relay leg is content-blind — the relay registers the binary's server-id from the x-pyrycode-server request header and claims the slot on WS upgrade, so the conn is treated as established the moment the upgrade completes; there is no relay-originated hello/hello_ack handshake on this leg. It does NOT dispatch on envelope types, validate device tokens, or interpret application-level error payloads — those concerns layer above this package in a future ticket (supervisor wiring + per-message handlers).
The single source of truth for the headers and close codes is docs/protocol-mobile.md (§ Authentication, § Connection lifecycle, § Worked example). When that document changes, this package changes.
Index ¶
- Constants
- Variables
- type AuthOutcome
- type Config
- type Connection
- type InnerFrameV2Decoded
- type V2Session
- type V2SessionConfig
- type V2SessionManager
- func (m *V2SessionManager) ActiveConnIDs(ctx context.Context) []string
- func (m *V2SessionManager) Push(ctx context.Context, connID string, env protocol.Envelope) error
- func (m *V2SessionManager) Rekey(ctx context.Context, connID string) error
- func (m *V2SessionManager) Run(ctx context.Context) error
- type V2SessionState
Constants ¶
const ( // StatusProtocolMismatch is the WS close code the binary asks the // relay to apply when a phone sends an inner frame that violates the // v2 inner-frame shape, the state machine, or the discriminator // table. Wire spec: docs/protocol-mobile.md § Error codes, close-code // row 4421. StatusProtocolMismatch websocket.StatusCode = 4421 // StatusHandshakeFailure is the WS close code the binary asks the // relay to apply when the Noise_IK handshake fails before // CipherStates exist (e.g. MAC failure on IK message 1, wrong static // pubkey). No AEAD-sealed error envelope can be sent — the close // code is the only signal. Wire spec: docs/protocol-mobile.md // § Error codes, close-code row 4426. StatusHandshakeFailure websocket.StatusCode = 4426 )
Mobile Protocol v2 close codes (docs/protocol-mobile.md § Error codes). 4401 (StatusUnauthorized) lives in auth.go and is reused unchanged.
const MsgInvalidToken = "device token not recognised; re-pair via pyry pair on the binary"
MsgInvalidToken is the fixed user-facing message emitted in the auth.invalid_token error payload (docs/protocol-mobile.md § Error codes). Defined as an exported const so future integration tests can pin it without re-typing the spec sentence.
StatusUnauthorized is the WS close code the relay sends when the binary rejects a phone's device token (docs/protocol-mobile.md § Error codes, close-code row 4401). Typed locally so callers don't import the websocket package for the value; parallel to statusServerIDConflict in connection.go.
Variables ¶
var ( // ErrServerIDConflict is the terminal error returned by Wait when // the relay refused our claim with WS close 4409. Another binary is // currently holding the same server-id and the relay's 30-second // grace window has not elapsed. Operator escalation: another pyry is // already running for this server-id, or a stale connection on the // relay side has not yet been reaped. ErrServerIDConflict = errors.New("relay: server-id conflict (close 4409)") // ErrInvalidConfig is returned by Connect on missing required fields. ErrInvalidConfig = errors.New("relay: invalid config") )
Sentinel errors. Callers distinguish fatal vs. retryable via errors.Is.
var ErrConnNotFound = fmt.Errorf("relay: conn not found: %w", control.ErrConnNotFound)
ErrConnNotFound is returned by (*V2SessionManager).Rekey when connID is not currently registered in the manager's sessions map. Wraps control.ErrConnNotFound so the control dispatcher's errors.Is(err, control.ErrConnNotFound) check in handleRekey continues to map to ErrCodeConnNotFound on the wire without further plumbing.
var ErrMalformedHelloFrame = errors.New("relay: malformed hello frame")
ErrMalformedHelloFrame is returned by AuthenticateFirstFrame when the inner envelope inside env.Frame cannot be JSON-decoded. The relay-conn caller maps this to its existing protocol.malformed handling; this package does not synthesize an error envelope for it (the malformed- frame response shape is owned by a sibling ticket).
var ErrSessionNotOpen = errors.New("relay: session not open")
ErrSessionNotOpen is returned by (*V2SessionManager).Rekey when the named session exists but is not eligible for a manual rekey — either not in V2StateOpen (still handshaking, or already torn down), or already awaiting a rekey reply from a prior emit. The control dispatcher surfaces this verbatim through Response.Error with no ErrorCode (slice A defines no wire code for this state yet).
Functions ¶
This section is empty.
Types ¶
type AuthOutcome ¶
type AuthOutcome struct {
Response protocol.RoutingEnvelope
CloseConn bool
// Device is the matched *devices.Device snapshot on the accept path.
// Nil on reject and on the ErrMalformedHelloFrame early return. The
// dispatcher carries this forward into the per-conn Auth slot so
// downstream verb handlers can read the authenticated device without
// re-validating the token (see #318 / docs/protocol-mobile.md §
// Authentication).
Device *devices.Device
}
AuthOutcome is the structured result of AuthenticateFirstFrame. The relay-conn caller forwards Response back through the binary→relay leg and, when CloseConn is true, asks the relay to close the phone WS with StatusUnauthorized after the Response has been written.
CloseConn carries the protocol-level intent (close-because-auth-failed) rather than the wire code itself; the close code is fixed at 4401 by spec and lives on the StatusUnauthorized constant.
func AuthenticateFirstFrame ¶
func AuthenticateFirstFrame( env protocol.RoutingEnvelope, token string, reg *devices.Registry, serverID string, logger *slog.Logger, ) (AuthOutcome, error)
AuthenticateFirstFrame is the per-connection token-validation predicate for the phone→relay→binary auth phase (docs/protocol-mobile.md § Authentication). It is invoked exactly once per phone conn — on the binary's receipt of the first frame for a given conn_id — and returns the routing envelope the binary should send back plus the close-or-keep signal the relay-conn layer will act on.
The function is carrier-agnostic with respect to how token reached the binary: it never parses WS headers, never reads env.Frame's payload for a token field, and never inspects a hello payload. The relay-conn ticket that wires this handler into phone traffic picks one of (a) extended routing envelope, (b) synthesized connection_opened control frame, or (c) amended hello payload, and forwards the extracted token here unchanged.
Two-state semantics: reg.Validate returns (Device, bool). A true result means the device row exists and was just bumped (the predicate already handled LastSeenAt under reg.mu — the handler does not call any further mutator). A false result means either never-paired or the row was removed via reg.Remove; both produce the same auth.invalid_token outcome per docs/protocol-mobile.md § Error codes line 535 ("Same UX as invalid_token"). The CodeAuthTokenRevoked constant is reserved for a future tombstone primitive and is NOT emitted by this handler.
SECURITY: token is never logged, never wrapped into any returned error, and never echoed to the phone. The matched device's name IS logged on accept but is NOT logged on reject (preventing name-enumeration probes from binary logs).
type Config ¶
type Config struct {
ServerID identity.ServerID
RelayURL string
BinaryVersion string
Logger *slog.Logger
// AllowInsecureScheme, when true, lets RelayURL use plain ws:// in
// addition to wss://. Test-only seam so e2e suites can point pyry at
// an httptest-hosted fakerelay over plaintext. Production callers
// leave this false; cmd/pyry flips it only when the operator sets
// PYRY_ALLOW_INSECURE_RELAY=1.
AllowInsecureScheme bool
}
Config carries the static configuration for a Connection. The caller resolves ServerID via internal/identity.LoadOrCreate before constructing Config — the relay package never touches the on-disk store, keeping the net package free of pairing / storage concerns.
type Connection ¶
type Connection struct {
// contains filtered or unexported fields
}
Connection runs the binary↔relay leg of the wire protocol. Lifecycle is tied to the context passed to Connect; cancellation closes the WS cleanly. Wait blocks until the lifecycle terminates; the returned error is the terminal classification (ErrServerIDConflict for fatal 4409, ctx.Err for graceful shutdown, or a wrapped transport error for unexpected halts).
func Connect ¶
func Connect(ctx context.Context, cfg Config) (*Connection, error)
Connect builds the transport, starts the lifecycle goroutine, and returns immediately. The connection is not yet Ready — observe Frames to consume post-handshake inbound frames, or call Wait to block on terminal classification. The caller is responsible for invoking Close during shutdown to release resources; ctx cancellation also drains the lifecycle.
func (*Connection) Close ¶
func (c *Connection) Close() error
Close requests a clean shutdown. Idempotent. After Close, Frames drains and closes; Wait returns.
func (*Connection) CloseConn ¶
func (c *Connection) CloseConn(connID string, code uint16) error
CloseConn asks the relay to close the named phone conn with the given WS close code. Builds a close-only routing envelope (no Frame) with CloseCode set and forwards via the transport. Returns transport.ErrNotConnected when the underlying WS is currently dropped or transport.ErrDisconnected if the live conn drops while Send is blocked (caller decides whether to retry; transport reconnect runs asynchronously). Wire mechanism: docs/protocol-mobile.md § Routing envelope (CloseCode).
CloseConn does NOT block on the relay's close-frame being delivered to the phone — the request is fire-and-forget at this layer. The per-conn close ack is implicit (no more inbound frames will arrive for connID).
The dispatcher's auth-reject path does NOT call CloseConn; instead it publishes one routing envelope carrying both Frame and CloseCode so the error envelope and the close are atomic on the wire. CloseConn is the explicit surface for callers that want close-without-payload (none today; reserved for the idle/inactivity sweep hinted at in #307).
func (*Connection) Frames ¶
func (c *Connection) Frames() <-chan protocol.RoutingEnvelope
Frames returns the channel of inbound frames. The channel closes when the lifecycle terminates. Frames are delivered in the order the underlying conn produces them; reconnects are transparent — frames resume on the new conn directly.
func (*Connection) Send ¶
func (c *Connection) Send(env protocol.RoutingEnvelope) error
Send marshals env to JSON and forwards it to the relay over the current transport conn. Returns transport.ErrDisconnected if the underlying conn is currently dropped (caller decides whether to retry or drop the frame); transport reconnect happens asynchronously, so a frame sent while disconnected is lost — that's consistent with the protocol's connection-lifecycle expectations (docs/protocol-mobile.md § Connection lifecycle).
func (*Connection) Wait ¶
func (c *Connection) Wait() error
Wait blocks until the lifecycle terminates and returns the terminal classification: ErrServerIDConflict (fatal), ctx.Err (graceful shutdown), or a wrapped transport error.
type InnerFrameV2Decoded ¶ added in v0.14.0
InnerFrameV2Decoded is the post-validation form of an InnerFrameV2: Type matches one of the discriminator constants and Data has been base64-decoded with the size cap enforced.
type V2Session ¶ added in v0.14.0
type V2Session struct {
// contains filtered or unexported fields
}
V2Session is the per-conn_id state held by V2SessionManager. Mutation is serialised by the manager's single dispatch goroutine (the loop is the lock); there is no mutex because flynn/noise's CipherStates are not safe for concurrent use and the manager guarantees a single writer per conn_id. The re-key responder (handleRekeyInit) atomically swaps s.send / s.recv in a single tuple assignment on this same goroutine; old *CipherState pointers are dropped from the struct and reclaimed by GC. No explicit Wipe() of the key bytes is exposed — the single-owner-goroutine invariant means no code path reads the old state after the swap, which is the practical zeroisation property.
func (*V2Session) State ¶ added in v0.14.0
func (s *V2Session) State() V2SessionState
State returns the externally-observable state. Called from the same goroutine that mutates today; a cross-goroutine reader (e.g. a broadcast layer added in a later slice) would need atomic.Int32 or a small mutex — tracked in spec § Open questions.
type V2SessionConfig ¶ added in v0.14.0
type V2SessionConfig struct {
// Frames is the inbound RoutingEnvelope stream from a relay.Connection
// (or an in-memory channel in tests). Run consumes until Frames
// closes or ctx is done.
Frames <-chan protocol.RoutingEnvelope
// Outbound forwards a single binary→relay RoutingEnvelope. Production
// wiring passes (*relay.Connection).Send. Non-nil errors are logged
// at debug and dropped — the relay leg's reconnect handles recovery
// (mirrors v1's cmd/pyry/relay.go forwarder posture).
Outbound func(protocol.RoutingEnvelope) error
// StaticPriv is the binary's 32-byte X25519 static private key.
StaticPriv []byte
// Devices is the token-validation predicate for hello.Token.
Devices *devices.Registry
// ServerID is surfaced into the hello_ack early-data payload.
ServerID string
// Logger receives lifecycle and reject events. Token, key bytes,
// payload bytes, AEAD ciphertext, and base64 forms thereof MUST NOT
// appear in any logged field.
Logger *slog.Logger
// Handlers is the application-layer envelope-type → handler table
// used for v2 open-state dispatch. Optional: nil or empty map means
// no app handlers are registered, and every open-state envelope falls
// through to a sealed protocol.unsupported reply via dispatch.Route.
// Mirror v1's internal/dispatch.Dispatcher.Register registration
// shape — production wires Handlers via the daemon, same handlers as
// v1.
//
// SECURITY: handlers run on the manager's single dispatch goroutine
// (same goroutine that mutates s.send / s.recv). Handlers MUST be
// synchronous and MUST NOT spawn long-lived background goroutines
// that retain a reference to the *dispatch.Conn passed in — the
// conn's outbound channel is per-frame and is drained before
// dispatchAppFrame returns; sends from a forked goroutine after that
// drain are silently lost (the channel is leaked but bounded by its
// capacity, and reclaimed by GC).
Handlers map[string]dispatch.Handler
}
V2SessionConfig parameterises V2SessionManager. All fields are required; NewV2SessionManager validates and panics or errors on missing required values per the documentation below.
SECURITY: StaticPriv is the binary's 32-byte X25519 static private key. It MUST NOT be logged, wrapped into an error message, or emitted on any wire surface. internal/keys and internal/noise document the same contract for the same bytes; this struct extends the contract to the manager's holding site.
type V2SessionManager ¶ added in v0.14.0
type V2SessionManager struct {
// contains filtered or unexported fields
}
V2SessionManager owns the per-conn_id v2 state machine. Construct with NewV2SessionManager; drive with Run. The manager is single-shot — Run returns when Frames closes or ctx is done, and the manager must not be reused.
Concurrency: Run is the only goroutine the manager owns. sessions is mutated exclusively by Run; no lock. This is intentionally simpler than internal/dispatch.Dispatcher (which spins one goroutine per conn_id); v2 in this slice runs no application handlers, every frame processes synchronously (~100µs Noise call or sub-µs JSON decode), so single-goroutine fan-in is correct and obviously safe. The re-key responder's CipherState swap (s.send, s.recv = newSend, newRecv) inherits this property: a single tuple assignment on this goroutine cannot be observed half-applied by any other code path, so the spec's atomic-switchover requirement is structural.
func NewV2SessionManager ¶ added in v0.14.0
func NewV2SessionManager(cfg V2SessionConfig) (*V2SessionManager, error)
NewV2SessionManager validates cfg and returns a ready manager. Panics on missing Frames or Logger (matching internal/dispatch.New style for programmer errors). Returns an error on missing Outbound, missing Devices, missing ServerID, or wrong-length StaticPriv.
func (*V2SessionManager) ActiveConnIDs ¶ added in v0.14.0
func (m *V2SessionManager) ActiveConnIDs(ctx context.Context) []string
ActiveConnIDs returns a snapshot of the conn IDs of every session currently in V2StateOpen — the authenticated, token-validated sessions to which Push may deliver. The result is an unordered set (Go's randomized map-iteration order); a caller that needs a stable order must sort it.
Safe to call from any goroutine other than the dispatch goroutine: the request is funneled onto Run via m.snapshot so m.sessions is never read concurrently with an in-flight handshake transition, dispatchAppFrame reply, re-key swap, or closeWith teardown. It is the enumeration half of the server-initiated fan-out primitive — the consumer (#572's assistant- turn bridge) calls this, then Push on each returned id to fan one unsolicited message envelope out to every connected phone. It is the v2 analog of v1's dispatch.Dispatcher.ActiveConns().
Sessions still handshaking (V2StateAwaitingInit) or handshake-complete-but- token-unvalidated (V2StateHandshakeComplete) are excluded — the same V2StateOpen security gate handlePush enforces, so a server push never reaches an un-authenticated peer. A torn-down session (deleted from the map by closeWith) cannot appear.
Returns nil on caller ctx cancellation, or when Run has already exited (Frames closed, no receiver on m.snapshot) and the caller's ctx then fires — both equivalent to "no open sessions" for the broadcast consumer, which fans out to nobody this round and re-enumerates on the next turn. nil and an empty non-nil slice are interchangeable (both len 0); a snapshot has no failure the caller can act on, so no error is returned.
Production wire-up of *V2SessionManager into the cmd/pyry daemon for server-initiated fan-out lands in a separate ticket (#572); until then this method is reachable only from internal/relay tests.
func (*V2SessionManager) Push ¶ added in v0.14.0
Push seals env under the addressed session's send CipherState, wraps it as a noise_msg transport frame, and forwards it to the phone. Safe to call from any goroutine other than the dispatch goroutine: the request is funneled onto Run via m.push so s.send is never touched concurrently with an in-flight dispatchAppFrame reply or a re-key swap. It is the missing primitive behind server-initiated delivery to a phone (the "broadcast layer" deferred at the V2Session / State() comments).
connID names a specific connected phone. The caller owns env entirely (Type, ID, TS, Payload); Push performs no envelope validation — it is a transport primitive.
Returns ErrConnNotFound (wraps control.ErrConnNotFound) when no session with connID exists or it has been torn down; ErrSessionNotOpen when the session exists but is not in V2StateOpen (still handshaking, or handshake-complete-but-token-unvalidated — refusing the push keeps server output away from an un-authenticated peer); ctx.Err() on caller cancellation; or a wrapped marshal/seal error (realistically unreachable under correct flynn/noise). Returns nil once the sealed frame is forwarded to Outbound — a transport-level drop (relay disconnected) is logged at debug inside m.send and NOT surfaced, matching v1 reconnect semantics and the rest of the package.
Production wire-up of *V2SessionManager into the cmd/pyry daemon for server-initiated pushes lands in a separate ticket (#572); until then this method is reachable only from internal/relay tests.
func (*V2SessionManager) Rekey ¶ added in v0.14.0
func (m *V2SessionManager) Rekey(ctx context.Context, connID string) error
func (*V2SessionManager) Run ¶ added in v0.14.0
func (m *V2SessionManager) Run(ctx context.Context) error
Run drives the state machine until Frames closes or ctx is cancelled. Returns ctx.Err() on cancellation, nil on Frames close. Every per-conn session is released on return; no goroutines outlive Run.
runCtx is a derived-cancel context so per-session timer-callback goroutines (spawned by armRekeyTimer / armRekeyReplyTimer via time.AfterFunc) unblock cleanly when Run exits. The callbacks select on (m.wake, runCtx.Done) so a fired-but-undelivered wake completes via the ctx branch on shutdown and leaves no goroutine behind.
type V2SessionState ¶ added in v0.14.0
type V2SessionState int
V2SessionState is the externally-observable lifecycle state of a per-conn V2Session. The handshakeComplete substate is distinct from open even though both can be set inside the same noise_init handler: the field exists so the gating test pins the "handler chain unreachable from handshakeComplete" invariant deterministically (AC #1 / #4).
const ( V2StateAwaitingInit V2SessionState = iota V2StateHandshakeComplete V2StateOpen V2StateClosed )