mlua_swarm/types.rs
1//! Fundamental types: Role / Verb / RoleVerbGate / CapToken / IDs.
2
3use hmac::{Hmac, Mac};
4use serde::{Deserialize, Serialize};
5use sha2::Sha256;
6use std::collections::{HashMap, HashSet};
7use std::time::{Duration, SystemTime, UNIX_EPOCH};
8
9// ─── ID newtypes ───────────────────────────────────────────────────────────
10
11/// Error returned when an ID string does not carry the expected prefix.
12///
13/// Produced by the fallible constructors on the ID newtypes
14/// ([`StepId::parse`], [`TaskId::parse`], ...) and by their serde
15/// `Deserialize` impls (which route through `TryFrom<String>`), so a
16/// misrouted or malformed id fails at the boundary instead of deep inside
17/// a store lookup.
18#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
19#[error("invalid {kind} id `{got}`: expected `{expected}` prefix")]
20pub struct IdParseError {
21 /// Human-readable ID kind (`"step"`, `"task"`, ...).
22 pub kind: &'static str,
23 /// The prefix this ID kind requires, e.g. `ST-`.
24 pub expected: &'static str,
25 /// The rejected input.
26 pub got: String,
27}
28
29/// Defines a prefix-validated ID newtype.
30///
31/// The generated type keeps its inner `String` **private**: the only ways
32/// to obtain a value are `new()` (mint) and `parse()` / `TryFrom<String>` /
33/// `FromStr` (validated) — which is what makes the prefix check impossible
34/// to bypass at call sites. Serde deserialization routes through
35/// `TryFrom<String>` (`#[serde(try_from = "String")]`), and serialization
36/// stays the plain inner string, so the wire format is byte-for-byte
37/// unchanged from the `pub String` era.
38macro_rules! id_newtype {
39 ($(#[$meta:meta])* $name:ident, $prefix:literal, $kind:literal) => {
40 $(#[$meta])*
41 #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
42 #[serde(try_from = "String")]
43 pub struct $name(String);
44
45 impl $name {
46 /// The prefix this ID kind carries on the wire.
47 pub const PREFIX: &'static str = $prefix;
48
49 /// Mint a fresh id with the kind prefix and a process-unique
50 /// nonce (see [`uid_hex`]).
51 pub fn new() -> Self {
52 Self(format!(concat!($prefix, "{}"), uid_hex(8)))
53 }
54
55 /// Parse an externally-supplied string, rejecting values that
56 /// do not start with the kind prefix or carry nothing after it.
57 pub fn parse(s: impl Into<String>) -> Result<Self, IdParseError> {
58 let s = s.into();
59 if s.len() > $prefix.len() && s.starts_with($prefix) {
60 Ok(Self(s))
61 } else {
62 Err(IdParseError {
63 kind: $kind,
64 expected: $prefix,
65 got: s,
66 })
67 }
68 }
69
70 /// View the id as a string slice.
71 pub fn as_str(&self) -> &str {
72 &self.0
73 }
74
75 /// Consume the id and return the inner string.
76 pub fn into_string(self) -> String {
77 self.0
78 }
79 }
80
81 impl Default for $name {
82 fn default() -> Self {
83 Self::new()
84 }
85 }
86
87 impl std::fmt::Display for $name {
88 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
89 f.write_str(&self.0)
90 }
91 }
92
93 impl TryFrom<String> for $name {
94 type Error = IdParseError;
95 fn try_from(s: String) -> Result<Self, IdParseError> {
96 Self::parse(s)
97 }
98 }
99
100 impl std::str::FromStr for $name {
101 type Err = IdParseError;
102 fn from_str(s: &str) -> Result<Self, IdParseError> {
103 Self::parse(s)
104 }
105 }
106
107 impl AsRef<str> for $name {
108 fn as_ref(&self) -> &str {
109 &self.0
110 }
111 }
112
113 impl From<$name> for String {
114 fn from(id: $name) -> String {
115 id.0
116 }
117 }
118 };
119}
120
121id_newtype!(
122 /// Opaque per-step identifier, e.g. `ST-<hex>`. Newtype over `String` so
123 /// step, session, and worker ids can't be swapped by accident at call
124 /// sites.
125 ///
126 /// One `StepId` is minted per dispatched Blueprint step (the engine's
127 /// dispatcher "spins up a fresh task per `Step.ref`"). It is scoped to a
128 /// single step execution — the whole-kick identity is [`RunId`], and the
129 /// work-item identity is [`TaskId`].
130 ///
131 /// Renamed from `TaskId` (`T-` prefix) in the issue #13 ID-hierarchy
132 /// reconciliation: Blueprint → Task → Run → Step → Attempt.
133 StepId, "ST-", "step"
134);
135
136id_newtype!(
137 /// Opaque work-item identifier, e.g. `T-<hex>`. One `TaskId` names one
138 /// unit of work ("resolve issue #10" + a Blueprint ref + input ctx),
139 /// persisted in the task store. A task can be kicked N times; each kick
140 /// is a [`RunId`].
141 ///
142 /// Not to be confused with [`StepId`] (the per-step id that carried the
143 /// `TaskId` name before issue #13).
144 TaskId, "T-", "task"
145);
146
147id_newtype!(
148 /// Opaque run identifier, e.g. `R-<hex>`. One `RunId` names one kick of a
149 /// [`TaskId`] — minted server-side when a task is started, propagated
150 /// through the engine ctx to every wire frame so steps, workers, and
151 /// outputs correlate back to the run.
152 ///
153 /// The `R-` prefix is reserved for run ids; the engine's resume keys
154 /// moved to `RK-` in issue #14 so the two can't shadow each other under
155 /// prefix validation.
156 RunId, "R-", "run"
157);
158
159id_newtype!(
160 /// Opaque session identifier, e.g. `S-<hex>`. See [`StepId`] for the
161 /// newtype rationale.
162 ///
163 /// This is the one session-id shape across the system (issue #11): the
164 /// engine mints it for attached operator sessions, and the server's
165 /// `POST /v1/operators` login path mints the WS operator `sid` in the
166 /// same shape (the old `op-<uuid>` sid form is retired). A `SessionId`
167 /// is an identifier, not a credential — bearer secrets use `secure_hex`
168 /// tokens.
169 SessionId, "S-", "session"
170);
171
172id_newtype!(
173 /// Opaque worker identifier, e.g. `W-<hex>`. See [`StepId`] for the
174 /// newtype rationale.
175 WorkerId, "W-", "worker"
176);
177
178// ─── Role × Verb ───────────────────────────────────────────────────────────
179
180/// The four participant roles in the swarm. Every [`Verb`] a caller wants to
181/// invoke must be allow-listed for its role in a [`RoleVerbGate`].
182#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
183#[serde(rename_all = "snake_case")]
184pub enum Role {
185 /// Drives task lifecycle: starts tasks, dispatches attempts, reads
186 /// state, manages sessions.
187 Operator,
188 /// Executes a dispatched attempt: fetches its prompt/data, posts a
189 /// result, verifies its own token.
190 Worker,
191 /// Read-only: subscribes to events and reads trace/state without
192 /// mutating anything.
193 Observer,
194 /// Human/oversight role: answers queries, overrides verdicts, and can
195 /// pause/resume the loop or inject a directive.
196 Senior,
197}
198
199/// Every action a participant can request. Grouped by the [`Role`] that
200/// typically performs it (see the `// operator` / `// worker` / ... section
201/// comments below); the grouping is documentation only — actual
202/// authorization is decided by [`RoleVerbGate::is_allowed`].
203#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
204#[serde(rename_all = "snake_case")]
205pub enum Verb {
206 // operator
207 /// Create a new task.
208 StartTask,
209 /// Dispatch (or re-dispatch) an attempt for a task.
210 DispatchAttempt,
211 /// Mint a [`CapToken`] for a worker.
212 MintWorkerToken,
213 /// Read the current state of a task.
214 ReadTaskState,
215 /// Cancel a task.
216 CancelTask,
217 /// Ask a [`Role::Senior`] a question about a task.
218 QuerySenior,
219 /// Mark a task/attempt as passed.
220 MarkPass,
221 /// Mark a task/attempt as blocked.
222 MarkBlocked,
223 /// Attach a session to a task.
224 AttachSession,
225 /// Detach a session from a task.
226 DetachSession,
227 /// Emit a liveness heartbeat.
228 Heartbeat,
229 /// Poll for task progress/completion.
230 PollTask,
231 // worker
232 /// Fetch the rendered prompt for the current attempt.
233 FetchPrompt,
234 /// Fetch task input data.
235 FetchData,
236 /// Post the result of an attempt.
237 PostResult,
238 /// Verify a presented [`CapToken`].
239 VerifyToken,
240 /// Emit intermediate output for observers.
241 EmitOutput,
242 // observer
243 /// Subscribe to the task's event stream.
244 SubscribeEvents,
245 /// Read the accumulated trace of a task.
246 ReadTrace,
247 // senior
248 /// Answer a query raised via [`Verb::QuerySenior`].
249 AnswerQuery,
250 /// Override a previously recorded verdict.
251 OverrideVerdict,
252 /// Pause the dispatch loop.
253 PauseLoop,
254 /// Resume a paused dispatch loop.
255 ResumeLoop,
256 /// Inject a directive into a running task.
257 InjectDirective,
258}
259
260/// Role × Verb gate table. Const-style storage.
261#[derive(Debug, Clone)]
262pub struct RoleVerbGate {
263 table: HashMap<Role, HashSet<Verb>>,
264}
265
266impl RoleVerbGate {
267 /// Build an empty gate (nothing allowed until [`Self::allow`] is called).
268 pub fn new() -> Self {
269 Self {
270 table: HashMap::new(),
271 }
272 }
273
274 /// Allow-list `verbs` for `role`, merging with any existing entries.
275 /// Returns `self` for chained construction (see
276 /// [`default_role_verb_table`]).
277 pub fn allow(mut self, role: Role, verbs: &[Verb]) -> Self {
278 let set = self.table.entry(role).or_default();
279 for v in verbs {
280 set.insert(*v);
281 }
282 self
283 }
284
285 /// Whether `role` is allow-listed to invoke `verb`.
286 pub fn is_allowed(&self, role: Role, verb: Verb) -> bool {
287 self.table
288 .get(&role)
289 .map(|s| s.contains(&verb))
290 .unwrap_or(false)
291 }
292}
293
294impl Default for RoleVerbGate {
295 fn default() -> Self {
296 default_role_verb_table()
297 }
298}
299
300// ─── Verb tables (const slices, swap-out points for future Role splits) ──
301
302/// Verbs an Operator may invoke — covers task lifecycle, session, and
303/// senior interactions.
304pub const OPERATOR_VERBS: &[Verb] = &[
305 Verb::StartTask,
306 Verb::DispatchAttempt,
307 Verb::MintWorkerToken,
308 Verb::ReadTaskState,
309 Verb::CancelTask,
310 Verb::QuerySenior,
311 Verb::MarkPass,
312 Verb::MarkBlocked,
313 Verb::AttachSession,
314 Verb::DetachSession,
315 Verb::Heartbeat,
316 Verb::PollTask,
317];
318
319/// The Worker verbs shared across all workers — the minimum a leaf
320/// needs, with no sub-task spawning. If we introduce
321/// `Role::WorkerLeaf` in the future, that role gets allowed against
322/// this slice.
323pub const WORKER_LEAF_VERBS: &[Verb] = &[
324 Verb::FetchPrompt,
325 Verb::FetchData,
326 Verb::PostResult,
327 Verb::VerifyToken,
328 Verb::EmitOutput,
329];
330
331/// Worker verbs for recursive swarming: sub-task spawn and
332/// observation. When `Role::WorkerSwarm` splits out in the future,
333/// that role gets allowed against `WORKER_LEAF_VERBS` plus this
334/// slice. The safety valves are `EngineCfg.max_spawn_depth` today,
335/// and a task-ownership gate down the line.
336pub const WORKER_SWARM_VERBS: &[Verb] = &[
337 Verb::StartTask,
338 Verb::DispatchAttempt,
339 Verb::ReadTaskState,
340 Verb::PollTask,
341 Verb::CancelTask,
342];
343
344/// Verbs an Observer may invoke — strictly read-only (event subscription
345/// and trace/state reads, no mutation).
346pub const OBSERVER_VERBS: &[Verb] = &[Verb::SubscribeEvents, Verb::ReadTrace, Verb::ReadTaskState];
347
348/// Verbs a Senior may invoke — human/oversight actions: answering
349/// queries, overriding verdicts, and pausing/resuming/injecting into the
350/// dispatch loop.
351pub const SENIOR_VERBS: &[Verb] = &[
352 Verb::AnswerQuery,
353 Verb::OverrideVerdict,
354 Verb::PauseLoop,
355 Verb::ResumeLoop,
356 Verb::InjectDirective,
357];
358
359/// The default Role × Verb table.
360///
361/// Today `Role::Worker` holds both leaf and swarm capabilities. When
362/// we split it into `WorkerLeaf` / `WorkerSwarm` in the future, the
363/// only change needed is swapping the `allow(Role::Worker, ...)` line
364/// here for two lines — the verb slices themselves stay `const` and
365/// get reused as-is.
366pub fn default_role_verb_table() -> RoleVerbGate {
367 RoleVerbGate::new()
368 .allow(Role::Operator, OPERATOR_VERBS)
369 .allow(Role::Worker, WORKER_LEAF_VERBS)
370 .allow(Role::Worker, WORKER_SWARM_VERBS)
371 .allow(Role::Observer, OBSERVER_VERBS)
372 .allow(Role::Senior, SENIOR_VERBS)
373}
374
375// ─── CapToken ──────────────────────────────────────────────────────────────
376
377/// Capability token. `max_uses` picks between OneTime / Session /
378/// Limited.
379///
380/// The `uses_left` counter is **server-side, on `EngineState`**: the
381/// token stays immutable, and the record holds the counter.
382#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
383pub struct CapToken {
384 /// Identifier of the agent this token was minted for.
385 pub agent_id: String,
386 /// The [`Role`] the bearer is authorized to act as.
387 pub role: Role,
388 /// Free-form scope strings (interpretation is caller-defined; `"*"`
389 /// conventionally means unrestricted).
390 pub scopes: Vec<String>,
391 /// Unix timestamp (seconds) when the token was minted.
392 pub issued_at: u64,
393 /// Unix timestamp (seconds) after which the token is expired.
394 pub expire_at: u64,
395 /// Remaining-use budget: `None` = unlimited (session token), `Some(n)`
396 /// = at most `n` uses (one-time when `n == 1`).
397 pub max_uses: Option<u32>,
398 /// Random per-mint value — **secret material** (it rides inside
399 /// `encode()` and the `MSE_TOKEN_NONCE` env). The server-side lookup
400 /// key is [`CapToken::fingerprint`] (its SHA-256), never the nonce
401 /// itself (issue #14).
402 pub nonce: String,
403 /// Hex-encoded HMAC-SHA256 signature over [`CapToken::signing_input`].
404 pub sig_hex: String,
405}
406
407impl CapToken {
408 /// Server-side lookup key for this token: hex SHA-256 of the `nonce`.
409 ///
410 /// The nonce is the token's secret material, so the server never uses
411 /// it directly as a map key or prints it in diagnostics — the
412 /// fingerprint is the loggable identity (issue #14; the sibling
413 /// pattern is the operator login flow's sid / token split). Replaces
414 /// the former `id()` accessor, which returned the raw nonce.
415 pub fn fingerprint(&self) -> String {
416 token_fingerprint(&self.nonce)
417 }
418
419 /// Input for the HMAC signature — the concatenation of every field
420 /// except `sig` itself.
421 pub fn signing_input(&self) -> Vec<u8> {
422 let s = format!(
423 "{}|{:?}|{}|{}|{}|{:?}|{}",
424 self.agent_id,
425 self.role,
426 self.scopes.join(","),
427 self.issued_at,
428 self.expire_at,
429 self.max_uses,
430 self.nonce,
431 );
432 s.into_bytes()
433 }
434
435 /// Whether `now_unix` is at or past [`CapToken::expire_at`].
436 pub fn is_expired(&self, now_unix: u64) -> bool {
437 now_unix >= self.expire_at
438 }
439
440 /// Transport-safe string encoding — URL-safe base64 of the
441 /// `serde_json` representation. Used when SubAgents put the token
442 /// on the HTTP path via `Authorization: Bearer <encode()>`. The
443 /// HMAC signature covers every field, so the server verifies with
444 /// `verify_sig` after decoding.
445 pub fn encode(&self) -> String {
446 use base64::Engine as _;
447 let json = serde_json::to_vec(self).expect("CapToken is always JSON-serializable");
448 base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(json)
449 }
450
451 /// The inverse of `encode()`: base64 decode followed by JSON
452 /// parse. Either failure returns `CapTokenDecodeError` — this is
453 /// the input-validation step when the server receives a `Bearer`
454 /// token.
455 pub fn decode(s: &str) -> Result<Self, CapTokenDecodeError> {
456 use base64::Engine as _;
457 let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD
458 .decode(s)
459 .map_err(|e| CapTokenDecodeError::Base64(e.to_string()))?;
460 serde_json::from_slice(&bytes).map_err(|e| CapTokenDecodeError::Json(e.to_string()))
461 }
462}
463
464/// Response body for `HTTP /v1/worker/prompt` — the shape that lets a
465/// SubAgent pull its task input in a single round-trip.
466///
467/// - `system`: the rendered `AgentDef.profile.system_prompt` (`None`
468/// when the profile is absent).
469/// - `prompt`: `TaskSpec.initial_directive` — the value baked into the
470/// prompts table during dispatch preparation.
471/// - `agent`: `TaskSpec.agent` — the agent name this dispatch is
472/// targeting.
473/// - `attempt`: the 1-based attempt number, matching the current
474/// `task.attempt`.
475#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
476pub struct WorkerPayload {
477 /// The task this payload was fetched for. Typed [`StepId`] since issue
478 /// #14 — serde keeps the wire shape a plain string.
479 pub task_id: StepId,
480 /// 1-based attempt number, matching the current `task.attempt`.
481 pub attempt: u32,
482 /// Name of the agent this dispatch is targeting.
483 pub agent: String,
484 /// Rendered system prompt, if the agent profile defines one.
485 #[serde(skip_serializing_if = "Option::is_none")]
486 pub system: Option<String>,
487 /// The task's initial directive, baked in at dispatch preparation.
488 pub prompt: String,
489}
490
491/// Error returned when `CapToken::decode` fails.
492#[derive(Debug, thiserror::Error)]
493pub enum CapTokenDecodeError {
494 /// The input was not valid URL-safe base64.
495 #[error("base64 decode failed: {0}")]
496 Base64(String),
497 /// The decoded bytes were not valid `CapToken` JSON.
498 #[error("json parse failed: {0}")]
499 Json(String),
500}
501
502/// Server-side machinery for minting and verifying tokens.
503#[derive(Debug, Clone)]
504pub struct TokenSigner {
505 secret: Vec<u8>,
506}
507
508impl TokenSigner {
509 /// Build a signer from a raw HMAC secret (any length; HMAC accepts it).
510 pub fn new(secret: impl AsRef<[u8]>) -> Self {
511 Self {
512 secret: secret.as_ref().to_vec(),
513 }
514 }
515
516 /// Mint and sign a [`CapToken`] with an explicit `max_uses` policy.
517 /// Prefer [`Self::one_time`] / [`Self::session`] / [`Self::limited`]
518 /// for the common cases.
519 pub fn mint(
520 &self,
521 agent_id: impl Into<String>,
522 role: Role,
523 scopes: Vec<String>,
524 ttl: Duration,
525 max_uses: Option<u32>,
526 ) -> CapToken {
527 let now = now_unix();
528 let mut token = CapToken {
529 agent_id: agent_id.into(),
530 role,
531 scopes,
532 issued_at: now,
533 expire_at: now + ttl.as_secs(),
534 max_uses,
535 nonce: secure_hex(16),
536 sig_hex: String::new(),
537 };
538 let mut mac =
539 Hmac::<Sha256>::new_from_slice(&self.secret).expect("HMAC accepts any key length");
540 mac.update(&token.signing_input());
541 let sig = mac.finalize().into_bytes();
542 token.sig_hex = hex::encode(sig);
543 token
544 }
545
546 /// HMAC sig verify (constant-time eq for timing side-channel resistance).
547 pub fn verify_sig(&self, token: &CapToken) -> bool {
548 let mut mac =
549 Hmac::<Sha256>::new_from_slice(&self.secret).expect("HMAC accepts any key length");
550 mac.update(&token.signing_input());
551 let expected = mac.finalize().into_bytes();
552 let Ok(provided) = hex::decode(&token.sig_hex) else {
553 return false;
554 };
555 ct_eq(&expected, &provided)
556 }
557
558 /// Builder convenience: one-time token.
559 pub fn one_time(
560 &self,
561 agent_id: impl Into<String>,
562 role: Role,
563 scopes: Vec<String>,
564 ttl: Duration,
565 ) -> CapToken {
566 self.mint(agent_id, role, scopes, ttl, Some(1))
567 }
568
569 /// Builder convenience: session token (unlimited uses until expire).
570 pub fn session(
571 &self,
572 agent_id: impl Into<String>,
573 role: Role,
574 scopes: Vec<String>,
575 ttl: Duration,
576 ) -> CapToken {
577 self.mint(agent_id, role, scopes, ttl, None)
578 }
579
580 /// Builder convenience: limited (N uses).
581 pub fn limited(
582 &self,
583 agent_id: impl Into<String>,
584 role: Role,
585 scopes: Vec<String>,
586 ttl: Duration,
587 max_uses: u32,
588 ) -> CapToken {
589 self.mint(agent_id, role, scopes, ttl, Some(max_uses))
590 }
591}
592
593// ─── helpers ───────────────────────────────────────────────────────────────
594
595pub(crate) fn now_unix() -> u64 {
596 // A clock reporting before the epoch means the host clock is broken in a
597 // way that would otherwise silently mint `issued_at: 0` / `expire_at: 0`
598 // tokens (indistinguishable from "already expired" *and* from "minted at
599 // the epoch") — fail loud instead of laundering that into a bogus
600 // timestamp.
601 SystemTime::now()
602 .duration_since(UNIX_EPOCH)
603 .expect("system clock is before UNIX_EPOCH")
604 .as_secs()
605}
606
607/// In-process-unique, restart-decorrelated hex id.
608///
609/// Combines a monotonic per-process counter (bijective — guarantees no two
610/// calls in the same process ever collide) with a random per-process salt
611/// drawn once from the OS RNG (decorrelates ids across restarts, so a
612/// long-lived id from a previous process run can't be mistaken for one
613/// minted by the current process). The high bits of the 128-bit XOR are
614/// dominated by the salt (a process fingerprint); the low bits change on
615/// every call.
616///
617/// **Not unguessable.** The counter is a public, low-entropy sequence once
618/// the salt leaks (e.g. via any single id from this process) — never use
619/// this for bearer credentials, signing nonces, or anything else that must
620/// resist an adversary who can observe some ids and guess others. Use
621/// [`secure_hex`] for that.
622pub fn uid_hex(bytes: usize) -> String {
623 use std::sync::atomic::{AtomicU64, Ordering};
624 use std::sync::OnceLock;
625 static COUNTER: AtomicU64 = AtomicU64::new(0);
626 static SALT: OnceLock<u128> = OnceLock::new();
627 let salt = *SALT.get_or_init(|| {
628 let mut b = [0u8; 16];
629 getrandom::fill(&mut b).expect("OS RNG unavailable");
630 u128::from_le_bytes(b)
631 });
632 let c = COUNTER.fetch_add(1, Ordering::Relaxed) as u128;
633 // XOR keeps the counter's in-process uniqueness (bijection) while the
634 // per-process random salt decorrelates restarts. High 64 bits are pure
635 // salt (a process fingerprint); low bits change every call.
636 let v = salt ^ c;
637 let raw = format!("{:032x}", v);
638 let n = (bytes * 2).min(32);
639 raw[32 - n..].to_string()
640}
641
642/// OS-RNG hex, safe for bearer credentials.
643///
644/// Every byte comes from the OS random source (`getrandom`) on every call —
645/// unpredictable across calls *and* across process restarts, unlike
646/// [`uid_hex`]. Use this whenever the value itself is the secret: the
647/// [`CapToken`] nonce (its server-side lookup key and part of the signed
648/// material) and worker/session bearer handles.
649pub fn secure_hex(bytes: usize) -> String {
650 let mut buf = vec![0u8; bytes];
651 getrandom::fill(&mut buf).expect("OS RNG unavailable");
652 hex::encode(buf)
653}
654
655/// Hex SHA-256 of a token nonce / bearer string — the lookup-key shape
656/// used by [`CapToken::fingerprint`]. Standalone so callers holding only
657/// the bearer string (not a decoded token) can derive the same key.
658pub fn token_fingerprint(nonce: &str) -> String {
659 use sha2::Digest as _;
660 hex::encode(Sha256::digest(nonce.as_bytes()))
661}
662
663/// Constant-time byte-slice equality (XOR accumulate). Public so bearer
664/// comparisons outside this module (e.g. the operator login token check)
665/// can avoid the timing side channel of `==`.
666pub fn ct_eq(a: &[u8], b: &[u8]) -> bool {
667 if a.len() != b.len() {
668 return false;
669 }
670 let mut diff: u8 = 0;
671 for (x, y) in a.iter().zip(b.iter()) {
672 diff |= x ^ y;
673 }
674 diff == 0
675}
676
677#[cfg(test)]
678mod id_newtype_tests {
679 use super::*;
680
681 #[test]
682 fn parse_accepts_prefixed_ids() {
683 assert_eq!(StepId::parse("ST-abc123").unwrap().as_str(), "ST-abc123");
684 assert_eq!(TaskId::parse("T-abc123").unwrap().as_str(), "T-abc123");
685 assert_eq!(RunId::parse("R-abc123").unwrap().as_str(), "R-abc123");
686 assert_eq!(SessionId::parse("S-abc123").unwrap().as_str(), "S-abc123");
687 assert_eq!(WorkerId::parse("W-abc123").unwrap().as_str(), "W-abc123");
688 }
689
690 #[test]
691 fn parse_rejects_wrong_prefix_and_empty_suffix() {
692 // Wrong prefix (including another kind's prefix).
693 assert!(StepId::parse("T-abc").is_err());
694 assert!(TaskId::parse("ST-abc").is_err());
695 assert!(
696 RunId::parse("RK-abc").is_err(),
697 "resume keys are not run ids"
698 );
699 assert!(SessionId::parse("W-abc").is_err());
700 assert!(WorkerId::parse("S-abc").is_err());
701 // Case-sensitive.
702 assert!(StepId::parse("st-abc").is_err());
703 // Prefix alone (nothing after it).
704 assert!(TaskId::parse("T-").is_err());
705 // Garbage / empty.
706 assert!(RunId::parse("nope").is_err());
707 assert!(WorkerId::parse("").is_err());
708 }
709
710 #[test]
711 fn parse_error_carries_kind_prefix_and_input() {
712 let err = TaskId::parse("R-xyz").unwrap_err();
713 assert_eq!(err.kind, "task");
714 assert_eq!(err.expected, "T-");
715 assert_eq!(err.got, "R-xyz");
716 assert_eq!(
717 err.to_string(),
718 "invalid task id `R-xyz`: expected `T-` prefix"
719 );
720 }
721
722 #[test]
723 fn minted_ids_round_trip_through_parse() {
724 assert!(StepId::parse(StepId::new().into_string()).is_ok());
725 assert!(TaskId::parse(TaskId::new().into_string()).is_ok());
726 assert!(RunId::parse(RunId::new().into_string()).is_ok());
727 assert!(SessionId::parse(SessionId::new().into_string()).is_ok());
728 assert!(WorkerId::parse(WorkerId::new().into_string()).is_ok());
729 }
730
731 #[test]
732 fn serde_wire_format_is_a_plain_string() {
733 let id = TaskId::parse("T-abc").unwrap();
734 assert_eq!(
735 serde_json::to_value(&id).unwrap(),
736 serde_json::json!("T-abc")
737 );
738 let back: TaskId = serde_json::from_value(serde_json::json!("T-abc")).unwrap();
739 assert_eq!(back, id);
740 }
741
742 #[test]
743 fn serde_deserialize_validates_prefix() {
744 let err = serde_json::from_value::<TaskId>(serde_json::json!("ST-abc"));
745 assert!(err.is_err(), "deserialize must route through parse");
746 }
747}
748
749#[cfg(test)]
750mod cap_token_fingerprint_tests {
751 use super::*;
752 use std::time::Duration;
753
754 #[test]
755 fn fingerprint_is_sha256_of_nonce_and_not_the_nonce() {
756 let signer = TokenSigner::new("test-secret");
757 let token = signer.session("a", Role::Worker, vec!["*".into()], Duration::from_secs(60));
758 let fp = token.fingerprint();
759 // 32-byte SHA-256, hex-encoded.
760 assert_eq!(fp.len(), 64);
761 // The lookup key must never equal (or contain) the secret nonce.
762 assert_ne!(fp, token.nonce);
763 assert!(!fp.contains(&token.nonce));
764 // Standalone helper derives the same key from the bare bearer string.
765 assert_eq!(fp, token_fingerprint(&token.nonce));
766 // Deterministic per token, distinct across mints.
767 assert_eq!(fp, token.fingerprint());
768 let other = signer.session("a", Role::Worker, vec!["*".into()], Duration::from_secs(60));
769 assert_ne!(fp, other.fingerprint());
770 }
771}
772
773#[cfg(test)]
774mod cap_token_transport_tests {
775 use super::*;
776 use std::time::Duration;
777
778 #[test]
779 fn encode_decode_round_trips() {
780 let signer = TokenSigner::new("test-secret");
781 let token = signer.session(
782 "worker-of-task-x",
783 Role::Worker,
784 vec!["*".into()],
785 Duration::from_secs(600),
786 );
787 let s = token.encode();
788 // URL-safe base64 should not contain `+` `/` `=`
789 assert!(!s.contains('+'));
790 assert!(!s.contains('/'));
791 assert!(!s.contains('='));
792
793 let decoded = CapToken::decode(&s).expect("decode ok");
794 assert_eq!(decoded, token);
795 assert!(
796 signer.verify_sig(&decoded),
797 "HMAC sig still verifies after round-trip"
798 );
799 }
800
801 #[test]
802 fn decode_rejects_garbage() {
803 let err = CapToken::decode("not-base64!!!").expect_err("should fail");
804 assert!(matches!(err, CapTokenDecodeError::Base64(_)));
805 }
806
807 #[test]
808 fn decode_rejects_non_token_json() {
809 use base64::Engine as _;
810 let bogus = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(b"{\"oops\":1}");
811 let err = CapToken::decode(&bogus).expect_err("should fail json shape");
812 assert!(matches!(err, CapTokenDecodeError::Json(_)));
813 }
814}