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