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