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