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};
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. Use these claims for
316/// attribution, never authorization; gate on the daemon-stamped [`Principal`]
317/// instead.
318///
319/// Protocol 0.34 identities carry no project fields. For project-free openers,
320/// project attribution comes from the admitted session [`scope::ScopeStamp`]'s
321/// `workdir` and optional `project_id`; without these fields there is no project
322/// attribution. During migration, daemon 0.39 also accepts legacy opener project
323/// fields and prefers the legacy root over the scope workdir for internal root
324/// attribution and compatibility bind fields. Decoding remains lenient so
325/// readers can ignore project fields sent by older daemons during migration.
326/// See [`scope::BIND_NO_PROJECT_CAPABILITY`] for target opt-in to project-free
327/// bind identities.
328#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
329#[non_exhaustive]
330pub struct BindIdentity {
331 pub harness: String,
332 pub session: String,
333 /// The opener's claim about the kind of build it is, sent on `route.open`.
334 /// [`BUILD_CLASS_PRODUCTION`] marks a production build whose integrity the
335 /// opener has verified.
336 ///
337 /// Like every other field here it is unattested. The daemon recognizes
338 /// `callosum` as the caller module ID eligible for this claim. It honours
339 /// the claim only when the opener's principal is
340 /// `Reserved { module_id: "callosum" }`, and only the exact value
341 /// [`BUILD_CLASS_PRODUCTION`]; any other value counts as absent. From any
342 /// other opener it is ignored. The daemon never relays it to the target
343 /// module: the identity on `route.bind` never carries it.
344 ///
345 /// An absent build-class claim is omitted from the wire. A reader that
346 /// predates this field drops it, which grants nothing.
347 /// Set it on the public field after [`BindIdentity::new`].
348 #[serde(default, skip_serializing_if = "Option::is_none")]
349 pub build_class: Option<String>,
350}
351
352/// The only [`BindIdentity::build_class`] value the daemon honours.
353pub const BUILD_CLASS_PRODUCTION: &str = "production";
354
355impl BindIdentity {
356 /// Constructs a project-free attribution identity.
357 ///
358 /// Use this instead of a struct literal so future additive identity fields do
359 /// not force construction-site migrations across the fleet.
360 pub fn new(harness: impl Into<String>, session: impl Into<String>) -> Self {
361 Self {
362 harness: harness.into(),
363 session: session.into(),
364 build_class: None,
365 }
366 }
367}
368
369/// Caller fact stamped by subc on each route.bind relayed to a module.
370#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
371#[serde(tag = "kind", rename_all = "snake_case")]
372pub enum Principal {
373 /// A daemon-spawned module proved possession of its launch nonce.
374 Reserved { module_id: String },
375 /// No consumer identity was presented; the caller is a direct key-holder.
376 Direct,
377 /// Reserved vocabulary for a future degraded/no-key-auth mode.
378 Unverified,
379}
380
381/// Explicit target for a route open/bind operation.
382///
383/// RouteTarget.kind ↔ ProviderRole mapping:
384///
385/// | RouteTarget.kind | required ProviderRole | disambiguator |
386/// |---|---|---|
387/// | `tool_provider` | `ToolProvider` | v1: ≤1 per module |
388/// | `management_surface` | `ManagementSurface` | v1: ≤1 per module |
389/// | `internal_service` | `InternalService` | `service_id` (multiple allowed) |
390///
391/// `ProviderRole::PipelineStage` is intentionally unroutable; pipeline modules
392/// are wired by an orchestrator rather than opened directly by clients.
393#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
394#[serde(tag = "kind", rename_all = "snake_case")]
395pub enum RouteTarget {
396 ToolProvider {
397 module_id: String,
398 },
399 ManagementSurface {
400 module_id: String,
401 },
402 InternalService {
403 module_id: String,
404 service_id: String,
405 },
406}
407
408/// Envelope protocol version this build speaks.
409pub const PROTOCOL_VERSION: u8 = 2;
410
411/// The version of THIS crate (`subc-protocol`) as compiled into the linking
412/// binary — the fleet's shared wire-vocabulary version, and the value
413/// `ManifestProvenance.wire_crate_version` declares. Not the version of a
414/// module's own envelope or payload crates: those are different numbering
415/// spaces, and declaring one here produces a confident wrong answer at any
416/// version gate (insula shipped exactly that before the referent was written
417/// down). `env!` makes it a property of the compiled binary, not of whatever
418/// source tree sits beside it at run time.
419pub const SUBC_PROTOCOL_CRATE_VERSION: &str = env!("CARGO_PKG_VERSION");
420
421/// Oldest envelope protocol version this build accepts.
422pub const MIN_SUPPORTED_VERSION: u8 = 2;
423
424/// Env var subc sets on each supervised child telling it the module_id it is
425/// supervised under, so it can register under that id.
426pub const SUBC_MODULE_ID_ENV: &str = "SUBC_MODULE_ID";
427
428/// Env var subc sets, on each spawn of a `reserved` module only, to a fresh
429/// one-time launch nonce. The child echoes it in `ModuleHelloBody::launch_nonce`;
430/// subc accepts a reserved module_id's HELLO only when the nonce matches the one it
431/// last injected for that id. Non-reserved modules never receive it.
432pub const SUBC_LAUNCH_NONCE_ENV: &str = "SUBC_LAUNCH_NONCE";
433
434/// Fixed header length for `PROTOCOL_VERSION` 2.
435pub const HEADER_LEN: usize = 21;
436
437/// Bytes of the frozen prefix (`len` u32 + `ver` u8) that are stable across
438/// every envelope version. A reader needs only these to learn the version and
439/// thus the full header length.
440pub const FROZEN_PREFIX_LEN: usize = 5;
441
442/// Maximum frame body accepted before allocation.
443///
444/// This 64 MiB starting cap prevents a malformed header from forcing an
445/// unbounded allocation. Future protocol versions can negotiate or encode a
446/// different cap while preserving the frozen prefix.
447pub const MAX_FRAME_BODY_LEN: u32 = 64 * 1024 * 1024;
448
449/// Largest frame, `HEADER_LEN` included, that the daemon delivers from a module
450/// to a client: a reply, stream frame, error, reverse request or push. A module
451/// sizes what it sends to a client against this, not against
452/// `MAX_FRAME_BODY_LEN`.
453///
454/// A larger module frame is never forwarded to the client. A reply, stream
455/// frame or error that is too large ends its request with a `frame_too_large`
456/// error; a reverse request that is too large is answered with an error to the
457/// module; an unsolicited push that is too large closes the client connection.
458///
459/// Requests from a client to a module are not held to this limit; they are
460/// bounded only by `MAX_FRAME_BODY_LEN`.
461pub const MAX_DELIVERED_FRAME_LEN: usize = 4 * 1024 * 1024;
462
463/// Canonical JSON body for all subc-generated `ERROR` frames.
464///
465/// `detail` is an optional machine-parsable surface for refusals whose remedy
466/// needs more than a code (e.g. a producer-published backoff number, an
467/// observed-vs-configured size pair). Absent detail serializes to nothing, so
468/// bodies without it are byte-identical to the pre-detail wire and older
469/// readers simply never see the field. Producers document each code's detail
470/// fields where the code is defined; `detail` must never carry secrets.
471#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
472pub struct ErrorBody {
473 pub code: String,
474 pub message: String,
475 #[serde(default, skip_serializing_if = "Option::is_none")]
476 pub detail: Option<serde_json::Value>,
477}
478
479impl ErrorBody {
480 /// A detail-less error body; the common case.
481 pub fn new(code: impl Into<String>, message: impl Into<String>) -> Self {
482 Self {
483 code: code.into(),
484 message: message.into(),
485 detail: None,
486 }
487 }
488
489 /// Attach a machine-parsable detail object to this error.
490 pub fn with_detail(mut self, detail: serde_json::Value) -> Self {
491 self.detail = Some(detail);
492 self
493 }
494}
495
496/// Module-to-subc `HELLO` body used during module registration.
497#[derive(Clone, Serialize, Deserialize, PartialEq)]
498pub struct ModuleHelloBody {
499 pub manifest: manifest::ModuleManifest,
500 pub protocol_ver: u8,
501 #[serde(default)]
502 pub control_ops: Option<Vec<String>>,
503 /// One-time launch nonce, echoed back from the `SUBC_LAUNCH_NONCE` environment
504 /// variable the daemon injected when it spawned this process. Only a daemon-spawned
505 /// process for a `reserved` module receives a nonce; subc accepts a reserved
506 /// `module_id`'s HELLO only when this matches the nonce it last injected for that
507 /// id, so a different process cannot register as a reserved module while the real
508 /// one is down/restarting. Absent (`serde(default)`) for non-reserved modules and
509 /// self-connecting providers, which are never nonce-checked.
510 #[serde(default, skip_serializing_if = "Option::is_none")]
511 pub launch_nonce: Option<String>,
512}
513
514// Hand-written so the launch nonce is never printed. The nonce is the credential
515// that attributes a connection to a supervised module, and a derived Debug would
516// write it into any log line or panic message that formats this value. Same
517// reasoning as ConnectionInfo's Debug in subc-transport.
518impl fmt::Debug for ModuleHelloBody {
519 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
520 f.debug_struct("ModuleHelloBody")
521 .field("manifest", &self.manifest)
522 .field("protocol_ver", &self.protocol_ver)
523 .field("control_ops", &self.control_ops)
524 .field(
525 "launch_nonce",
526 &self
527 .launch_nonce
528 .as_ref()
529 .map(|nonce| format!("<{} bytes redacted>", nonce.len())),
530 )
531 .finish()
532 }
533}
534
535/// subc-to-module `HELLO_ACK` body used during module registration.
536#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
537pub struct ModuleHelloAckBody {
538 pub negotiated_ver: u8,
539 pub subc_ops: Vec<String>,
540 pub subc_capabilities: Vec<String>,
541 /// The module's resolved storage descriptor, when the daemon's central config
542 /// configures managed storage. Carried opaquely here (subc-protocol stays a
543 /// thin wire crate with no storage/database dependency); a module that uses
544 /// managed storage deserializes it into `cortexkit_store_types::StorageDescriptor`
545 /// and hands it to `cortexkit-store`. Absent when no storage is configured, and
546 /// `serde(default)` so an older module simply ignores it.
547 #[serde(default, skip_serializing_if = "Option::is_none")]
548 pub storage: Option<serde_json::Value>,
549 /// The daemon's machine id (see [`MachineId`]): a name for this machine,
550 /// never an authority. Nothing may admit a peer, grant trust or skip a check
551 /// because two messages carry the same value.
552 ///
553 /// Carried as a plain string so one malformed value cannot fail the whole
554 /// registration reply; a module validates it with [`MachineId::parse`].
555 /// Absent from a daemon that predates the machine id, which a module must
556 /// read as exactly that, never as "no machine" and never as a reason to mint
557 /// its own.
558 #[serde(default, skip_serializing_if = "Option::is_none")]
559 pub machine_id: Option<String>,
560}
561
562/// Frame kind (`type` byte at offset 5).
563///
564/// `CANCEL`, `PING`, `PONG`, and `GOODBYE` are pure-header frames (`len == 0`);
565/// only `HELLO`/`HELLO_ACK` and the RPC payloads carry bodies.
566#[derive(Debug, Clone, Copy, PartialEq, Eq)]
567#[repr(u8)]
568pub enum FrameType {
569 Request = 0,
570 Response = 1,
571 Push = 2,
572 StreamData = 3,
573 StreamEnd = 4,
574 Error = 5,
575 Cancel = 6,
576 Ping = 7,
577 Pong = 8,
578 Hello = 9,
579 HelloAck = 10,
580 Goodbye = 11,
581}
582
583impl FrameType {
584 /// Map the raw `type` byte to a `FrameType`, or `None` if unknown.
585 pub fn from_u8(b: u8) -> Option<Self> {
586 Some(match b {
587 0 => Self::Request,
588 1 => Self::Response,
589 2 => Self::Push,
590 3 => Self::StreamData,
591 4 => Self::StreamEnd,
592 5 => Self::Error,
593 6 => Self::Cancel,
594 7 => Self::Ping,
595 8 => Self::Pong,
596 9 => Self::Hello,
597 10 => Self::HelloAck,
598 11 => Self::Goodbye,
599 _ => return None,
600 })
601 }
602
603 pub fn is_pure_header(self) -> bool {
604 matches!(self, Self::Cancel | Self::Ping | Self::Pong | Self::Goodbye)
605 }
606}
607
608/// Scheduling priority carried in `flags` bits 1-2. subc schedules on this
609/// without parsing the body.
610#[derive(Debug, Clone, Copy, PartialEq, Eq)]
611#[repr(u8)]
612pub enum Priority {
613 Passive = 0,
614 Interactive = 1,
615 Background = 2,
616}
617
618impl Priority {
619 fn from_bits(bits: u8) -> Option<Self> {
620 Some(match bits {
621 0 => Self::Passive,
622 1 => Self::Interactive,
623 2 => Self::Background,
624 _ => return None,
625 })
626 }
627}
628
629/// Admission behavior carried in `flags` bits 4-5.
630#[derive(Debug, Clone, Copy, PartialEq, Eq)]
631#[repr(u8)]
632pub enum AdmissionClass {
633 Normal = 0,
634 Expedite = 1,
635 Sheddable = 2,
636}
637
638impl AdmissionClass {
639 fn from_bits(bits: u8) -> Option<Self> {
640 Some(match bits {
641 0 => Self::Normal,
642 1 => Self::Expedite,
643 2 => Self::Sheddable,
644 _ => return None,
645 })
646 }
647}
648
649const FLAG_BINARY: u8 = 0b0000_0001; // bit 0
650const FLAG_PRIORITY_MASK: u8 = 0b0000_0110; // bits 1-2
651const FLAG_PRIORITY_SHIFT: u8 = 1;
652const FLAG_LAST: u8 = 0b0000_1000; // bit 3
653const FLAG_ADMISSION_MASK: u8 = 0b0011_0000; // bits 4-5
654const FLAG_ADMISSION_SHIFT: u8 = 4;
655pub const FLAG_DAEMON_ORIGIN: u8 = 0b0100_0000;
656/// A request credit the client explicitly declares as a held-open subscription.
657pub const FLAG_SUBSCRIPTION: u8 = 0b1000_0000;
658
659/// The `flags` byte (offset 6): binary, priority, last, admission, daemon origin, subscription.
660#[derive(Debug, Clone, Copy, PartialEq, Eq)]
661pub struct Flags(pub u8);
662
663impl Flags {
664 /// Build flags with the default [`AdmissionClass::Normal`] class.
665 pub fn new(binary: bool, priority: Priority, last: bool) -> Self {
666 let mut b = 0u8;
667 if binary {
668 b |= FLAG_BINARY;
669 }
670 b |= (priority as u8) << FLAG_PRIORITY_SHIFT;
671 if last {
672 b |= FLAG_LAST;
673 }
674 Flags(b)
675 }
676
677 /// Return these flags with a typed admission class.
678 pub fn with_admission_class(mut self, admission_class: AdmissionClass) -> Self {
679 self.0 =
680 (self.0 & !FLAG_ADMISSION_MASK) | ((admission_class as u8) << FLAG_ADMISSION_SHIFT);
681 self
682 }
683
684 /// Body is raw bytes (bulk lane) rather than JSON-RPC.
685 pub fn is_binary(self) -> bool {
686 self.0 & FLAG_BINARY != 0
687 }
688
689 /// Final frame of a streamed message.
690 pub fn is_last(self) -> bool {
691 self.0 & FLAG_LAST != 0
692 }
693
694 /// Decode the priority bits, or `None` if they hold a reserved value.
695 pub fn priority(self) -> Option<Priority> {
696 Priority::from_bits((self.0 & FLAG_PRIORITY_MASK) >> FLAG_PRIORITY_SHIFT)
697 }
698
699 /// Decode the admission-class bits, or `None` if they hold `0b11`.
700 pub fn admission_class(self) -> Option<AdmissionClass> {
701 AdmissionClass::from_bits((self.0 & FLAG_ADMISSION_MASK) >> FLAG_ADMISSION_SHIFT)
702 }
703
704 /// True when a request was explicitly opened as a held-open subscription.
705 pub fn is_subscription(self) -> bool {
706 self.0 & FLAG_SUBSCRIPTION != 0
707 }
708
709 /// True when the frame was authored by the daemon.
710 pub fn is_daemon_origin(self) -> bool {
711 self.0 & FLAG_DAEMON_ORIGIN != 0
712 }
713
714 /// Return these flags with daemon origin asserted.
715 pub fn with_daemon_origin(mut self) -> Self {
716 self.0 |= FLAG_DAEMON_ORIGIN;
717 self
718 }
719
720 /// Return these flags with daemon origin cleared.
721 pub fn without_daemon_origin(self) -> Self {
722 Self(self.0 & !FLAG_DAEMON_ORIGIN)
723 }
724}
725
726/// A decoded envelope header. The body is the `len` bytes that follow it.
727#[derive(Debug, Clone, Copy, PartialEq, Eq)]
728pub struct EnvelopeHeader {
729 /// Number of body bytes after the header.
730 pub len: u32,
731 /// Envelope version.
732 pub ver: u8,
733 /// Frame kind.
734 pub ty: FrameType,
735 /// Flag bits.
736 pub flags: Flags,
737 /// Sender-local route slot; 0 is the control channel.
738 pub channel: u16,
739 /// Sender-local binding epoch; 0 is reserved for the control channel.
740 pub epoch: u32,
741 /// Correlation id.
742 pub corr: u64,
743}
744
745impl EnvelopeHeader {
746 /// Serialize the header to its fixed 21-byte little-endian form.
747 pub fn encode(&self) -> [u8; HEADER_LEN] {
748 let mut buf = [0u8; HEADER_LEN];
749 buf[0..4].copy_from_slice(&self.len.to_le_bytes());
750 buf[4] = self.ver;
751 buf[5] = self.ty as u8;
752 buf[6] = self.flags.0;
753 buf[7..9].copy_from_slice(&self.channel.to_le_bytes());
754 buf[9..13].copy_from_slice(&self.epoch.to_le_bytes());
755 buf[13..21].copy_from_slice(&self.corr.to_le_bytes());
756 buf
757 }
758}
759
760/// Why a header could not be decoded.
761#[derive(Debug, Clone, Copy, PartialEq, Eq)]
762pub enum DecodeError {
763 /// Fewer than `FROZEN_PREFIX_LEN` bytes — cannot even read `len`/`ver`.
764 TooShortForPrefix { have: usize },
765 /// `ver` is not a version this build understands.
766 UnsupportedVersion { ver: u8 },
767 /// Version known but fewer than its header length is present.
768 TooShortForHeader { have: usize, need: usize },
769 /// `type` byte is not a known `FrameType`.
770 UnknownFrameType { byte: u8 },
771 /// A reserved flag bit is set (retained for older decoder error compatibility).
772 ReservedFlagBits { flags: u8 },
773 /// Priority bits 1-2 hold the reserved value `0b11`.
774 ReservedPriorityBits { flags: u8 },
775 /// Admission bits 4-5 hold the reserved value `0b11`.
776 ReservedAdmissionClass { flags: u8 },
777 /// SHEDDABLE is set on a frame type that must be delivered.
778 SheddableIllegalFrameType { ty: FrameType, flags: u8 },
779 /// Channel 0 carried an epoch other than its reserved epoch 0.
780 NonzeroEpochOnControlChannel { epoch: u32 },
781 /// A pure-header frame declared body bytes.
782 PureHeaderFrameWithBody { ty: FrameType, len: u32 },
783}
784
785impl fmt::Display for DecodeError {
786 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
787 match self {
788 Self::TooShortForPrefix { have } => {
789 write!(f, "header shorter than frozen prefix: have {have} bytes")
790 }
791 Self::UnsupportedVersion { ver } => write!(f, "unsupported envelope version {ver}"),
792 Self::TooShortForHeader { have, need } => {
793 write!(
794 f,
795 "header too short for version: have {have} bytes, need {need}"
796 )
797 }
798 Self::UnknownFrameType { byte } => write!(f, "unknown frame type byte {byte}"),
799 Self::ReservedFlagBits { flags } => {
800 write!(f, "reserved flag bits set in flags 0b{flags:08b}")
801 }
802 Self::ReservedPriorityBits { flags } => {
803 write!(f, "reserved priority bits set in flags 0b{flags:08b}")
804 }
805 Self::ReservedAdmissionClass { flags } => {
806 write!(f, "reserved admission class set in flags 0b{flags:08b}")
807 }
808 Self::SheddableIllegalFrameType { ty, flags } => write!(
809 f,
810 "SHEDDABLE admission class is illegal on {ty:?} in flags 0b{flags:08b}"
811 ),
812 Self::NonzeroEpochOnControlChannel { epoch } => {
813 write!(f, "control channel carried nonzero epoch {epoch}")
814 }
815 Self::PureHeaderFrameWithBody { ty, len } => {
816 write!(
817 f,
818 "pure-header frame {ty:?} declared non-zero body length {len}"
819 )
820 }
821 }
822 }
823}
824
825impl Error for DecodeError {}
826
827/// How many header bytes a given envelope version occupies. Driven by the
828/// frozen prefix: read `ver`, then learn the full header length here.
829fn header_len_for_version(ver: u8) -> Option<usize> {
830 match ver {
831 PROTOCOL_VERSION => Some(HEADER_LEN),
832 _ => None,
833 }
834}
835
836/// Decode an envelope header from the front of `bytes`, following the
837/// frozen-prefix discipline:
838/// 1. need at least the 5-byte prefix to read `len` + `ver`;
839/// 2. dispatch the full header length on `ver`;
840/// 3. need the full header present; then parse the rest.
841///
842/// Never panics on malformed input — returns a typed [`DecodeError`].
843pub fn decode_header(bytes: &[u8]) -> Result<EnvelopeHeader, DecodeError> {
844 if bytes.len() < FROZEN_PREFIX_LEN {
845 return Err(DecodeError::TooShortForPrefix { have: bytes.len() });
846 }
847 let ver = bytes[4];
848 let need = header_len_for_version(ver).ok_or(DecodeError::UnsupportedVersion { ver })?;
849 if bytes.len() < need {
850 return Err(DecodeError::TooShortForHeader {
851 have: bytes.len(),
852 need,
853 });
854 }
855
856 let len = u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);
857 let ty =
858 FrameType::from_u8(bytes[5]).ok_or(DecodeError::UnknownFrameType { byte: bytes[5] })?;
859 let flags = Flags(bytes[6]);
860 if flags.priority().is_none() {
861 return Err(DecodeError::ReservedPriorityBits { flags: bytes[6] });
862 }
863 let admission_class = flags
864 .admission_class()
865 .ok_or(DecodeError::ReservedAdmissionClass { flags: bytes[6] })?;
866 if admission_class == AdmissionClass::Sheddable
867 && !matches!(ty, FrameType::Push | FrameType::StreamData)
868 {
869 return Err(DecodeError::SheddableIllegalFrameType {
870 ty,
871 flags: bytes[6],
872 });
873 }
874 if ty.is_pure_header() && len != 0 {
875 return Err(DecodeError::PureHeaderFrameWithBody { ty, len });
876 }
877 let channel = u16::from_le_bytes([bytes[7], bytes[8]]);
878 let epoch = u32::from_le_bytes([bytes[9], bytes[10], bytes[11], bytes[12]]);
879 if channel == 0 && epoch != 0 {
880 return Err(DecodeError::NonzeroEpochOnControlChannel { epoch });
881 }
882 let corr = u64::from_le_bytes([
883 bytes[13], bytes[14], bytes[15], bytes[16], bytes[17], bytes[18], bytes[19], bytes[20],
884 ]);
885
886 Ok(EnvelopeHeader {
887 len,
888 ver,
889 ty,
890 flags,
891 channel,
892 epoch,
893 corr,
894 })
895}
896
897#[cfg(test)]
898mod tests {
899 use super::*;
900
901 fn hdr(len: u32, ty: FrameType, flags: Flags, channel: u16, corr: u64) -> EnvelopeHeader {
902 hdr_with_epoch(len, ty, flags, channel, u32::from(channel != 0), corr)
903 }
904
905 fn hdr_with_epoch(
906 len: u32,
907 ty: FrameType,
908 flags: Flags,
909 channel: u16,
910 epoch: u32,
911 corr: u64,
912 ) -> EnvelopeHeader {
913 EnvelopeHeader {
914 len,
915 ver: PROTOCOL_VERSION,
916 ty,
917 flags,
918 channel,
919 epoch,
920 corr,
921 }
922 }
923
924 /// Modules size their replies against this limit and the TypeScript and
925 /// Swift clients mirror it, so changing it must be a deliberate edit here
926 /// as well as in the constant.
927 #[test]
928 fn max_delivered_frame_len_is_four_mebibytes_including_the_header() {
929 assert_eq!(MAX_DELIVERED_FRAME_LEN, 4_194_304);
930 }
931
932 #[test]
933 fn bind_identity_round_trips_json() {
934 let identity = BindIdentity::new("opencode", "session-1");
935
936 let encoded = serde_json::to_vec(&identity).unwrap();
937 let decoded: BindIdentity = serde_json::from_slice(&encoded).unwrap();
938
939 assert_eq!(decoded, identity);
940 }
941
942 #[test]
943 fn legacy_bind_identity_project_fields_are_ignored() {
944 let decoded: BindIdentity = serde_json::from_value(serde_json::json!({
945 "project_root": "/tmp/project",
946 "project_id": "pj-a1b2c3d4",
947 "harness": "opencode",
948 "session": "session-1"
949 }))
950 .unwrap();
951
952 assert_eq!(decoded, BindIdentity::new("opencode", "session-1"));
953 }
954
955 #[test]
956 fn bind_identity_omits_both_project_fields() {
957 let encoded = serde_json::to_value(BindIdentity::new("opencode", "session-1")).unwrap();
958
959 assert!(encoded.get("project_id").is_none());
960 assert!(encoded.get("project_root").is_none());
961 }
962
963 #[test]
964 fn wire_crate_version_is_a_numeric_three_component_version() {
965 let components = SUBC_PROTOCOL_CRATE_VERSION.split('.').collect::<Vec<_>>();
966
967 assert!(!SUBC_PROTOCOL_CRATE_VERSION.is_empty());
968 assert_eq!(components.len(), 3);
969 assert!(components
970 .iter()
971 .all(|component| !component.is_empty() && component.parse::<u64>().is_ok()));
972 }
973
974 #[test]
975 fn route_target_variants_round_trip_json() {
976 let targets = [
977 RouteTarget::ToolProvider {
978 module_id: "aft".to_string(),
979 },
980 RouteTarget::ManagementSurface {
981 module_id: "memory".to_string(),
982 },
983 RouteTarget::InternalService {
984 module_id: "bus".to_string(),
985 service_id: "dm".to_string(),
986 },
987 ];
988
989 for target in targets {
990 let encoded = serde_json::to_vec(&target).unwrap();
991 let decoded: RouteTarget = serde_json::from_slice(&encoded).unwrap();
992 assert_eq!(decoded, target);
993 }
994 }
995
996 #[test]
997 fn error_body_round_trips_json() {
998 let body = ErrorBody {
999 code: "config_divergence".to_string(),
1000 message: "active config differs".to_string(),
1001 detail: None,
1002 };
1003
1004 let encoded = serde_json::to_vec(&body).unwrap();
1005 let decoded: ErrorBody = serde_json::from_slice(&encoded).unwrap();
1006
1007 assert_eq!(decoded, body);
1008 }
1009
1010 #[test]
1011 fn round_trip_request() {
1012 let h = hdr(
1013 1234,
1014 FrameType::Request,
1015 Flags::new(false, Priority::Interactive, false),
1016 42,
1017 0xDEAD_BEEF_0000_0001,
1018 );
1019 let decoded = decode_header(&h.encode()).unwrap();
1020 assert_eq!(h, decoded);
1021 }
1022
1023 #[test]
1024 fn round_trip_all_frame_types() {
1025 for b in 0u8..=11 {
1026 let ty = FrameType::from_u8(b).unwrap();
1027 let h = hdr(0, ty, Flags::new(false, Priority::Passive, false), 0, 0);
1028 assert_eq!(decode_header(&h.encode()).unwrap().ty, ty);
1029 }
1030 }
1031
1032 #[test]
1033 fn pure_header_frame_has_zero_len() {
1034 // CANCEL carries only header (len = 0) + the target corr.
1035 let h = hdr(
1036 0,
1037 FrameType::Cancel,
1038 Flags::new(false, Priority::Passive, false),
1039 7,
1040 99,
1041 );
1042 let d = decode_header(&h.encode()).unwrap();
1043 assert_eq!(d.len, 0);
1044 assert_eq!(d.corr, 99);
1045 }
1046
1047 #[test]
1048 fn flags_round_trip() {
1049 let f = Flags::new(true, Priority::Background, true)
1050 .with_admission_class(AdmissionClass::Expedite);
1051 assert!(f.is_binary());
1052 assert!(f.is_last());
1053 assert_eq!(f.priority(), Some(Priority::Background));
1054 assert_eq!(f.admission_class(), Some(AdmissionClass::Expedite));
1055 let h = hdr(8, FrameType::StreamData, f, 1, 1);
1056 assert_eq!(decode_header(&h.encode()).unwrap().flags, f);
1057 }
1058
1059 #[test]
1060 fn daemon_origin_flags_decode_and_round_trip() {
1061 let old = hdr(0, FrameType::Error, Flags(0), 7, 1);
1062 let old_decoded = decode_header(&old.encode()).unwrap();
1063 assert!(!old_decoded.flags.is_daemon_origin());
1064
1065 let daemon = hdr(0, FrameType::Error, Flags(0).with_daemon_origin(), 7, 1);
1066 let daemon_decoded = decode_header(&daemon.encode()).unwrap();
1067 assert!(daemon_decoded.flags.is_daemon_origin());
1068 assert_eq!(daemon_decoded.flags.without_daemon_origin(), Flags(0));
1069 assert!(Flags(0).with_daemon_origin().is_daemon_origin());
1070 }
1071
1072 #[test]
1073 fn little_endian_and_frozen_prefix_layout() {
1074 let h = hdr_with_epoch(
1075 0x0403_0201,
1076 FrameType::Request,
1077 Flags(0),
1078 0x0605,
1079 0x0a09_0807,
1080 0x1211_100f_0e0d_0c0b,
1081 );
1082 let buf = h.encode();
1083 assert_eq!(&buf[0..4], &[1, 2, 3, 4]);
1084 assert_eq!(buf[4], PROTOCOL_VERSION);
1085 assert_eq!(&buf[7..9], &[5, 6]);
1086 assert_eq!(&buf[9..13], &[7, 8, 9, 10]);
1087 assert_eq!(&buf[13..21], &[11, 12, 13, 14, 15, 16, 17, 18]);
1088 assert_eq!(buf.len(), HEADER_LEN);
1089 }
1090
1091 #[test]
1092 fn reject_too_short_for_prefix() {
1093 assert_eq!(
1094 decode_header(&[0, 0, 0, 0]),
1095 Err(DecodeError::TooShortForPrefix { have: 4 })
1096 );
1097 }
1098
1099 #[test]
1100 fn reject_too_short_for_header() {
1101 // Valid 5-byte prefix but the v2 header is truncated.
1102 let mut b = [0u8; 10];
1103 b[4] = PROTOCOL_VERSION;
1104 assert_eq!(
1105 decode_header(&b),
1106 Err(DecodeError::TooShortForHeader {
1107 have: 10,
1108 need: HEADER_LEN
1109 })
1110 );
1111 }
1112
1113 #[test]
1114 fn reject_unsupported_version() {
1115 let mut b = [0u8; HEADER_LEN];
1116 b[4] = 1;
1117 assert_eq!(
1118 decode_header(&b),
1119 Err(DecodeError::UnsupportedVersion { ver: 1 })
1120 );
1121 }
1122
1123 #[test]
1124 fn reject_unknown_frame_type() {
1125 let mut b = [0u8; HEADER_LEN];
1126 b[4] = PROTOCOL_VERSION;
1127 b[5] = 99;
1128 assert_eq!(
1129 decode_header(&b),
1130 Err(DecodeError::UnknownFrameType { byte: 99 })
1131 );
1132 }
1133
1134 #[test]
1135 fn subscription_flag_decodes_and_tags_the_request() {
1136 let mut b = [0u8; HEADER_LEN];
1137 b[4] = PROTOCOL_VERSION;
1138 b[5] = FrameType::Request as u8;
1139 b[6] = FLAG_SUBSCRIPTION;
1140 let decoded = decode_header(&b).unwrap();
1141 assert!(decoded.flags.is_subscription());
1142 }
1143
1144 #[test]
1145 fn reject_reserved_priority_bits() {
1146 let mut b = [0u8; HEADER_LEN];
1147 b[4] = PROTOCOL_VERSION;
1148 b[5] = FrameType::Request as u8;
1149 b[6] = 0b0000_0110; // priority bits 1-2 are reserved value 0b11
1150 assert_eq!(
1151 decode_header(&b),
1152 Err(DecodeError::ReservedPriorityBits { flags: 0b0000_0110 })
1153 );
1154 }
1155
1156 #[test]
1157 fn reject_pure_header_frame_with_body_len() {
1158 let h = hdr(
1159 1,
1160 FrameType::Ping,
1161 Flags::new(false, Priority::Passive, false),
1162 0,
1163 1,
1164 );
1165 assert_eq!(
1166 decode_header(&h.encode()),
1167 Err(DecodeError::PureHeaderFrameWithBody {
1168 ty: FrameType::Ping,
1169 len: 1
1170 })
1171 );
1172 }
1173
1174 #[test]
1175 fn epoch_boundaries_round_trip() {
1176 for (channel, epoch) in [(0, 0), (1, 1), (u16::MAX, u32::MAX)] {
1177 let h = hdr_with_epoch(
1178 0,
1179 FrameType::Request,
1180 Flags::new(false, Priority::Passive, false),
1181 channel,
1182 epoch,
1183 9,
1184 );
1185 assert_eq!(decode_header(&h.encode()).unwrap(), h);
1186 }
1187 }
1188
1189 #[test]
1190 fn admission_classes_accept_three_values_and_reject_reserved_value() {
1191 for (ty, admission_class) in [
1192 (FrameType::Request, AdmissionClass::Normal),
1193 (FrameType::Request, AdmissionClass::Expedite),
1194 (FrameType::Push, AdmissionClass::Sheddable),
1195 (FrameType::StreamData, AdmissionClass::Sheddable),
1196 ] {
1197 let flags = Flags::new(false, Priority::Interactive, false)
1198 .with_admission_class(admission_class);
1199 let h = hdr(0, ty, flags, 1, 2);
1200 assert_eq!(decode_header(&h.encode()).unwrap().flags, flags);
1201 }
1202
1203 let mut h = hdr(
1204 0,
1205 FrameType::Push,
1206 Flags::new(false, Priority::Passive, false),
1207 1,
1208 2,
1209 )
1210 .encode();
1211 h[6] |= 0b0011_0000;
1212 assert_eq!(
1213 decode_header(&h),
1214 Err(DecodeError::ReservedAdmissionClass { flags: h[6] })
1215 );
1216 }
1217
1218 #[test]
1219 fn sheddable_rejected_on_every_illegal_frame_type() {
1220 let flags = Flags::new(false, Priority::Passive, false)
1221 .with_admission_class(AdmissionClass::Sheddable);
1222 for ty in [
1223 FrameType::Request,
1224 FrameType::Response,
1225 FrameType::StreamEnd,
1226 FrameType::Error,
1227 FrameType::Cancel,
1228 FrameType::Ping,
1229 FrameType::Pong,
1230 FrameType::Hello,
1231 FrameType::HelloAck,
1232 FrameType::Goodbye,
1233 ] {
1234 let h = hdr(0, ty, flags, 1, 2);
1235 assert_eq!(
1236 decode_header(&h.encode()),
1237 Err(DecodeError::SheddableIllegalFrameType { ty, flags: flags.0 })
1238 );
1239 }
1240 }
1241
1242 #[test]
1243 fn nonzero_epoch_on_control_channel_is_rejected() {
1244 let h = hdr_with_epoch(
1245 0,
1246 FrameType::Request,
1247 Flags::new(false, Priority::Passive, false),
1248 0,
1249 u32::MAX,
1250 2,
1251 );
1252 assert_eq!(
1253 decode_header(&h.encode()),
1254 Err(DecodeError::NonzeroEpochOnControlChannel { epoch: u32::MAX })
1255 );
1256 }
1257}
1258
1259#[cfg(test)]
1260mod launch_nonce_redaction_tests {
1261 use super::*;
1262
1263 #[test]
1264 fn hello_body_debug_never_prints_the_nonce() {
1265 let body = ModuleHelloBody {
1266 manifest: manifest::ModuleManifest::builder("broca", "0.1.0").build(),
1267 protocol_ver: 2,
1268 control_ops: None,
1269 launch_nonce: Some("nonce-f00dfeed1234abcd".to_string()),
1270 };
1271 let printed = format!("{body:?}");
1272 assert!(printed.contains("broca"), "{printed}");
1273 assert!(
1274 !printed.contains("nonce-f00dfeed1234abcd"),
1275 "launch nonce printed: {printed}"
1276 );
1277 }
1278}