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