subc_protocol/lib.rs
1//! subc wire contract.
2//!
3//! This crate is the single source of truth for the subc <-> module wire,
4//! shared by subc-core and AFT. It defines the **envelope** (the fixed
5//! 21-byte routing header subc splices on), the canonical subc-generated body
6//! schemas such as [`ErrorBody`], and the capability manifest. JSON-RPC request
7//! and response bodies remain module-owned opaque payloads to subc.
8//!
9//! ## The envelope (locked — see docs/subc-core-architecture.md §4.8)
10//!
11//! ```text
12//! offset size field type purpose
13//! 0 4 len u32 # of BODY bytes after this 21-byte header
14//! 4 1 ver u8 envelope version
15//! 5 1 type u8 frame kind (see FrameType)
16//! 6 1 flags u8 bit0 BINARY · bits1-2 PRIORITY · bit3 LAST · bits4-5 ADMISSION · bit6 DAEMON_ORIGIN · bit7 SUBSCRIPTION
17//! 7 2 channel u16 route = (component, session); 0 = subc itself
18//! 9 4 epoch u32 per-slot binding epoch; 0 on channel 0
19//! 13 8 corr u64 correlation id; CANCEL carries the target call's corr
20//! 21 -> body
21//! ```
22//!
23//! Little-endian (same-machine, native, no byte-swap on the hot path).
24//!
25//! **Frozen prefix (the versioning invariant):** `len` (u32 @ 0) and `ver`
26//! (u8 @ 4) keep fixed meaning + position in *every* future version. A reader
27//! of any version can therefore always read the first 5 bytes, learn `ver`,
28//! look up that version's header length, read the rest, and splice `len` body
29//! bytes. `decode_header` enforces this discipline.
30
31#![forbid(unsafe_code)]
32
33use std::{error::Error, fmt, path::PathBuf};
34
35use serde::{Deserialize, Serialize};
36
37pub use machine_id::{MachineId, MachineIdError};
38
39pub mod call_mode;
40pub mod frame;
41pub mod framed_body;
42pub mod machine_id;
43pub mod manifest;
44pub mod peer;
45pub mod scope;
46pub mod session;
47pub mod tool_call;
48
49/// Canonical error codes emitted by subc.
50///
51/// Error frames remain extensible strings, but these daemon-owned route-open
52/// outcomes need identical spelling across the daemon and SDK retry policies.
53pub mod error_codes {
54 use crate::Flags;
55
56 pub const UNKNOWN_CHANNEL: &str = "unknown_channel";
57 pub const STALE_ROUTE_EPOCH: &str = "stale_route_epoch";
58 /// A module reply exceeds the client connection's whole egress byte budget.
59 /// TERMINAL for this request: the module already received it, and retrying
60 /// unchanged would produce the same oversized reply. The route stays open.
61 pub const FRAME_TOO_LARGE: &str = "frame_too_large";
62 pub const UNKNOWN_MODULE: &str = "unknown_module";
63 pub const MODULE_REMOVED: &str = "module_removed";
64 /// The target module's endpoint is draining for a reload, restart or disable.
65 ///
66 /// On the data plane (an `ERROR` frame answering a `REQUEST` on a bound route)
67 /// this code is a PRE-SEND GUARANTEE: the daemon returns it only when the
68 /// request could not take a route credit because the endpoint is draining,
69 /// and it returns it BEFORE forwarding, so the module never received the
70 /// request. A caller may therefore re-dispatch the same request once the
71 /// route is reopened without risking a duplicated side effect, exactly as it
72 /// may after `unknown_channel`. The daemon keeps this guarantee:
73 /// `supervisor_reload_rejects_new_work_during_drain` asserts the module's
74 /// event journal never records the rejected request. A request the module
75 /// already received is answered by the module (or its route closes with
76 /// `route.closed`), never by this code.
77 pub const MODULE_RELOADING: &str = "module_reloading";
78 pub const MODULE_WARMING: &str = "module_warming";
79 pub const TARGET_UNAVAILABLE: &str = "target_unavailable";
80 /// A flow-scoped route targets a module that does not provide
81 /// either `flow-scopes/v1` or `call-modes/v1`. TERMINAL: decoding `flow_id`
82 /// alone does not promise flow behaviour, and removing it would silently
83 /// change the identity.
84 pub const TARGET_FLOW_UNSUPPORTED: &str = "target_flow_unsupported";
85 /// An agent-run-scoped route targets a module providing neither
86 /// `agent-run-scopes/v1` nor `call-modes/v1`, or a delegating run targets a
87 /// module without `call-modes/v1`. TERMINAL: removing `run_id` or delegation
88 /// would silently change the identity or authority under which the route acts.
89 pub const TARGET_AGENT_RUN_UNSUPPORTED: &str = "target_agent_run_unsupported";
90 pub const MODULE_TIMEOUT: &str = "module_timeout";
91 /// The target module is declared as speaking no subc wire protocol
92 /// (`protocol: "none"` in daemon config), so it has no control lane and can
93 /// never accept a route. The daemon supervises its process and nothing else.
94 ///
95 /// TERMINAL, and deliberately neither of its two neighbours. It is not
96 /// `unknown_module`, which means "no module of this id is registered or
97 /// supervised here" and is likewise terminal; retrying here would storm the
98 /// daemon forever, because the answer is a property of the module's
99 /// declaration rather than of its current state. It is not `module_removed` either: the module is configured,
100 /// running, and supervised. Only an edit to its configuration can change
101 /// this answer, and a caller cannot wait that out.
102 pub const MODULE_NO_PROTOCOL: &str = "module_no_protocol";
103 /// A request field is malformed. The error's `detail.field` names the field
104 /// (for a `route.open`, `role_versions`). TERMINAL: the same request will be
105 /// refused the same way every time, so only a corrected request can succeed.
106 pub const INVALID_REQUEST: &str = "invalid_request";
107
108 /// A `route.open` named a scope whose owner is configured but has not
109 /// synced since this daemon incarnation started. RETRYABLE: after a daemon
110 /// restart a carrier's open can arrive before the owner re-syncs, and the
111 /// carrier waits within its own deadline. See `docs/designs/daemon-scopes.md`.
112 pub const SCOPE_NOT_SYNCED: &str = "scope_not_synced";
113 /// A scoped `route.open` was admitted, but the scope record changed before
114 /// the module's bind committed. Nothing was sent on the route, so the caller
115 /// may re-open against the current record: RETRYABLE.
116 pub const SCOPE_CHANGED: &str = "scope_changed";
117 /// A scoped `route.open` named no `scope_epoch`. Every opener names one,
118 /// the owner included, so an old call can never be carried into a newer
119 /// session that reused the ref. TERMINAL.
120 pub const SCOPE_EPOCH_REQUIRED: &str = "scope_epoch_required";
121 /// A scoped `route.open` named a ref the owner's synced set does not hold,
122 /// or an owner that is not a configured module. TERMINAL.
123 pub const SCOPE_NOT_LIVE: &str = "scope_not_live";
124 /// A scoped `route.open` named a `scope_epoch` that is not the live one, or
125 /// the scope ended between admission and commit. TERMINAL.
126 pub const SCOPE_ENDED: &str = "scope_ended";
127 /// The opener of a scoped `route.open` is neither the scope's owner nor a
128 /// listed carrier, or it is a targeted carrier and the target module is not
129 /// in its list. TERMINAL.
130 pub const SCOPE_NOT_CARRIER: &str = "scope_not_carrier";
131 /// A scope with a bind-proof hash requires every opener, including its
132 /// owner, to present the proof. TERMINAL.
133 pub const SCOPE_BIND_PROOF_REQUIRED: &str = "scope_bind_proof_required";
134 /// The proof is malformed or does not match the scope's hash. TERMINAL.
135 pub const SCOPE_BIND_PROOF_MISMATCH: &str = "scope_bind_proof_mismatch";
136 /// An idle-only epoch/proof replacement found routes, admitted binds or
137 /// connected presence under the live epoch. Per-record refusal. TERMINAL.
138 pub const SCOPE_EPOCH_IN_USE: &str = "scope_epoch_in_use";
139 /// Raised by a carrier, never by the daemon: the daemon does not advertise
140 /// `scopes/v1`, so the carrier fails the call instead of opening an
141 /// unscoped route.
142 pub const SCOPE_UNSUPPORTED: &str = "scope_unsupported";
143
144 /// `scope.sync` or `scope.apply` came from a connection that is not the
145 /// owner's sync authority: another connection of the same launch holds it,
146 /// or this connection's launch is no longer the owner's current one (a
147 /// blue/green swap candidate before cutover, or an incumbent after it).
148 pub const SCOPE_SYNC_NOT_AUTHORITY: &str = "scope_sync_not_authority";
149 /// `scope.apply` came from a connection that has not taken sync authority
150 /// through an accepted full `scope.sync`. The whole call changes nothing.
151 pub const SCOPE_SYNC_REQUIRED: &str = "scope_sync_required";
152 /// `scope.sync` or `scope.apply` carried a generation no larger than the last
153 /// one the authority accepted. The whole call is refused and nothing changes.
154 pub const SCOPE_SYNC_STALE: &str = "scope_sync_stale";
155 /// `scope.sync` or `scope.apply` exceeds the owner's live-scope limit.
156 /// The whole call is refused and nothing changes.
157 pub const SCOPE_LIVE_LIMIT_EXCEEDED: &str = "scope_live_limit_exceeded";
158 /// One record in a `scope.sync` or `scope.apply` carried more attribute bytes
159 /// than a scope may hold. The whole call is refused and nothing changes.
160 pub const SCOPE_ATTRIBUTES_TOO_LARGE: &str = "scope_attributes_too_large";
161
162 // Per-record refusals: each is reported against one record in the
163 // `scope.sync` or `scope.apply` reply. A refusal itself does not change the
164 // ref or undo expiry processing; other records in the call still apply.
165
166 /// The record lowers the `scope_epoch` the daemon holds for its ref.
167 pub const SCOPE_EPOCH_REGRESSED: &str = "scope_epoch_regressed";
168 /// The record names an `(owner, ref, scope_epoch)` that already ended in
169 /// this daemon incarnation; an ended session cannot come back.
170 pub const SCOPE_EPOCH_ENDED: &str = "scope_epoch_ended";
171 /// The record's deadline has passed, or this ref at this epoch was ended by
172 /// expiry and its tombstone is still held. The same session epoch cannot
173 /// return.
174 pub const SCOPE_EXPIRED: &str = "scope_expired";
175 /// The record adds, removes or changes the deadline of a live scope at the
176 /// same epoch. A different deadline requires a new session epoch.
177 pub const SCOPE_EXPIRY_IMMUTABLE: &str = "scope_expiry_immutable";
178 /// The record's deadline is more than `scope::MAX_SCOPE_EXPIRY_AHEAD_MS`
179 /// ahead of the daemon's current Unix wall clock.
180 pub const SCOPE_EXPIRY_TOO_FAR: &str = "scope_expiry_too_far";
181 /// The record changes `kind` at the same `scope_epoch`.
182 pub const SCOPE_KIND_CHANGED: &str = "scope_kind_changed";
183 pub const INVALID_WORKDIR: &str = "invalid_workdir";
184 pub const SCOPE_WORKDIR_CHANGED: &str = "scope_workdir_changed";
185 /// Installed flow identity cannot be added, changed or removed within an epoch.
186 pub const SCOPE_FLOW_IDENTITY_CHANGED: &str = "scope_flow_identity_changed";
187 pub const SCOPE_PROJECT_CHANGED: &str = "scope_project_changed";
188 /// The record sets authority-controlled attributes and its owner is not
189 /// listed in `scope_authority_owners`, or combines `on_behalf_of_agent` with
190 /// `agent_id`, `delegates`, `flow_id` or `run_id`, or supplies an incomplete
191 /// installed flow identity or one without `flow_id`.
192 pub const SCOPE_ATTRIBUTE_NOT_PERMITTED: &str = "scope_attribute_not_permitted";
193 /// The record's parent link is not permitted: the parent's owner has synced
194 /// and the parent is not live at the named epoch, the syncing owner is
195 /// neither the parent's owner nor in its `child_owners`, or the link would
196 /// close a cycle.
197 pub const SCOPE_PARENT_NOT_PERMITTED: &str = "scope_parent_not_permitted";
198 /// A targeted carrier entry lists no target modules, or more than
199 /// `scope::MAX_CARRIER_TARGETS`.
200 pub const SCOPE_CARRIER_TARGETS_INVALID: &str = "scope_carrier_targets_invalid";
201 /// The record sets `delegates` without an `agent_id` to delegate.
202 pub const SCOPE_DELEGATES_WITHOUT_AGENT: &str = "scope_delegates_without_agent";
203 /// The record sets `run_id` without either `agent_id` (an agent run) or
204 /// `on_behalf_of_agent` (a worker run).
205 pub const SCOPE_RUN_ID_WITHOUT_AGENT: &str = "scope_run_id_without_agent";
206 /// The record sets both `run_id` and `flow_id`; a run scope is not a flow scope.
207 pub const SCOPE_RUN_ID_WITH_FLOW_ID: &str = "scope_run_id_with_flow_id";
208 /// Legacy refusal for a record setting `run_id` with `delegates`.
209 /// No longer emitted by validation: run records may delegate, and route
210 /// admission instead requires a target providing `call-modes/v1`.
211 pub const SCOPE_RUN_ID_DELEGATES: &str = "scope_run_id_delegates";
212
213 /// An `operator.confirm` was declined or withdrawn. `detail.reason` is
214 /// `person`, `backoff`, `route_closed`, `module_closed` or `caller_cancelled`.
215 pub const OPERATOR_DECLINED: &str = "operator_declined";
216 /// An `operator.confirm` could not prompt or complete. `detail.reason` is
217 /// `no_presence`, `timeout`, `module_limit`, `queue_full`, `queue_wait`,
218 /// `provider_stuck`, `unsupported_platform` or `provider_error`.
219 pub const OPERATOR_PRESENCE_UNAVAILABLE: &str = "operator_presence_unavailable";
220 /// The summary of an `operator.confirm` breaks the daemon's summary rules.
221 pub const OPERATOR_SUMMARY_INVALID: &str = "operator_summary_invalid";
222 /// An `operator.confirm` is not from a nonce-proven module connection for
223 /// an open route with a verified opener on that connection.
224 pub const OPERATOR_REQUEST_NOT_PERMITTED: &str = "operator_request_not_permitted";
225
226 /// Whether a `route.open` refusal carrying `code` may be retried in place
227 /// within the caller's deadline, or is terminal for the target as named.
228 ///
229 /// This lives beside the codes because every consumer with its own
230 /// connection layer needs the same answer: a copied list breaks loudly on
231 /// a renamed code and silently on an added one. The SDKs call this; the
232 /// golden `decision_tables.json` (`route_open_retryable`) is the record
233 /// the daemon and every SDK are tested against, and the test in
234 /// `golden_json.rs` holds this function to it.
235 ///
236 /// Unknown codes are terminal: a refusal this crate has never heard of
237 /// must not be retried on the strength of a match-all arm.
238 ///
239 /// `unknown_module` is terminal: it now means only "no module of this id
240 /// is registered or supervised here" — a typo, or a peer not deployed on
241 /// this host. The daemon reports a configured-but-late target with its own
242 /// retryable codes (`module_warming`, `target_unavailable`), so a caller
243 /// that races an unsupervised module's HELLO owns its own retry; retrying
244 /// in place only papers over that race for one narrow window.
245 pub fn is_retryable_route_open(code: &str) -> bool {
246 if matches!(
247 code,
248 TARGET_FLOW_UNSUPPORTED
249 | TARGET_AGENT_RUN_UNSUPPORTED
250 | SCOPE_BIND_PROOF_REQUIRED
251 | SCOPE_BIND_PROOF_MISMATCH
252 | SCOPE_EPOCH_IN_USE
253 ) {
254 return false;
255 }
256 matches!(
257 code,
258 MODULE_RELOADING
259 | MODULE_WARMING
260 | TARGET_UNAVAILABLE
261 | MODULE_TIMEOUT
262 | SCOPE_NOT_SYNCED
263 | SCOPE_CHANGED
264 )
265 }
266
267 /// Whether the caller should evict this established route, reopen it, and
268 /// resend the request once. Consumers mapping route death to their own
269 /// custody, provider, or suspect verdict keep their own named code lists;
270 /// sharing this predicate for those meanings can change a verdict on a
271 /// protocol bump (prefrontal#59).
272 ///
273 /// Takes envelope flags so the daemon-origin check can be enabled here in
274 /// one place. Phase 2 requires first that every daemon a consumer can meet
275 /// sets DAEMON_ORIGIN on these error frames, both landed and deployed;
276 /// only then may this predicate require the bit. Requiring it sooner makes
277 /// a new SDK against an older daemon stop evicting on a genuine
278 /// `stale_route_epoch` — the failure this predicate is meant to prevent.
279 ///
280 /// The daemon emits these codes in `RouterError::to_error_frame` at
281 /// `crates/subc-daemon/src/router.rs` (UnknownChannel and StaleRouteEpoch).
282 pub fn is_established_route_dead(_flags: Flags, code: &str) -> bool {
283 matches!(code, UNKNOWN_CHANNEL | STALE_ROUTE_EPOCH)
284 }
285}
286
287pub use frame::{Frame, FrameBuildError};
288
289/// Why subc is closing a module's client routes.
290#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
291#[serde(rename_all = "snake_case")]
292pub enum RouteCloseReason {
293 Reload,
294 Restart,
295 Disable,
296 Crash,
297 /// A live route became forbidden because newly attested capability metadata
298 /// matched its supervised opening module's deny edge.
299 CapabilityDenied,
300 /// The route's scope ended: it expired, its owner ended it, or replaced it
301 /// with a higher `scope_epoch` (a new session under the same ref).
302 ScopeEnded,
303 /// The route's opener is no longer a listed carrier of its scope, or the
304 /// route's target was removed from that carrier's target list.
305 ScopeCarrierRemoved,
306 /// The scope's `delegates` went from true to false, or its `agent_id`,
307 /// `on_behalf_of_agent`, `flow_id` or `run_id` changed.
308 ScopeDelegationChanged,
309 /// The scope's parent ended, so its stamp no longer names a live parent.
310 ScopeParentEnded,
311}
312
313/// Per-route bind identity shared by client-facing and module-facing control.
314///
315/// EVERY FIELD HERE IS CLIENT-SUPPLIED AND UNATTESTED. The daemon canonicalizes
316/// `project_root` as a path but does not verify that the caller has any relation
317/// to it, and `harness`, `session`, and `project_id` are strings the caller chose.
318/// A client holding the connection key can present any values it likes.
319///
320/// This sits directly above `Principal`, which is the opposite: stamped BY the
321/// daemon from a launch nonce it minted. The two travel together on every
322/// `route.bind`, so a module reading them side by side is reading one fact it can
323/// trust and four it cannot. THE DISTINCTION IS INVISIBLE FROM THE TYPES, which
324/// is why it is written here.
325///
326/// So these fields are for SCOPING AND ATTRIBUTION -- which project's state to
327/// open, which session to thread, what to log -- and never for authorization. A
328/// module that grants capability on `harness` or trusts `project_root` to bound
329/// what a caller may reach has built an authorization check on a value the caller
330/// controls. Gate on `Principal` instead, and where a module needs a caller fact
331/// subc does not stamp, it must establish that fact itself rather than believe
332/// this struct.
333#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
334#[non_exhaustive]
335pub struct BindIdentity {
336 pub project_root: PathBuf,
337 pub harness: String,
338 pub session: String,
339 /// The entorhinal-registered project id (`pj-…`) for `project_root`, when
340 /// the root is a registered project. Aliases count as registered projects;
341 /// implicit roots do not. Absent means "no stable id, key on the triple",
342 /// not "unknown".
343 ///
344 /// A producer sends the id on every bind of a session or on none. A producer
345 /// that alternates between `Some(id)` and `None` across binds silently forks
346 /// the consumer's lineage into separate stores, with no error at either end.
347 /// Therefore, a producer that cannot answer consistently must answer `None`
348 /// consistently.
349 ///
350 /// Resolve this at most once per session, before its first bind, and persist
351 /// the outcome with the session. ALF's resolver has real `Resolved`, `Unavailable`,
352 /// and `Disabled` outcomes: if unavailable at cold start is re-resolved on a
353 /// later bind, the session can alternate from `None` to `Some(id)`. Send only
354 /// registered or alias resolutions, never implicit, unavailable, or disabled
355 /// fallback ids.
356 #[serde(default, skip_serializing_if = "Option::is_none")]
357 pub project_id: Option<String>,
358 /// The opener's claim about the kind of build it is, sent on `route.open`.
359 /// [`BUILD_CLASS_PRODUCTION`] marks a production build whose integrity the
360 /// opener has verified.
361 ///
362 /// Like every other field here it is unattested. The daemon honours it only
363 /// when the opener's principal is `Reserved { module_id: "callosum" }`, and
364 /// only the exact value [`BUILD_CLASS_PRODUCTION`]; any other value counts
365 /// as absent. From any other opener it is ignored. The daemon never relays
366 /// it to the target module: the identity on `route.bind` never carries it.
367 ///
368 /// Absent is omitted from the wire, so existing identities keep their bytes,
369 /// and a reader that predates the field drops it, which grants nothing.
370 /// Set it on the public field after [`BindIdentity::new`].
371 #[serde(default, skip_serializing_if = "Option::is_none")]
372 pub build_class: Option<String>,
373}
374
375/// The only [`BindIdentity::build_class`] value the daemon honours.
376pub const BUILD_CLASS_PRODUCTION: &str = "production";
377
378impl BindIdentity {
379 /// Constructs an identity with no registered project id.
380 ///
381 /// Use this instead of a struct literal so future additive identity fields do
382 /// not force construction-site migrations across the fleet.
383 pub fn new(
384 project_root: impl Into<PathBuf>,
385 harness: impl Into<String>,
386 session: impl Into<String>,
387 ) -> Self {
388 Self {
389 project_root: project_root.into(),
390 harness: harness.into(),
391 session: session.into(),
392 project_id: None,
393 build_class: None,
394 }
395 }
396}
397
398/// Caller fact stamped by subc on each route.bind relayed to a module.
399#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
400#[serde(tag = "kind", rename_all = "snake_case")]
401pub enum Principal {
402 /// A daemon-spawned module proved possession of its launch nonce.
403 Reserved { module_id: String },
404 /// No consumer identity was presented; the caller is a direct key-holder.
405 Direct,
406 /// Reserved vocabulary for a future degraded/no-key-auth mode.
407 Unverified,
408}
409
410/// Explicit target for a route open/bind operation.
411///
412/// RouteTarget.kind ↔ ProviderRole mapping:
413///
414/// | RouteTarget.kind | required ProviderRole | disambiguator |
415/// |---|---|---|
416/// | `tool_provider` | `ToolProvider` | v1: ≤1 per module |
417/// | `management_surface` | `ManagementSurface` | v1: ≤1 per module |
418/// | `internal_service` | `InternalService` | `service_id` (multiple allowed) |
419///
420/// `ProviderRole::PipelineStage` is intentionally unroutable; pipeline modules
421/// are wired by an orchestrator rather than opened directly by clients.
422#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
423#[serde(tag = "kind", rename_all = "snake_case")]
424pub enum RouteTarget {
425 ToolProvider {
426 module_id: String,
427 },
428 ManagementSurface {
429 module_id: String,
430 },
431 InternalService {
432 module_id: String,
433 service_id: String,
434 },
435}
436
437/// Envelope protocol version this build speaks.
438pub const PROTOCOL_VERSION: u8 = 2;
439
440/// The version of THIS crate (`subc-protocol`) as compiled into the linking
441/// binary — the fleet's shared wire-vocabulary version, and the value
442/// `ManifestProvenance.wire_crate_version` declares. Not the version of a
443/// module's own envelope or payload crates: those are different numbering
444/// spaces, and declaring one here produces a confident wrong answer at any
445/// version gate (insula shipped exactly that before the referent was written
446/// down). `env!` makes it a property of the compiled binary, not of whatever
447/// source tree sits beside it at run time.
448pub const SUBC_PROTOCOL_CRATE_VERSION: &str = env!("CARGO_PKG_VERSION");
449
450/// Oldest envelope protocol version this build accepts.
451pub const MIN_SUPPORTED_VERSION: u8 = 2;
452
453/// Env var subc sets on each supervised child telling it the module_id it is
454/// supervised under, so it can register under that id.
455pub const SUBC_MODULE_ID_ENV: &str = "SUBC_MODULE_ID";
456
457/// Env var subc sets, on each spawn of a `reserved` module only, to a fresh
458/// one-time launch nonce. The child echoes it in `ModuleHelloBody::launch_nonce`;
459/// subc accepts a reserved module_id's HELLO only when the nonce matches the one it
460/// last injected for that id. Non-reserved modules never receive it.
461pub const SUBC_LAUNCH_NONCE_ENV: &str = "SUBC_LAUNCH_NONCE";
462
463/// Fixed header length for `PROTOCOL_VERSION` 2.
464pub const HEADER_LEN: usize = 21;
465
466/// Bytes of the frozen prefix (`len` u32 + `ver` u8) that are stable across
467/// every envelope version. A reader needs only these to learn the version and
468/// thus the full header length.
469pub const FROZEN_PREFIX_LEN: usize = 5;
470
471/// Maximum frame body accepted before allocation.
472///
473/// This 64 MiB starting cap prevents a malformed header from forcing an
474/// unbounded allocation. Future protocol versions can negotiate or encode a
475/// different cap while preserving the frozen prefix.
476pub const MAX_FRAME_BODY_LEN: u32 = 64 * 1024 * 1024;
477
478/// Largest frame, `HEADER_LEN` included, that the daemon delivers from a module
479/// to a client: a reply, stream frame, error, reverse request or push. A module
480/// sizes what it sends to a client against this, not against
481/// `MAX_FRAME_BODY_LEN`.
482///
483/// A larger module frame is never forwarded to the client. A reply, stream
484/// frame or error that is too large ends its request with a `frame_too_large`
485/// error; a reverse request that is too large is answered with an error to the
486/// module; an unsolicited push that is too large closes the client connection.
487///
488/// Requests from a client to a module are not held to this limit; they are
489/// bounded only by `MAX_FRAME_BODY_LEN`.
490pub const MAX_DELIVERED_FRAME_LEN: usize = 4 * 1024 * 1024;
491
492/// Canonical JSON body for all subc-generated `ERROR` frames.
493///
494/// `detail` is an optional machine-parsable surface for refusals whose remedy
495/// needs more than a code (e.g. a producer-published backoff number, an
496/// observed-vs-configured size pair). Absent detail serializes to nothing, so
497/// bodies without it are byte-identical to the pre-detail wire and older
498/// readers simply never see the field. Producers document each code's detail
499/// fields where the code is defined; `detail` must never carry secrets.
500#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
501pub struct ErrorBody {
502 pub code: String,
503 pub message: String,
504 #[serde(default, skip_serializing_if = "Option::is_none")]
505 pub detail: Option<serde_json::Value>,
506}
507
508impl ErrorBody {
509 /// A detail-less error body; the common case.
510 pub fn new(code: impl Into<String>, message: impl Into<String>) -> Self {
511 Self {
512 code: code.into(),
513 message: message.into(),
514 detail: None,
515 }
516 }
517
518 /// Attach a machine-parsable detail object to this error.
519 pub fn with_detail(mut self, detail: serde_json::Value) -> Self {
520 self.detail = Some(detail);
521 self
522 }
523}
524
525/// Module-to-subc `HELLO` body used during module registration.
526#[derive(Clone, Serialize, Deserialize, PartialEq)]
527pub struct ModuleHelloBody {
528 pub manifest: manifest::ModuleManifest,
529 pub protocol_ver: u8,
530 #[serde(default)]
531 pub control_ops: Option<Vec<String>>,
532 /// One-time launch nonce, echoed back from the `SUBC_LAUNCH_NONCE` environment
533 /// variable the daemon injected when it spawned this process. Only a daemon-spawned
534 /// process for a `reserved` module receives a nonce; subc accepts a reserved
535 /// `module_id`'s HELLO only when this matches the nonce it last injected for that
536 /// id, so a different process cannot register as a reserved module while the real
537 /// one is down/restarting. Absent (`serde(default)`) for non-reserved modules and
538 /// self-connecting providers, which are never nonce-checked.
539 #[serde(default, skip_serializing_if = "Option::is_none")]
540 pub launch_nonce: Option<String>,
541}
542
543// Hand-written so the launch nonce is never printed. The nonce is the credential
544// that attributes a connection to a supervised module, and a derived Debug would
545// write it into any log line or panic message that formats this value. Same
546// reasoning as ConnectionInfo's Debug in subc-transport.
547impl fmt::Debug for ModuleHelloBody {
548 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
549 f.debug_struct("ModuleHelloBody")
550 .field("manifest", &self.manifest)
551 .field("protocol_ver", &self.protocol_ver)
552 .field("control_ops", &self.control_ops)
553 .field(
554 "launch_nonce",
555 &self
556 .launch_nonce
557 .as_ref()
558 .map(|nonce| format!("<{} bytes redacted>", nonce.len())),
559 )
560 .finish()
561 }
562}
563
564/// subc-to-module `HELLO_ACK` body used during module registration.
565#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
566pub struct ModuleHelloAckBody {
567 pub negotiated_ver: u8,
568 pub subc_ops: Vec<String>,
569 pub subc_capabilities: Vec<String>,
570 /// The module's resolved storage descriptor, when the daemon's central config
571 /// configures managed storage. Carried opaquely here (subc-protocol stays a
572 /// thin wire crate with no storage/database dependency); a module that uses
573 /// managed storage deserializes it into `cortexkit_store_types::StorageDescriptor`
574 /// and hands it to `cortexkit-store`. Absent when no storage is configured, and
575 /// `serde(default)` so an older module simply ignores it.
576 #[serde(default, skip_serializing_if = "Option::is_none")]
577 pub storage: Option<serde_json::Value>,
578 /// The daemon's machine id (see [`MachineId`]): a name for this machine,
579 /// never an authority. Nothing may admit a peer, grant trust or skip a check
580 /// because two messages carry the same value.
581 ///
582 /// Carried as a plain string so one malformed value cannot fail the whole
583 /// registration reply; a module validates it with [`MachineId::parse`].
584 /// Absent from a daemon that predates the machine id, which a module must
585 /// read as exactly that, never as "no machine" and never as a reason to mint
586 /// its own.
587 #[serde(default, skip_serializing_if = "Option::is_none")]
588 pub machine_id: Option<String>,
589}
590
591/// Frame kind (`type` byte at offset 5).
592///
593/// `CANCEL`, `PING`, `PONG`, and `GOODBYE` are pure-header frames (`len == 0`);
594/// only `HELLO`/`HELLO_ACK` and the RPC payloads carry bodies.
595#[derive(Debug, Clone, Copy, PartialEq, Eq)]
596#[repr(u8)]
597pub enum FrameType {
598 Request = 0,
599 Response = 1,
600 Push = 2,
601 StreamData = 3,
602 StreamEnd = 4,
603 Error = 5,
604 Cancel = 6,
605 Ping = 7,
606 Pong = 8,
607 Hello = 9,
608 HelloAck = 10,
609 Goodbye = 11,
610}
611
612impl FrameType {
613 /// Map the raw `type` byte to a `FrameType`, or `None` if unknown.
614 pub fn from_u8(b: u8) -> Option<Self> {
615 Some(match b {
616 0 => Self::Request,
617 1 => Self::Response,
618 2 => Self::Push,
619 3 => Self::StreamData,
620 4 => Self::StreamEnd,
621 5 => Self::Error,
622 6 => Self::Cancel,
623 7 => Self::Ping,
624 8 => Self::Pong,
625 9 => Self::Hello,
626 10 => Self::HelloAck,
627 11 => Self::Goodbye,
628 _ => return None,
629 })
630 }
631
632 pub fn is_pure_header(self) -> bool {
633 matches!(self, Self::Cancel | Self::Ping | Self::Pong | Self::Goodbye)
634 }
635}
636
637/// Scheduling priority carried in `flags` bits 1-2. subc schedules on this
638/// without parsing the body.
639#[derive(Debug, Clone, Copy, PartialEq, Eq)]
640#[repr(u8)]
641pub enum Priority {
642 Passive = 0,
643 Interactive = 1,
644 Background = 2,
645}
646
647impl Priority {
648 fn from_bits(bits: u8) -> Option<Self> {
649 Some(match bits {
650 0 => Self::Passive,
651 1 => Self::Interactive,
652 2 => Self::Background,
653 _ => return None,
654 })
655 }
656}
657
658/// Admission behavior carried in `flags` bits 4-5.
659#[derive(Debug, Clone, Copy, PartialEq, Eq)]
660#[repr(u8)]
661pub enum AdmissionClass {
662 Normal = 0,
663 Expedite = 1,
664 Sheddable = 2,
665}
666
667impl AdmissionClass {
668 fn from_bits(bits: u8) -> Option<Self> {
669 Some(match bits {
670 0 => Self::Normal,
671 1 => Self::Expedite,
672 2 => Self::Sheddable,
673 _ => return None,
674 })
675 }
676}
677
678const FLAG_BINARY: u8 = 0b0000_0001; // bit 0
679const FLAG_PRIORITY_MASK: u8 = 0b0000_0110; // bits 1-2
680const FLAG_PRIORITY_SHIFT: u8 = 1;
681const FLAG_LAST: u8 = 0b0000_1000; // bit 3
682const FLAG_ADMISSION_MASK: u8 = 0b0011_0000; // bits 4-5
683const FLAG_ADMISSION_SHIFT: u8 = 4;
684pub const FLAG_DAEMON_ORIGIN: u8 = 0b0100_0000;
685/// A request credit the client explicitly declares as a held-open subscription.
686pub const FLAG_SUBSCRIPTION: u8 = 0b1000_0000;
687
688/// The `flags` byte (offset 6): binary, priority, last, admission, daemon origin, subscription.
689#[derive(Debug, Clone, Copy, PartialEq, Eq)]
690pub struct Flags(pub u8);
691
692impl Flags {
693 /// Build flags with the default [`AdmissionClass::Normal`] class.
694 pub fn new(binary: bool, priority: Priority, last: bool) -> Self {
695 let mut b = 0u8;
696 if binary {
697 b |= FLAG_BINARY;
698 }
699 b |= (priority as u8) << FLAG_PRIORITY_SHIFT;
700 if last {
701 b |= FLAG_LAST;
702 }
703 Flags(b)
704 }
705
706 /// Return these flags with a typed admission class.
707 pub fn with_admission_class(mut self, admission_class: AdmissionClass) -> Self {
708 self.0 =
709 (self.0 & !FLAG_ADMISSION_MASK) | ((admission_class as u8) << FLAG_ADMISSION_SHIFT);
710 self
711 }
712
713 /// Body is raw bytes (bulk lane) rather than JSON-RPC.
714 pub fn is_binary(self) -> bool {
715 self.0 & FLAG_BINARY != 0
716 }
717
718 /// Final frame of a streamed message.
719 pub fn is_last(self) -> bool {
720 self.0 & FLAG_LAST != 0
721 }
722
723 /// Decode the priority bits, or `None` if they hold a reserved value.
724 pub fn priority(self) -> Option<Priority> {
725 Priority::from_bits((self.0 & FLAG_PRIORITY_MASK) >> FLAG_PRIORITY_SHIFT)
726 }
727
728 /// Decode the admission-class bits, or `None` if they hold `0b11`.
729 pub fn admission_class(self) -> Option<AdmissionClass> {
730 AdmissionClass::from_bits((self.0 & FLAG_ADMISSION_MASK) >> FLAG_ADMISSION_SHIFT)
731 }
732
733 /// True when a request was explicitly opened as a held-open subscription.
734 pub fn is_subscription(self) -> bool {
735 self.0 & FLAG_SUBSCRIPTION != 0
736 }
737
738 /// True when the frame was authored by the daemon.
739 pub fn is_daemon_origin(self) -> bool {
740 self.0 & FLAG_DAEMON_ORIGIN != 0
741 }
742
743 /// Return these flags with daemon origin asserted.
744 pub fn with_daemon_origin(mut self) -> Self {
745 self.0 |= FLAG_DAEMON_ORIGIN;
746 self
747 }
748
749 /// Return these flags with daemon origin cleared.
750 pub fn without_daemon_origin(self) -> Self {
751 Self(self.0 & !FLAG_DAEMON_ORIGIN)
752 }
753}
754
755/// A decoded envelope header. The body is the `len` bytes that follow it.
756#[derive(Debug, Clone, Copy, PartialEq, Eq)]
757pub struct EnvelopeHeader {
758 /// Number of body bytes after the header.
759 pub len: u32,
760 /// Envelope version.
761 pub ver: u8,
762 /// Frame kind.
763 pub ty: FrameType,
764 /// Flag bits.
765 pub flags: Flags,
766 /// Sender-local route slot; 0 is the control channel.
767 pub channel: u16,
768 /// Sender-local binding epoch; 0 is reserved for the control channel.
769 pub epoch: u32,
770 /// Correlation id.
771 pub corr: u64,
772}
773
774impl EnvelopeHeader {
775 /// Serialize the header to its fixed 21-byte little-endian form.
776 pub fn encode(&self) -> [u8; HEADER_LEN] {
777 let mut buf = [0u8; HEADER_LEN];
778 buf[0..4].copy_from_slice(&self.len.to_le_bytes());
779 buf[4] = self.ver;
780 buf[5] = self.ty as u8;
781 buf[6] = self.flags.0;
782 buf[7..9].copy_from_slice(&self.channel.to_le_bytes());
783 buf[9..13].copy_from_slice(&self.epoch.to_le_bytes());
784 buf[13..21].copy_from_slice(&self.corr.to_le_bytes());
785 buf
786 }
787}
788
789/// Why a header could not be decoded.
790#[derive(Debug, Clone, Copy, PartialEq, Eq)]
791pub enum DecodeError {
792 /// Fewer than `FROZEN_PREFIX_LEN` bytes — cannot even read `len`/`ver`.
793 TooShortForPrefix { have: usize },
794 /// `ver` is not a version this build understands.
795 UnsupportedVersion { ver: u8 },
796 /// Version known but fewer than its header length is present.
797 TooShortForHeader { have: usize, need: usize },
798 /// `type` byte is not a known `FrameType`.
799 UnknownFrameType { byte: u8 },
800 /// A reserved flag bit is set (retained for older decoder error compatibility).
801 ReservedFlagBits { flags: u8 },
802 /// Priority bits 1-2 hold the reserved value `0b11`.
803 ReservedPriorityBits { flags: u8 },
804 /// Admission bits 4-5 hold the reserved value `0b11`.
805 ReservedAdmissionClass { flags: u8 },
806 /// SHEDDABLE is set on a frame type that must be delivered.
807 SheddableIllegalFrameType { ty: FrameType, flags: u8 },
808 /// Channel 0 carried an epoch other than its reserved epoch 0.
809 NonzeroEpochOnControlChannel { epoch: u32 },
810 /// A pure-header frame declared body bytes.
811 PureHeaderFrameWithBody { ty: FrameType, len: u32 },
812}
813
814impl fmt::Display for DecodeError {
815 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
816 match self {
817 Self::TooShortForPrefix { have } => {
818 write!(f, "header shorter than frozen prefix: have {have} bytes")
819 }
820 Self::UnsupportedVersion { ver } => write!(f, "unsupported envelope version {ver}"),
821 Self::TooShortForHeader { have, need } => {
822 write!(
823 f,
824 "header too short for version: have {have} bytes, need {need}"
825 )
826 }
827 Self::UnknownFrameType { byte } => write!(f, "unknown frame type byte {byte}"),
828 Self::ReservedFlagBits { flags } => {
829 write!(f, "reserved flag bits set in flags 0b{flags:08b}")
830 }
831 Self::ReservedPriorityBits { flags } => {
832 write!(f, "reserved priority bits set in flags 0b{flags:08b}")
833 }
834 Self::ReservedAdmissionClass { flags } => {
835 write!(f, "reserved admission class set in flags 0b{flags:08b}")
836 }
837 Self::SheddableIllegalFrameType { ty, flags } => write!(
838 f,
839 "SHEDDABLE admission class is illegal on {ty:?} in flags 0b{flags:08b}"
840 ),
841 Self::NonzeroEpochOnControlChannel { epoch } => {
842 write!(f, "control channel carried nonzero epoch {epoch}")
843 }
844 Self::PureHeaderFrameWithBody { ty, len } => {
845 write!(
846 f,
847 "pure-header frame {ty:?} declared non-zero body length {len}"
848 )
849 }
850 }
851 }
852}
853
854impl Error for DecodeError {}
855
856/// How many header bytes a given envelope version occupies. Driven by the
857/// frozen prefix: read `ver`, then learn the full header length here.
858fn header_len_for_version(ver: u8) -> Option<usize> {
859 match ver {
860 PROTOCOL_VERSION => Some(HEADER_LEN),
861 _ => None,
862 }
863}
864
865/// Decode an envelope header from the front of `bytes`, following the
866/// frozen-prefix discipline:
867/// 1. need at least the 5-byte prefix to read `len` + `ver`;
868/// 2. dispatch the full header length on `ver`;
869/// 3. need the full header present; then parse the rest.
870///
871/// Never panics on malformed input — returns a typed [`DecodeError`].
872pub fn decode_header(bytes: &[u8]) -> Result<EnvelopeHeader, DecodeError> {
873 if bytes.len() < FROZEN_PREFIX_LEN {
874 return Err(DecodeError::TooShortForPrefix { have: bytes.len() });
875 }
876 let ver = bytes[4];
877 let need = header_len_for_version(ver).ok_or(DecodeError::UnsupportedVersion { ver })?;
878 if bytes.len() < need {
879 return Err(DecodeError::TooShortForHeader {
880 have: bytes.len(),
881 need,
882 });
883 }
884
885 let len = u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);
886 let ty =
887 FrameType::from_u8(bytes[5]).ok_or(DecodeError::UnknownFrameType { byte: bytes[5] })?;
888 let flags = Flags(bytes[6]);
889 if flags.priority().is_none() {
890 return Err(DecodeError::ReservedPriorityBits { flags: bytes[6] });
891 }
892 let admission_class = flags
893 .admission_class()
894 .ok_or(DecodeError::ReservedAdmissionClass { flags: bytes[6] })?;
895 if admission_class == AdmissionClass::Sheddable
896 && !matches!(ty, FrameType::Push | FrameType::StreamData)
897 {
898 return Err(DecodeError::SheddableIllegalFrameType {
899 ty,
900 flags: bytes[6],
901 });
902 }
903 if ty.is_pure_header() && len != 0 {
904 return Err(DecodeError::PureHeaderFrameWithBody { ty, len });
905 }
906 let channel = u16::from_le_bytes([bytes[7], bytes[8]]);
907 let epoch = u32::from_le_bytes([bytes[9], bytes[10], bytes[11], bytes[12]]);
908 if channel == 0 && epoch != 0 {
909 return Err(DecodeError::NonzeroEpochOnControlChannel { epoch });
910 }
911 let corr = u64::from_le_bytes([
912 bytes[13], bytes[14], bytes[15], bytes[16], bytes[17], bytes[18], bytes[19], bytes[20],
913 ]);
914
915 Ok(EnvelopeHeader {
916 len,
917 ver,
918 ty,
919 flags,
920 channel,
921 epoch,
922 corr,
923 })
924}
925
926#[cfg(test)]
927mod tests {
928 use super::*;
929
930 fn hdr(len: u32, ty: FrameType, flags: Flags, channel: u16, corr: u64) -> EnvelopeHeader {
931 hdr_with_epoch(len, ty, flags, channel, u32::from(channel != 0), corr)
932 }
933
934 fn hdr_with_epoch(
935 len: u32,
936 ty: FrameType,
937 flags: Flags,
938 channel: u16,
939 epoch: u32,
940 corr: u64,
941 ) -> EnvelopeHeader {
942 EnvelopeHeader {
943 len,
944 ver: PROTOCOL_VERSION,
945 ty,
946 flags,
947 channel,
948 epoch,
949 corr,
950 }
951 }
952
953 /// Modules size their replies against this limit and the TypeScript and
954 /// Swift clients mirror it, so changing it must be a deliberate edit here
955 /// as well as in the constant.
956 #[test]
957 fn max_delivered_frame_len_is_four_mebibytes_including_the_header() {
958 assert_eq!(MAX_DELIVERED_FRAME_LEN, 4_194_304);
959 }
960
961 #[test]
962 fn bind_identity_with_project_id_round_trips_json() {
963 let mut identity = BindIdentity::new("/tmp/project", "opencode", "session-1");
964 identity.project_id = Some("pj-a1b2c3d4".to_string());
965
966 let encoded = serde_json::to_vec(&identity).unwrap();
967 let decoded: BindIdentity = serde_json::from_slice(&encoded).unwrap();
968
969 assert_eq!(decoded, identity);
970 }
971
972 #[test]
973 fn bind_identity_without_project_id_round_trips_json() {
974 let identity = BindIdentity::new("/tmp/project", "opencode", "session-1");
975
976 let encoded = serde_json::to_vec(&identity).unwrap();
977 let decoded: BindIdentity = serde_json::from_slice(&encoded).unwrap();
978
979 assert_eq!(decoded, identity);
980 }
981
982 #[test]
983 fn legacy_bind_identity_without_project_id_decodes() {
984 let decoded: BindIdentity = serde_json::from_value(serde_json::json!({
985 "project_root": "/tmp/project",
986 "harness": "opencode",
987 "session": "session-1"
988 }))
989 .unwrap();
990
991 assert_eq!(decoded.project_id, None);
992 }
993
994 #[test]
995 fn bind_identity_none_omits_project_id_instead_of_serializing_null() {
996 let encoded =
997 serde_json::to_value(BindIdentity::new("/tmp/project", "opencode", "session-1"))
998 .unwrap();
999
1000 assert!(encoded.get("project_id").is_none());
1001 }
1002
1003 #[test]
1004 fn wire_crate_version_is_a_numeric_three_component_version() {
1005 let components = SUBC_PROTOCOL_CRATE_VERSION.split('.').collect::<Vec<_>>();
1006
1007 assert!(!SUBC_PROTOCOL_CRATE_VERSION.is_empty());
1008 assert_eq!(components.len(), 3);
1009 assert!(components
1010 .iter()
1011 .all(|component| !component.is_empty() && component.parse::<u64>().is_ok()));
1012 }
1013
1014 #[test]
1015 fn route_target_variants_round_trip_json() {
1016 let targets = [
1017 RouteTarget::ToolProvider {
1018 module_id: "aft".to_string(),
1019 },
1020 RouteTarget::ManagementSurface {
1021 module_id: "memory".to_string(),
1022 },
1023 RouteTarget::InternalService {
1024 module_id: "bus".to_string(),
1025 service_id: "dm".to_string(),
1026 },
1027 ];
1028
1029 for target in targets {
1030 let encoded = serde_json::to_vec(&target).unwrap();
1031 let decoded: RouteTarget = serde_json::from_slice(&encoded).unwrap();
1032 assert_eq!(decoded, target);
1033 }
1034 }
1035
1036 #[test]
1037 fn error_body_round_trips_json() {
1038 let body = ErrorBody {
1039 code: "config_divergence".to_string(),
1040 message: "active config differs".to_string(),
1041 detail: None,
1042 };
1043
1044 let encoded = serde_json::to_vec(&body).unwrap();
1045 let decoded: ErrorBody = serde_json::from_slice(&encoded).unwrap();
1046
1047 assert_eq!(decoded, body);
1048 }
1049
1050 #[test]
1051 fn round_trip_request() {
1052 let h = hdr(
1053 1234,
1054 FrameType::Request,
1055 Flags::new(false, Priority::Interactive, false),
1056 42,
1057 0xDEAD_BEEF_0000_0001,
1058 );
1059 let decoded = decode_header(&h.encode()).unwrap();
1060 assert_eq!(h, decoded);
1061 }
1062
1063 #[test]
1064 fn round_trip_all_frame_types() {
1065 for b in 0u8..=11 {
1066 let ty = FrameType::from_u8(b).unwrap();
1067 let h = hdr(0, ty, Flags::new(false, Priority::Passive, false), 0, 0);
1068 assert_eq!(decode_header(&h.encode()).unwrap().ty, ty);
1069 }
1070 }
1071
1072 #[test]
1073 fn pure_header_frame_has_zero_len() {
1074 // CANCEL carries only header (len = 0) + the target corr.
1075 let h = hdr(
1076 0,
1077 FrameType::Cancel,
1078 Flags::new(false, Priority::Passive, false),
1079 7,
1080 99,
1081 );
1082 let d = decode_header(&h.encode()).unwrap();
1083 assert_eq!(d.len, 0);
1084 assert_eq!(d.corr, 99);
1085 }
1086
1087 #[test]
1088 fn flags_round_trip() {
1089 let f = Flags::new(true, Priority::Background, true)
1090 .with_admission_class(AdmissionClass::Expedite);
1091 assert!(f.is_binary());
1092 assert!(f.is_last());
1093 assert_eq!(f.priority(), Some(Priority::Background));
1094 assert_eq!(f.admission_class(), Some(AdmissionClass::Expedite));
1095 let h = hdr(8, FrameType::StreamData, f, 1, 1);
1096 assert_eq!(decode_header(&h.encode()).unwrap().flags, f);
1097 }
1098
1099 #[test]
1100 fn daemon_origin_flags_decode_and_round_trip() {
1101 let old = hdr(0, FrameType::Error, Flags(0), 7, 1);
1102 let old_decoded = decode_header(&old.encode()).unwrap();
1103 assert!(!old_decoded.flags.is_daemon_origin());
1104
1105 let daemon = hdr(0, FrameType::Error, Flags(0).with_daemon_origin(), 7, 1);
1106 let daemon_decoded = decode_header(&daemon.encode()).unwrap();
1107 assert!(daemon_decoded.flags.is_daemon_origin());
1108 assert_eq!(daemon_decoded.flags.without_daemon_origin(), Flags(0));
1109 assert!(Flags(0).with_daemon_origin().is_daemon_origin());
1110 }
1111
1112 #[test]
1113 fn little_endian_and_frozen_prefix_layout() {
1114 let h = hdr_with_epoch(
1115 0x0403_0201,
1116 FrameType::Request,
1117 Flags(0),
1118 0x0605,
1119 0x0a09_0807,
1120 0x1211_100f_0e0d_0c0b,
1121 );
1122 let buf = h.encode();
1123 assert_eq!(&buf[0..4], &[1, 2, 3, 4]);
1124 assert_eq!(buf[4], PROTOCOL_VERSION);
1125 assert_eq!(&buf[7..9], &[5, 6]);
1126 assert_eq!(&buf[9..13], &[7, 8, 9, 10]);
1127 assert_eq!(&buf[13..21], &[11, 12, 13, 14, 15, 16, 17, 18]);
1128 assert_eq!(buf.len(), HEADER_LEN);
1129 }
1130
1131 #[test]
1132 fn reject_too_short_for_prefix() {
1133 assert_eq!(
1134 decode_header(&[0, 0, 0, 0]),
1135 Err(DecodeError::TooShortForPrefix { have: 4 })
1136 );
1137 }
1138
1139 #[test]
1140 fn reject_too_short_for_header() {
1141 // Valid 5-byte prefix but the v2 header is truncated.
1142 let mut b = [0u8; 10];
1143 b[4] = PROTOCOL_VERSION;
1144 assert_eq!(
1145 decode_header(&b),
1146 Err(DecodeError::TooShortForHeader {
1147 have: 10,
1148 need: HEADER_LEN
1149 })
1150 );
1151 }
1152
1153 #[test]
1154 fn reject_unsupported_version() {
1155 let mut b = [0u8; HEADER_LEN];
1156 b[4] = 1;
1157 assert_eq!(
1158 decode_header(&b),
1159 Err(DecodeError::UnsupportedVersion { ver: 1 })
1160 );
1161 }
1162
1163 #[test]
1164 fn reject_unknown_frame_type() {
1165 let mut b = [0u8; HEADER_LEN];
1166 b[4] = PROTOCOL_VERSION;
1167 b[5] = 99;
1168 assert_eq!(
1169 decode_header(&b),
1170 Err(DecodeError::UnknownFrameType { byte: 99 })
1171 );
1172 }
1173
1174 #[test]
1175 fn subscription_flag_decodes_and_tags_the_request() {
1176 let mut b = [0u8; HEADER_LEN];
1177 b[4] = PROTOCOL_VERSION;
1178 b[5] = FrameType::Request as u8;
1179 b[6] = FLAG_SUBSCRIPTION;
1180 let decoded = decode_header(&b).unwrap();
1181 assert!(decoded.flags.is_subscription());
1182 }
1183
1184 #[test]
1185 fn reject_reserved_priority_bits() {
1186 let mut b = [0u8; HEADER_LEN];
1187 b[4] = PROTOCOL_VERSION;
1188 b[5] = FrameType::Request as u8;
1189 b[6] = 0b0000_0110; // priority bits 1-2 are reserved value 0b11
1190 assert_eq!(
1191 decode_header(&b),
1192 Err(DecodeError::ReservedPriorityBits { flags: 0b0000_0110 })
1193 );
1194 }
1195
1196 #[test]
1197 fn reject_pure_header_frame_with_body_len() {
1198 let h = hdr(
1199 1,
1200 FrameType::Ping,
1201 Flags::new(false, Priority::Passive, false),
1202 0,
1203 1,
1204 );
1205 assert_eq!(
1206 decode_header(&h.encode()),
1207 Err(DecodeError::PureHeaderFrameWithBody {
1208 ty: FrameType::Ping,
1209 len: 1
1210 })
1211 );
1212 }
1213
1214 #[test]
1215 fn epoch_boundaries_round_trip() {
1216 for (channel, epoch) in [(0, 0), (1, 1), (u16::MAX, u32::MAX)] {
1217 let h = hdr_with_epoch(
1218 0,
1219 FrameType::Request,
1220 Flags::new(false, Priority::Passive, false),
1221 channel,
1222 epoch,
1223 9,
1224 );
1225 assert_eq!(decode_header(&h.encode()).unwrap(), h);
1226 }
1227 }
1228
1229 #[test]
1230 fn admission_classes_accept_three_values_and_reject_reserved_value() {
1231 for (ty, admission_class) in [
1232 (FrameType::Request, AdmissionClass::Normal),
1233 (FrameType::Request, AdmissionClass::Expedite),
1234 (FrameType::Push, AdmissionClass::Sheddable),
1235 (FrameType::StreamData, AdmissionClass::Sheddable),
1236 ] {
1237 let flags = Flags::new(false, Priority::Interactive, false)
1238 .with_admission_class(admission_class);
1239 let h = hdr(0, ty, flags, 1, 2);
1240 assert_eq!(decode_header(&h.encode()).unwrap().flags, flags);
1241 }
1242
1243 let mut h = hdr(
1244 0,
1245 FrameType::Push,
1246 Flags::new(false, Priority::Passive, false),
1247 1,
1248 2,
1249 )
1250 .encode();
1251 h[6] |= 0b0011_0000;
1252 assert_eq!(
1253 decode_header(&h),
1254 Err(DecodeError::ReservedAdmissionClass { flags: h[6] })
1255 );
1256 }
1257
1258 #[test]
1259 fn sheddable_rejected_on_every_illegal_frame_type() {
1260 let flags = Flags::new(false, Priority::Passive, false)
1261 .with_admission_class(AdmissionClass::Sheddable);
1262 for ty in [
1263 FrameType::Request,
1264 FrameType::Response,
1265 FrameType::StreamEnd,
1266 FrameType::Error,
1267 FrameType::Cancel,
1268 FrameType::Ping,
1269 FrameType::Pong,
1270 FrameType::Hello,
1271 FrameType::HelloAck,
1272 FrameType::Goodbye,
1273 ] {
1274 let h = hdr(0, ty, flags, 1, 2);
1275 assert_eq!(
1276 decode_header(&h.encode()),
1277 Err(DecodeError::SheddableIllegalFrameType { ty, flags: flags.0 })
1278 );
1279 }
1280 }
1281
1282 #[test]
1283 fn nonzero_epoch_on_control_channel_is_rejected() {
1284 let h = hdr_with_epoch(
1285 0,
1286 FrameType::Request,
1287 Flags::new(false, Priority::Passive, false),
1288 0,
1289 u32::MAX,
1290 2,
1291 );
1292 assert_eq!(
1293 decode_header(&h.encode()),
1294 Err(DecodeError::NonzeroEpochOnControlChannel { epoch: u32::MAX })
1295 );
1296 }
1297}
1298
1299#[cfg(test)]
1300mod launch_nonce_redaction_tests {
1301 use super::*;
1302
1303 #[test]
1304 fn hello_body_debug_never_prints_the_nonce() {
1305 let body = ModuleHelloBody {
1306 manifest: manifest::ModuleManifest::builder("broca", "0.1.0").build(),
1307 protocol_ver: 2,
1308 control_ops: None,
1309 launch_nonce: Some("nonce-f00dfeed1234abcd".to_string()),
1310 };
1311 let printed = format!("{body:?}");
1312 assert!(printed.contains("broca"), "{printed}");
1313 assert!(
1314 !printed.contains("nonce-f00dfeed1234abcd"),
1315 "launch nonce printed: {printed}"
1316 );
1317 }
1318}