kanade_shared/signing.rs
1//! Command provenance: the backend signs, the agent verifies (#1165).
2//!
3//! The agent authorises a command **by the subject it arrived on** and runs it
4//! without checking who wrote it. #1155 measured why that is not fixable with
5//! credentials: `deliver_subject` is not authorization-checked, so a connected
6//! party can place attacker-authored bytes on `commands.all` /
7//! `commands.pc.<id>` through a push consumer, and subject permissions cannot
8//! express a rule against it. Signing attacks a different axis — the agent
9//! checks provenance regardless of how the bytes arrived.
10//!
11//! This is the code-signing model (signed packages, Authenticode), not a login
12//! handshake. The asymmetry is the whole point: the **private** key lives only
13//! on the backend, and agents hold only **public** verify keys, which are not
14//! secrets. Compromising one of hundreds of endpoints therefore yields nothing
15//! that can command another — the endpoint holds no key capable of authoring a
16//! valid command.
17//!
18//! # Where the signature travels
19//!
20//! In **NATS headers**, over the message body's exact bytes — not in an
21//! envelope wrapping the body.
22//!
23//! Both are detached signatures and both sidestep canonicalisation (verify the
24//! received bytes, *then* deserialize). Headers win on migration: the body
25//! stays a bare serialized `Command`, so an agent that predates this feature
26//! parses a signed message exactly as it parses an unsigned one and is
27//! unaffected by the rollout. An envelope would change the body's shape, which
28//! means every agent must understand both shapes for the whole of stages 1–2 —
29//! a dual-parse path across a fleet-wide upgrade window, to buy nothing.
30//!
31//! The frame plane already does this (#1140: metadata in headers, raw payload)
32//! for the same reason: don't wrap the body when the transport has a place for
33//! metadata.
34//!
35//! # Multiple signers from the start
36//!
37//! [`SIG_KID`] is populated and checked from the first release, even while
38//! only one key exists. Adding a key id later is a wire break across the whole
39//! fleet; reserving it now costs nothing, and it buys two things:
40//!
41//! * **Rotation is not a separate mechanism.** Rotating = two valid kids for a
42//! window, which is the same code path as having two signers. A rotation
43//! procedure that shares its implementation with everyday operation is one
44//! that still works the day it is needed.
45//! * **The recovery-path decision can wait.** `kanade run` publishes its own
46//! commands (`crates/kanade/src/cmd/run.rs`) and is the documented
47//! backend-down recovery route; whether it gets a break-glass key, routes
48//! through the backend, or is retired does not have to be settled before the
49//! wire format ships.
50//!
51//! A [`KeyRing`] therefore maps `kid → (key, policy)` rather than holding a
52//! bare set of keys. Policy is what makes more keys *safer* rather than merely
53//! wider: a break-glass key should not silently carry the same authority as
54//! the backend's.
55
56use std::collections::BTreeMap;
57use std::time::Duration;
58
59// The two traits are imported anonymously so `key.sign(..)` / `key.verify(..)`
60// still resolve without `ed25519_dalek::Signer` colliding with this module's
61// own [`Signer`] — the type an operator-facing caller actually holds.
62use ed25519_dalek::{Signature, Signer as _, SigningKey, Verifier as _, VerifyingKey};
63
64/// Header carrying the base64 (standard, padded) Ed25519 signature over the
65/// message body.
66pub const SIG: &str = "Kanade-Sig";
67/// Header naming which key signed it. Present from the first release; see the
68/// module doc on why it is not deferred.
69pub const SIG_KID: &str = "Kanade-Sig-Kid";
70/// Header naming the algorithm. Ed25519 today; present so a future migration
71/// is a value change rather than a format change.
72pub const SIG_ALG: &str = "Kanade-Sig-Alg";
73/// Header carrying when the message was signed, as decimal milliseconds since
74/// the Unix epoch. **Covered by the signature** — see [`signed_material`].
75pub const SIG_AT: &str = "Kanade-Sig-At";
76
77/// The only algorithm currently emitted or accepted.
78pub const ALG_ED25519: &str = "ed25519";
79
80/// The bytes a signature actually covers: the signing time, then the message.
81///
82/// The timestamp is **inside** the signed material, unlike [`SIG_KID`], and
83/// the asymmetry is easy to get backwards. A rewritten `kid` can only select a
84/// key under which verification fails, so it is safe outside. A rewritten
85/// timestamp would let anyone replay a captured message by making it look
86/// fresh again — which is the entire freshness bound, defeated by editing one
87/// header. So it is signed.
88///
89/// The prefix is fixed-width rather than delimited so there is no
90/// concatenation ambiguity to reason about: no timestamp encoding can be
91/// chosen such that one `(at, body)` pair produces the same bytes as another.
92/// Keeping it a prefix rather than a field also leaves the `Command` wire type
93/// untouched — agent-authored in-process commands would otherwise carry a
94/// field that means nothing for them.
95pub fn signed_material(at_ms: i64, body: &[u8]) -> Vec<u8> {
96 let mut out = Vec::with_capacity(8 + body.len());
97 out.extend_from_slice(&at_ms.to_be_bytes());
98 out.extend_from_slice(body);
99 out
100}
101
102/// What a key is allowed to authorise.
103///
104/// Exists from the first release with a single variant in practical use,
105/// because a keyring without policy is just more keys that can do everything —
106/// strictly worse than one key. Adding the concept later would mean auditing
107/// every existing key's authority retroactively.
108#[derive(Debug, Clone, PartialEq, Eq)]
109pub struct KeyPolicy {
110 /// Human-facing note for logs and audit ("backend", "break-glass").
111 pub label: String,
112 /// Reject a signature older than this. `None` = no freshness bound.
113 ///
114 /// **`None` is required for the ordinary signer, not merely convenient.**
115 /// The agent's JetStream replay path deliberately redelivers the most
116 /// recent retained command per subject, kept for 7 days, so an agent
117 /// reconnecting after a week legitimately receives week-old commands. A
118 /// bound on the backend key would reject exactly that.
119 ///
120 /// A break-glass key sets a short bound, and there the bound is doing real
121 /// work rather than being belt-and-braces. Replay dedup is keyed on
122 /// `request_id` in an in-memory cache, which is **empty on first boot** —
123 /// so without a freshness check, a machine booting for the first time
124 /// would execute a week-old emergency command that no dedup can catch.
125 pub max_age: Option<Duration>,
126 /// Emit an audit record on **every** use of this key, including failed
127 /// verifications.
128 ///
129 /// A break-glass credential whose use nobody investigates is a second
130 /// production key with extra steps, so the flag lives next to the key
131 /// rather than in a call site that can forget it.
132 pub audit_every_use: bool,
133}
134
135impl KeyPolicy {
136 /// The ordinary signer: no extra freshness bound, no per-use audit (the
137 /// command itself is already audited).
138 pub fn backend(label: impl Into<String>) -> Self {
139 Self {
140 label: label.into(),
141 max_age: None,
142 audit_every_use: false,
143 }
144 }
145
146 /// A deliberately-guarded key: short-lived signatures, every use recorded.
147 pub fn break_glass(label: impl Into<String>, max_age: Duration) -> Self {
148 Self {
149 label: label.into(),
150 max_age: Some(max_age),
151 audit_every_use: true,
152 }
153 }
154}
155
156/// The public keys an agent trusts, keyed by `kid`.
157#[derive(Debug, Clone, Default)]
158pub struct KeyRing {
159 keys: BTreeMap<String, (VerifyingKey, KeyPolicy)>,
160}
161
162impl KeyRing {
163 pub fn new() -> Self {
164 Self::default()
165 }
166
167 pub fn insert(&mut self, kid: impl Into<String>, key: VerifyingKey, policy: KeyPolicy) {
168 self.keys.insert(kid.into(), (key, policy));
169 }
170
171 pub fn is_empty(&self) -> bool {
172 self.keys.is_empty()
173 }
174
175 /// Look a key up, yielding the ring's own `kid` string so a verified
176 /// result borrows from the trusted ring rather than from the attacker-
177 /// supplied header it was matched against.
178 pub fn get(&self, kid: &str) -> Option<(&str, &VerifyingKey, &KeyPolicy)> {
179 self.keys
180 .get_key_value(kid)
181 .map(|(k, (key, policy))| (k.as_str(), key, policy))
182 }
183
184 /// Every `kid` on the ring, for reporting which keys an agent holds.
185 pub fn kids(&self) -> impl Iterator<Item = &str> {
186 self.keys.keys().map(String::as_str)
187 }
188
189 /// Every entry as `kid:fingerprint`, which is what the heartbeat reports.
190 ///
191 /// The `kid` alone cannot answer "do two machines holding the same id hold
192 /// the same key" (#1229). A ring entry with the right id and wrong bytes
193 /// refuses every command once enforcement is on, and does not self-heal —
194 /// the reload-on-unknown-key path never fires, because the key *is*
195 /// present, just wrong. Carrying the fingerprint makes that state visible
196 /// from the fleet view instead of only on the host.
197 pub fn kid_fingerprints(&self) -> impl Iterator<Item = String> {
198 self.keys
199 .iter()
200 .map(|(kid, (key, _))| format!("{kid}:{}", fingerprint(key)))
201 }
202}
203
204/// A short, stable identifier for a **public** key: the first 8 bytes of
205/// SHA-256 over its raw 32 bytes, lower-case hex.
206///
207/// Truncated deliberately. This is not a security boundary — the ring itself
208/// is the trust root, and a fingerprint that matched by luck would still have
209/// to be a valid Ed25519 key someone had provisioned. It exists to be read,
210/// compared, and pasted by an operator, and to survive a `LIKE` against the
211/// projected JSON array, so 16 characters beats 64.
212pub fn fingerprint(key: &VerifyingKey) -> String {
213 use sha2::{Digest, Sha256};
214
215 let digest = Sha256::digest(key.as_bytes());
216 digest[..8].iter().fold(String::new(), |mut s, b| {
217 use std::fmt::Write;
218 let _ = write!(s, "{b:02x}");
219 s
220 })
221}
222
223/// Why a message was not accepted as backend-authored.
224///
225/// Deliberately distinguishes "carries no signature" from every other case.
226/// During stages 1–2 of the rollout `Unsigned` is expected and benign, while
227/// the rest mean something is wrong — conflating them would hide a real
228/// failure inside a normal one for the whole migration window.
229#[derive(Debug, Clone, PartialEq, Eq)]
230pub enum VerifyError {
231 /// No signature headers at all. Normal until enforcement is switched on.
232 Unsigned,
233 /// Signed, but the `kid` is not on this agent's ring.
234 ///
235 /// The operationally dangerous case: an agent that never received a new
236 /// key looks, from the operator's side, exactly like a backend that is not
237 /// sending commands — and a mid-rotation fleet is full of agents in that
238 /// state. Callers must surface this, not just log it locally.
239 UnknownKid { kid: String },
240 /// Signed with an algorithm this build does not implement.
241 UnsupportedAlg { alg: String },
242 /// Signature header present but not decodable as a signature.
243 Malformed(String),
244 /// Cryptographically invalid for the bytes received.
245 BadSignature { kid: String },
246 /// Valid, by a key whose policy bounds how old a signature may be, and
247 /// this one is older. Distinct from [`VerifyError::BadSignature`] because
248 /// the signature is genuine — what failed is the policy, and the two want
249 /// different responses.
250 Stale {
251 kid: String,
252 age_ms: i64,
253 max_age_ms: u128,
254 },
255}
256
257impl std::fmt::Display for VerifyError {
258 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
259 match self {
260 VerifyError::Unsigned => write!(f, "no signature"),
261 VerifyError::UnknownKid { kid } => {
262 write!(
263 f,
264 "signed by unknown key id {kid} — is this agent's keyring current?"
265 )
266 }
267 VerifyError::UnsupportedAlg { alg } => {
268 write!(f, "unsupported signature algorithm {alg}")
269 }
270 VerifyError::Malformed(e) => write!(f, "malformed signature: {e}"),
271 VerifyError::BadSignature { kid } => {
272 write!(f, "signature by {kid} does not match these bytes")
273 }
274 VerifyError::Stale {
275 kid,
276 age_ms,
277 max_age_ms,
278 } => write!(
279 f,
280 "signature by {kid} is {age_ms}ms old, past its {max_age_ms}ms bound"
281 ),
282 }
283 }
284}
285
286impl std::error::Error for VerifyError {}
287
288/// A verified message: which key vouched for it, and under what policy.
289#[derive(Debug, Clone, PartialEq, Eq)]
290pub struct Verified<'a> {
291 pub kid: &'a str,
292 pub policy: &'a KeyPolicy,
293}
294
295/// The signature headers carried alongside a message body.
296///
297/// Extracted from the transport by the caller so this module stays free of a
298/// NATS dependency and is testable without a broker.
299#[derive(Debug, Clone, Default, PartialEq, Eq)]
300pub struct SigHeaders {
301 pub sig_b64: Option<String>,
302 pub kid: Option<String>,
303 pub alg: Option<String>,
304 /// Decimal milliseconds since the Unix epoch, as sent. Parsed rather than
305 /// trusted — it is covered by the signature, so a value that does not
306 /// reconstruct the signed material simply fails verification.
307 pub at_ms: Option<String>,
308}
309
310impl SigHeaders {
311 /// True only when the message makes **no signing claim at all**.
312 ///
313 /// Any one of these headers means the sender is asserting the message is
314 /// signed, so a partial set is a broken claim rather than an absent one.
315 /// `alg` counts for the same reason `kid` does: the rule has to be "no
316 /// signing headers at all", not "none of the two I happened to think of",
317 /// or stripping whichever header is unchecked reclassifies a malformed
318 /// message as an unsigned one — and unsigned is the accepted case for the
319 /// whole of stages 1-2.
320 pub fn is_absent(&self) -> bool {
321 self.sig_b64.is_none() && self.kid.is_none() && self.alg.is_none() && self.at_ms.is_none()
322 }
323}
324
325/// Verify `body` against the signature headers using `ring`.
326///
327/// Verification is over the **exact received bytes**; deserialization happens
328/// afterwards, at the caller. That ordering is what removes canonicalisation
329/// from the problem — there is no need for serde to produce byte-identical
330/// output on both sides, only for the bytes to arrive unchanged.
331pub fn verify<'a>(
332 ring: &'a KeyRing,
333 body: &[u8],
334 headers: &SigHeaders,
335 now_ms: i64,
336) -> Result<Verified<'a>, VerifyError> {
337 if headers.is_absent() {
338 return Err(VerifyError::Unsigned);
339 }
340 // A signature with no kid cannot be attributed, so it is not "unsigned" —
341 // it is a signed message we cannot route to a key.
342 let kid = headers
343 .kid
344 .as_deref()
345 .ok_or_else(|| VerifyError::Malformed("signature without a key id".into()))?;
346 let sig_b64 = headers
347 .sig_b64
348 .as_deref()
349 .ok_or_else(|| VerifyError::Malformed("key id without a signature".into()))?;
350 let at_raw = headers
351 .at_ms
352 .as_deref()
353 .ok_or_else(|| VerifyError::Malformed("signature without a signing time".into()))?;
354 let at_ms: i64 = at_raw
355 .parse()
356 .map_err(|_| VerifyError::Malformed(format!("signing time {at_raw} is not a number")))?;
357
358 // Absent alg means the original single-algorithm shape; anything else must
359 // match exactly rather than being guessed at.
360 if let Some(alg) = headers.alg.as_deref()
361 && alg != ALG_ED25519
362 {
363 return Err(VerifyError::UnsupportedAlg {
364 alg: alg.to_owned(),
365 });
366 }
367
368 // The kid is a key-selection hint and is NOT covered by the signature.
369 // That is safe: rewriting it can only select a key under which
370 // verification fails, never make an invalid signature pass. The signing
371 // time is the opposite case and IS covered — see `signed_material`.
372 let (ring_kid, key, policy) = ring.get(kid).ok_or_else(|| VerifyError::UnknownKid {
373 kid: kid.to_owned(),
374 })?;
375
376 let raw = base64_decode(sig_b64).map_err(VerifyError::Malformed)?;
377 let sig = Signature::from_slice(&raw).map_err(|e| VerifyError::Malformed(e.to_string()))?;
378 key.verify(&signed_material(at_ms, body), &sig)
379 .map_err(|_| VerifyError::BadSignature {
380 kid: kid.to_owned(),
381 })?;
382
383 // Freshness is checked only AFTER the signature holds, so a stale verdict
384 // is always about a genuine message. Checking it first would let anyone
385 // provoke a `Stale` report by sending garbage with an old timestamp.
386 if let Some(max_age) = policy.max_age {
387 let age_ms = now_ms - at_ms;
388 let max_age_ms = max_age.as_millis();
389 // Compared in i128 rather than casting the bound down to i64. A
390 // `max_age_secs` large enough to overflow the cast is nonsense config
391 // rather than an attack (the registry holding it is ACL'd), but the
392 // truncation would silently turn a bound into its opposite — a
393 // negative limit that nothing can satisfy, or one so large the key is
394 // effectively unbounded — and `-(x as i64)` can panic outright on
395 // i64::MIN in a debug build. i128 holds every value `Duration::as_millis`
396 // can produce, so there is nothing left to get wrong.
397 let age = age_ms as i128;
398 let bound = max_age_ms as i128;
399 // A signature from the future is not "fresh" — it is a clock that
400 // disagrees, and treating it as valid would let a skewed or hostile
401 // signer mint credentials that outlive the bound. Bound both ends.
402 if age > bound || age < -bound {
403 return Err(VerifyError::Stale {
404 kid: kid.to_owned(),
405 age_ms,
406 max_age_ms,
407 });
408 }
409 }
410
411 Ok(Verified {
412 kid: ring_kid,
413 policy,
414 })
415}
416
417/// Sign `body`, producing the headers to publish alongside it.
418///
419/// Lives here rather than in the backend so the signing and verifying halves
420/// cannot drift — a round-trip test in this module covers both at once.
421pub fn sign(key: &SigningKey, kid: &str, body: &[u8], at_ms: i64) -> SigHeaders {
422 let sig = key.sign(&signed_material(at_ms, body));
423 SigHeaders {
424 sig_b64: Some(base64_encode(&sig.to_bytes())),
425 kid: Some(kid.to_owned()),
426 alg: Some(ALG_ED25519.to_owned()),
427 at_ms: Some(at_ms.to_string()),
428 }
429}
430
431/// The signing half, bound to the id agents know it by.
432///
433/// The key and its `kid` are only meaningful together, so nothing here hands
434/// out one without the other. Signing under an id whose public half agents
435/// hold for a *different* key produces `command_signature_invalid` on every
436/// machine at once — which reads as a fleet-wide forgery, not as the
437/// misconfiguration it is. Any API that lets the two be supplied separately is
438/// a way to reach that state, and `resolve_kid` on the generating side already
439/// refuses the other way in (two keys sharing one id).
440pub struct Signer {
441 key: SigningKey,
442 kid: String,
443}
444
445impl Signer {
446 pub fn new(key: SigningKey, kid: impl Into<String>) -> Self {
447 Self {
448 key,
449 kid: kid.into(),
450 }
451 }
452
453 /// Build from the encoded secret as it rests in the registry or the
454 /// environment, rejecting an empty `kid` rather than signing under one.
455 ///
456 /// An empty id is not a cosmetic problem: `Kanade-Sig-Kid: ""` matches no
457 /// keyring entry, so every agent that holds keys reports
458 /// `command_signature_unknown_key` — the signal that is supposed to mean
459 /// "this agent missed a rotation". Producing it from a backend-side typo
460 /// would train operators to ignore the one alarm the rotation procedure
461 /// depends on.
462 ///
463 /// (An agent holding *no* keys reports `command_signature_unprovisioned`
464 /// instead, since it cannot tell an empty id from any other it lacks. The
465 /// distinction is the agent's, in `command_verify`; the harm named above is
466 /// the one that lands on an already-provisioned fleet.)
467 pub fn from_secret(secret: &str, kid: &str) -> Result<Self, String> {
468 if kid.trim().is_empty() {
469 return Err("the signing key id is empty".to_string());
470 }
471 Ok(Self::new(decode_secret(secret)?, kid))
472 }
473
474 pub fn kid(&self) -> &str {
475 &self.kid
476 }
477
478 pub fn verifying_key(&self) -> VerifyingKey {
479 self.key.verifying_key()
480 }
481
482 /// Sign `body` as of `at_ms`, yielding the headers to publish with it.
483 pub fn headers(&self, body: &[u8], at_ms: i64) -> SigHeaders {
484 sign(&self.key, &self.kid, body, at_ms)
485 }
486}
487
488/// Which half of a `(secret, kid)` pair is missing.
489///
490/// Returned rather than a formatted message so each caller can name the store
491/// it looked in — the registry, an environment variable pair, a config file —
492/// while the rule itself lives in one place. Two callers writing their own
493/// version of "half is an error" is how they end up disagreeing about it.
494#[derive(Debug, Clone, Copy, PartialEq, Eq)]
495pub enum MissingHalf {
496 /// A key id with no key to go with it.
497 Key,
498 /// A key with no id. Cannot be signed with: `Kanade-Sig-Kid` has to name
499 /// something the fleet's keyring recognises, and guessing produces a
500 /// signature every agent reports as unattributable.
501 Kid,
502}
503
504/// Classify a possibly-half-configured `(secret, kid)` pair.
505///
506/// `Ok(None)` = nothing configured, which is a legitimate state everywhere
507/// this is used (a host that does not sign, an operator without a break-glass
508/// key to hand). `Err` = exactly one half present, which is never intentional
509/// and must not silently fall back to unsigned: signing under a mismatched or
510/// invented id produces `command_signature_invalid` fleet-wide, which is the
511/// forgery alarm raised by a configuration mistake.
512pub fn pair<'a>(
513 secret: Option<&'a str>,
514 kid: Option<&'a str>,
515) -> Result<Option<(&'a str, &'a str)>, MissingHalf> {
516 match (secret, kid) {
517 (Some(s), Some(k)) => Ok(Some((s, k))),
518 (Some(_), None) => Err(MissingHalf::Kid),
519 (None, Some(_)) => Err(MissingHalf::Key),
520 (None, None) => Ok(None),
521 }
522}
523
524/// The JSON object an agent's `CommandKeys` array holds for a **break-glass**
525/// key.
526///
527/// Differs from [`keyring_entry`] by carrying `max_age_secs`, which is what
528/// makes the agent treat it as break-glass at all: `parse_keyring` maps a
529/// present `max_age_secs` to [`KeyPolicy::break_glass`], and that constructor
530/// is what sets `audit_every_use`.
531///
532/// Deliberately does **not** emit `audit_every_use`. The agent ignores that
533/// field whenever `max_age_secs` is present — auditing is not optional for a
534/// break-glass key — so printing it would put a value in the operator's file
535/// that looks adjustable and is not. An entry that lies about what it controls
536/// is worse than one that omits it.
537pub fn break_glass_keyring_entry(
538 kid: &str,
539 key: &VerifyingKey,
540 label: &str,
541 max_age: Duration,
542) -> serde_json::Value {
543 serde_json::json!({
544 "kid": kid,
545 "public_key": encode_public(key),
546 "label": label,
547 "max_age_secs": max_age.as_secs(),
548 })
549}
550
551/// Hand-written so the private key cannot reach a log line.
552///
553/// `SigningKey` derives `Debug` and prints its bytes, so a derived impl here
554/// would put the fleet's crown jewel into any `tracing` call that formats the
555/// struct — including the ones nobody writes deliberately, like a `#[derive(
556/// Debug)]` on an enclosing type.
557impl std::fmt::Debug for Signer {
558 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
559 f.debug_struct("Signer").field("kid", &self.kid).finish()
560 }
561}
562
563/// Registry subkey + value holding the backend's **private** signing key.
564///
565/// Lives beside `StaticToken` / `JwtSecret` in the key `deploy-backend.ps1`
566/// already hardens to SYSTEM + Administrators. Registry ACLs are per-key, not
567/// per-value, so a value written into that key inherits the protection — which
568/// is why the writer must refuse to *create* the key: creating it would
569/// produce an unhardened one and leave the signing key world-readable.
570pub const REG_BACKEND_SUBKEY: &str = r"SOFTWARE\kanade\backend";
571pub const REG_SIGNING_KEY: &str = "CommandSigningKey";
572/// Registry value holding the `kid` that names the key beside it.
573///
574/// Persisted rather than re-derived. The signing path needs it to fill
575/// `Kanade-Sig-Kid`, and it is the operator's choice — re-deriving a date
576/// stamp at signing time would produce a different id than the one already
577/// distributed to agents whenever a key is generated on one day and first used
578/// on another. An id that disagrees with the fleet's keyring is
579/// indistinguishable, from the agent's side, from an unknown signer.
580pub const REG_SIGNING_KID: &str = "CommandSigningKid";
581
582/// Mint a fresh signing keypair.
583pub fn generate_keypair() -> Result<SigningKey, String> {
584 // Seeded from the OS CSPRNG directly rather than through
585 // `SigningKey::generate`, which wants a `rand_core` RNG — and this
586 // workspace carries three incompatible `rand_core` majors transitively.
587 // Filling 32 bytes sidesteps the version pairing entirely, and the seed
588 // *is* the key, so nothing is lost.
589 let mut seed = [0u8; 32];
590 getrandom::fill(&mut seed).map_err(|e| format!("OS randomness unavailable: {e}"))?;
591 Ok(SigningKey::from_bytes(&seed))
592}
593
594/// Base64 of the 32-byte seed. This is the secret; it is written to the
595/// registry and never printed by any code path that logs.
596pub fn encode_secret(key: &SigningKey) -> String {
597 base64_encode(&key.to_bytes())
598}
599
600pub fn decode_secret(raw: &str) -> Result<SigningKey, String> {
601 let bytes = base64_decode(raw)?;
602 let arr: [u8; 32] = bytes
603 .as_slice()
604 .try_into()
605 .map_err(|_| format!("signing key must be 32 bytes, got {}", bytes.len()))?;
606 Ok(SigningKey::from_bytes(&arr))
607}
608
609pub fn encode_public(key: &VerifyingKey) -> String {
610 base64_encode(key.as_bytes())
611}
612
613/// The JSON object an agent's `CommandKeys` array holds for this key.
614///
615/// Emitted by the generator so the operator distributes a value that is
616/// correct by construction rather than assembling it by hand — the shape is
617/// parsed by `kanade-agent`'s `parse_keyring`, and a hand-built entry that
618/// fails to parse takes the whole ring with it.
619pub fn keyring_entry(kid: &str, key: &VerifyingKey, label: &str) -> serde_json::Value {
620 serde_json::json!({
621 "kid": kid,
622 "public_key": encode_public(key),
623 "label": label,
624 })
625}
626
627fn base64_encode(bytes: &[u8]) -> String {
628 use base64::Engine;
629 base64::engine::general_purpose::STANDARD.encode(bytes)
630}
631
632fn base64_decode(s: &str) -> Result<Vec<u8>, String> {
633 use base64::Engine;
634 base64::engine::general_purpose::STANDARD
635 .decode(s)
636 .map_err(|e| e.to_string())
637}
638
639#[cfg(test)]
640mod tests {
641 use super::*;
642
643 /// A fixed "now" so the tests never depend on wall-clock time.
644 const NOW: i64 = 1_700_000_000_000;
645
646 fn keypair(seed: u8) -> (SigningKey, VerifyingKey) {
647 let sk = SigningKey::from_bytes(&[seed; 32]);
648 let vk = sk.verifying_key();
649 (sk, vk)
650 }
651
652 fn ring_with(kid: &str, vk: VerifyingKey) -> KeyRing {
653 let mut r = KeyRing::new();
654 r.insert(kid, vk, KeyPolicy::backend("backend"));
655 r
656 }
657
658 #[test]
659 fn a_fingerprint_is_a_fixed_width_lower_hex_string() {
660 let (_, vk) = keypair(1);
661 let fp = fingerprint(&vk);
662 assert_eq!(fp.len(), 16, "8 bytes, hex: {fp}");
663 assert!(
664 fp.chars()
665 .all(|c| c.is_ascii_digit() || ('a'..='f').contains(&c)),
666 "must be pasteable and LIKE-able without escaping: {fp}"
667 );
668 }
669
670 #[test]
671 fn a_fingerprint_is_stable_across_calls_and_distinct_across_keys() {
672 // Stability is the whole point — a value that varied per call would
673 // make every host look like the odd one out. Distinctness is what makes
674 // a same-kid-different-key ring visible (#1229).
675 let (_, a) = keypair(2);
676 let (_, b) = keypair(3);
677 assert_eq!(fingerprint(&a), fingerprint(&a));
678 assert_ne!(fingerprint(&a), fingerprint(&b));
679 }
680
681 #[test]
682 fn a_fingerprint_is_pinned_to_the_public_key_bytes() {
683 // Pinned against a hand-computed value so a change of hash, of
684 // truncation length, or of *what* is hashed (the raw 32 bytes, not the
685 // base64 text) fails here rather than fleet-wide, where every host
686 // would silently disagree with every stored literal.
687 use sha2::{Digest, Sha256};
688
689 let (_, vk) = keypair(7);
690 let expect: String = Sha256::digest(vk.as_bytes())[..8]
691 .iter()
692 .map(|b| format!("{b:02x}"))
693 .collect();
694 assert_eq!(fingerprint(&vk), expect);
695 }
696
697 #[test]
698 fn a_ring_reports_each_entry_as_kid_then_fingerprint() {
699 let (_, a) = keypair(4);
700 let (_, b) = keypair(5);
701 let mut ring = ring_with("backend-1", a);
702 ring.insert("break-glass-1", b, KeyPolicy::backend("break-glass"));
703
704 let reported: Vec<String> = ring.kid_fingerprints().collect();
705 assert_eq!(
706 reported,
707 vec![
708 format!("backend-1:{}", fingerprint(&a)),
709 format!("break-glass-1:{}", fingerprint(&b)),
710 ],
711 "sorted by kid, so a heartbeat does not churn the projected value"
712 );
713 }
714
715 #[test]
716 fn round_trip_accepts_the_bytes_that_were_signed() {
717 let (sk, vk) = keypair(1);
718 let ring = ring_with("backend-1", vk);
719 let body = br#"{"id":"job","request_id":"r1"}"#;
720
721 let headers = sign(&sk, "backend-1", body, NOW);
722 let ok = verify(&ring, body, &headers, NOW).expect("verifies");
723 assert_eq!(ok.kid, "backend-1");
724 assert_eq!(ok.policy.label, "backend");
725 }
726
727 #[test]
728 fn a_single_flipped_byte_fails() {
729 let (sk, vk) = keypair(1);
730 let ring = ring_with("backend-1", vk);
731 let headers = sign(&sk, "backend-1", b"run this", NOW);
732 // The whole point: bytes the backend did not author must not execute.
733 assert_eq!(
734 verify(&ring, b"run thit", &headers, NOW),
735 Err(VerifyError::BadSignature {
736 kid: "backend-1".into()
737 })
738 );
739 }
740
741 #[test]
742 fn a_forged_command_from_another_key_fails() {
743 // The #1155 attacker: holds a NATS credential, can place bytes on a
744 // command subject, and signs with a key of their own.
745 let (_, backend_vk) = keypair(1);
746 let (attacker_sk, _) = keypair(9);
747 let ring = ring_with("backend-1", backend_vk);
748
749 let body = b"malicious";
750 // Signed with the attacker's key but claiming the backend's kid — the
751 // kid being outside the signature buys them nothing.
752 let headers = sign(&attacker_sk, "backend-1", body, NOW);
753 assert_eq!(
754 verify(&ring, body, &headers, NOW),
755 Err(VerifyError::BadSignature {
756 kid: "backend-1".into()
757 })
758 );
759 }
760
761 #[test]
762 fn unsigned_is_distinct_from_every_failure() {
763 let (_, vk) = keypair(1);
764 let ring = ring_with("backend-1", vk);
765 // Stages 1–2 deliver unsigned commands as a matter of course. If this
766 // collapsed into the same error as a bad signature, a real forgery
767 // would be indistinguishable from normal traffic for the whole
768 // migration window.
769 assert_eq!(
770 verify(&ring, b"anything", &SigHeaders::default(), NOW),
771 Err(VerifyError::Unsigned)
772 );
773 }
774
775 #[test]
776 fn an_unknown_kid_is_its_own_error() {
777 let (sk, vk) = keypair(1);
778 let ring = ring_with("backend-1", vk);
779 let headers = sign(&sk, "backend-2", b"body", NOW);
780 // The mid-rotation state: correctly signed, but this agent has not
781 // been given the new key. Reported distinctly because "your keyring is
782 // stale" and "someone forged this" need opposite responses.
783 assert_eq!(
784 verify(&ring, b"body", &headers, NOW),
785 Err(VerifyError::UnknownKid {
786 kid: "backend-2".into()
787 })
788 );
789 }
790
791 #[test]
792 fn rotation_is_two_kids_on_one_ring() {
793 // Rotation shares its implementation with multi-signer rather than
794 // being a separate mechanism — this is that claim, as a test.
795 let (old_sk, old_vk) = keypair(1);
796 let (new_sk, new_vk) = keypair(2);
797 let mut ring = ring_with("backend-1", old_vk);
798 ring.insert("backend-2", new_vk, KeyPolicy::backend("backend (new)"));
799
800 for (sk, kid) in [(&old_sk, "backend-1"), (&new_sk, "backend-2")] {
801 let headers = sign(sk, kid, b"during the window", NOW);
802 assert_eq!(
803 verify(&ring, b"during the window", &headers, NOW)
804 .unwrap()
805 .kid,
806 kid
807 );
808 }
809 }
810
811 #[test]
812 fn policies_are_per_key_not_per_ring() {
813 // Without this, "multiple signers" means "more keys that can do
814 // everything", which is worse than one key.
815 let (_, backend_vk) = keypair(1);
816 let (bg_sk, bg_vk) = keypair(3);
817 let mut ring = ring_with("backend-1", backend_vk);
818 ring.insert(
819 "break-glass",
820 bg_vk,
821 KeyPolicy::break_glass("break-glass", Duration::from_secs(300)),
822 );
823
824 let headers = sign(&bg_sk, "break-glass", b"emergency", NOW);
825 let ok = verify(&ring, b"emergency", &headers, NOW).unwrap();
826 assert!(
827 ok.policy.audit_every_use,
828 "break-glass use must be recorded"
829 );
830 assert_eq!(ok.policy.max_age, Some(Duration::from_secs(300)));
831
832 // The ordinary signer keeps the ordinary policy.
833 let (sk, vk) = keypair(1);
834 let mut r2 = KeyRing::new();
835 r2.insert("backend-1", vk, KeyPolicy::backend("backend"));
836 let h = sign(&sk, "backend-1", b"routine", NOW);
837 assert!(
838 !verify(&r2, b"routine", &h, NOW)
839 .unwrap()
840 .policy
841 .audit_every_use
842 );
843 }
844
845 #[test]
846 fn partial_or_unreadable_headers_are_rejected_rather_than_ignored() {
847 let (_, vk) = keypair(1);
848 let ring = ring_with("backend-1", vk);
849
850 // A signature with no kid cannot be attributed. Treating it as
851 // "unsigned" would let an attacker strip the kid to slip a message
852 // through the stage-1/2 accept-unsigned path.
853 let no_kid = SigHeaders {
854 sig_b64: Some("AAAA".into()),
855 kid: None,
856 alg: None,
857 at_ms: None,
858 };
859 assert!(matches!(
860 verify(&ring, b"x", &no_kid, NOW),
861 Err(VerifyError::Malformed(_))
862 ));
863
864 // A kid with no signature is equally not "unsigned".
865 let no_sig = SigHeaders {
866 sig_b64: None,
867 kid: Some("backend-1".into()),
868 alg: None,
869 at_ms: None,
870 };
871 assert!(matches!(
872 verify(&ring, b"x", &no_sig, NOW),
873 Err(VerifyError::Malformed(_))
874 ));
875
876 // Only the algorithm header, with nothing to verify. It still claims
877 // to be signed, so it must not fall through to the accept-unsigned
878 // path: the rule is "no signing headers at all", not "none of the two
879 // that carry the signature".
880 let alg_only = SigHeaders {
881 sig_b64: None,
882 kid: None,
883 alg: Some(ALG_ED25519.into()),
884 at_ms: None,
885 };
886 assert!(matches!(
887 verify(&ring, b"x", &alg_only, NOW),
888 Err(VerifyError::Malformed(_))
889 ));
890
891 // Not base64 at all.
892 let junk = SigHeaders {
893 sig_b64: Some("!!!not base64!!!".into()),
894 kid: Some("backend-1".into()),
895 alg: None,
896 at_ms: Some(NOW.to_string()),
897 };
898 assert!(matches!(
899 verify(&ring, b"x", &junk, NOW),
900 Err(VerifyError::Malformed(_))
901 ));
902 }
903
904 #[test]
905 fn an_unexpected_algorithm_is_refused_not_assumed() {
906 let (sk, vk) = keypair(1);
907 let ring = ring_with("backend-1", vk);
908 let mut headers = sign(&sk, "backend-1", b"body", NOW);
909 headers.alg = Some("hmac-sha256".into());
910 assert_eq!(
911 verify(&ring, b"body", &headers, NOW),
912 Err(VerifyError::UnsupportedAlg {
913 alg: "hmac-sha256".into()
914 })
915 );
916 }
917
918 #[test]
919 fn an_absent_alg_header_means_the_original_shape() {
920 // Forward compatibility in the other direction: a signer that predates
921 // the alg header must still verify.
922 let (sk, vk) = keypair(1);
923 let ring = ring_with("backend-1", vk);
924 let mut headers = sign(&sk, "backend-1", b"body", NOW);
925 headers.alg = None;
926 assert!(verify(&ring, b"body", &headers, NOW).is_ok());
927 }
928
929 #[test]
930 fn the_signing_time_is_covered_by_the_signature() {
931 // The asymmetry with `kid`: rewriting the timestamp must not verify,
932 // or a captured message could be replayed by simply making it look
933 // fresh. This is the whole reason `at` sits inside the signed
934 // material.
935 let (sk, vk) = keypair(1);
936 let ring = ring_with("backend-1", vk);
937 let mut headers = sign(&sk, "backend-1", b"body", NOW);
938 headers.at_ms = Some((NOW + 1).to_string());
939 assert_eq!(
940 verify(&ring, b"body", &headers, NOW),
941 Err(VerifyError::BadSignature {
942 kid: "backend-1".into()
943 })
944 );
945 }
946
947 #[test]
948 fn the_ordinary_signer_accepts_a_week_old_command() {
949 // Not a nicety: the agent's JetStream replay redelivers the retained
950 // command per subject for 7 days, so an agent reconnecting after a
951 // week legitimately receives week-old commands. A freshness bound on
952 // the backend key would reject exactly that traffic.
953 let (sk, vk) = keypair(1);
954 let ring = ring_with("backend-1", vk);
955 let week = 7 * 24 * 60 * 60 * 1000;
956 let headers = sign(&sk, "backend-1", b"scheduled job", NOW - week);
957 assert!(verify(&ring, b"scheduled job", &headers, NOW).is_ok());
958 }
959
960 #[test]
961 fn a_bounded_key_rejects_an_old_signature() {
962 let (sk, vk) = keypair(3);
963 let mut ring = KeyRing::new();
964 ring.insert(
965 "break-glass",
966 vk,
967 KeyPolicy::break_glass("break-glass", Duration::from_secs(300)),
968 );
969
970 // Inside the window.
971 let fresh = sign(&sk, "break-glass", b"emergency", NOW - 60_000);
972 assert!(verify(&ring, b"emergency", &fresh, NOW).is_ok());
973
974 // Past it. This is the case that stops a first-boot agent executing a
975 // week-old emergency command: its dedup cache is empty, so freshness
976 // is the only thing left.
977 let old = sign(&sk, "break-glass", b"emergency", NOW - 600_000);
978 assert_eq!(
979 verify(&ring, b"emergency", &old, NOW),
980 Err(VerifyError::Stale {
981 kid: "break-glass".into(),
982 age_ms: 600_000,
983 max_age_ms: 300_000,
984 })
985 );
986 }
987
988 #[test]
989 fn a_signature_from_the_future_is_not_fresh() {
990 // A clock that disagrees, or a signer trying to mint something that
991 // outlives its bound. Bounding only the old side would let a
992 // far-future timestamp stay valid indefinitely.
993 let (sk, vk) = keypair(3);
994 let mut ring = KeyRing::new();
995 ring.insert(
996 "break-glass",
997 vk,
998 KeyPolicy::break_glass("break-glass", Duration::from_secs(300)),
999 );
1000 let ahead = sign(&sk, "break-glass", b"emergency", NOW + 3_600_000);
1001 assert!(matches!(
1002 verify(&ring, b"emergency", &ahead, NOW),
1003 Err(VerifyError::Stale { .. })
1004 ));
1005 // Modest skew inside the window still passes, so a machine a few
1006 // seconds ahead is not locked out.
1007 let skewed = sign(&sk, "break-glass", b"emergency", NOW + 5_000);
1008 assert!(verify(&ring, b"emergency", &skewed, NOW).is_ok());
1009 }
1010
1011 #[test]
1012 fn freshness_is_only_judged_after_the_signature_holds() {
1013 // Otherwise anyone could provoke a `Stale` report — which at stage 3
1014 // is a rejection an operator has to investigate — by sending garbage
1015 // with an old timestamp.
1016 let (_, vk) = keypair(3);
1017 let mut ring = KeyRing::new();
1018 ring.insert(
1019 "break-glass",
1020 vk,
1021 KeyPolicy::break_glass("break-glass", Duration::from_secs(300)),
1022 );
1023 let forged = SigHeaders {
1024 sig_b64: Some(base64_encode(&[7u8; 64])),
1025 kid: Some("break-glass".into()),
1026 alg: Some(ALG_ED25519.into()),
1027 at_ms: Some((NOW - 600_000).to_string()),
1028 };
1029 assert_eq!(
1030 verify(&ring, b"x", &forged, NOW),
1031 Err(VerifyError::BadSignature {
1032 kid: "break-glass".into()
1033 })
1034 );
1035 }
1036
1037 #[test]
1038 fn a_missing_or_unparseable_signing_time_is_malformed() {
1039 let (sk, vk) = keypair(1);
1040 let ring = ring_with("backend-1", vk);
1041
1042 let mut no_at = sign(&sk, "backend-1", b"body", NOW);
1043 no_at.at_ms = None;
1044 assert!(matches!(
1045 verify(&ring, b"body", &no_at, NOW),
1046 Err(VerifyError::Malformed(_))
1047 ));
1048
1049 let mut junk_at = sign(&sk, "backend-1", b"body", NOW);
1050 junk_at.at_ms = Some("yesterday".into());
1051 assert!(matches!(
1052 verify(&ring, b"body", &junk_at, NOW),
1053 Err(VerifyError::Malformed(_))
1054 ));
1055
1056 // And a lone `at` header still counts as a signing claim rather than
1057 // an absent one.
1058 let at_only = SigHeaders {
1059 sig_b64: None,
1060 kid: None,
1061 alg: None,
1062 at_ms: Some(NOW.to_string()),
1063 };
1064 assert!(matches!(
1065 verify(&ring, b"body", &at_only, NOW),
1066 Err(VerifyError::Malformed(_))
1067 ));
1068 }
1069
1070 #[test]
1071 fn an_absurd_bound_neither_panics_nor_inverts() {
1072 // `max_age_secs` reaches this from JSON with no upper bound. A value
1073 // this large is a typo rather than an attack, but the old `as i64`
1074 // cast would have truncated it into a negative limit that nothing can
1075 // satisfy — turning "almost never expires" into "always expired" —
1076 // and could panic on the negation in a debug build.
1077 let (sk, vk) = keypair(5);
1078 let mut ring = KeyRing::new();
1079 ring.insert(
1080 "silly",
1081 vk,
1082 KeyPolicy::break_glass("silly", Duration::from_secs(u64::MAX / 1000)),
1083 );
1084 let headers = sign(&sk, "silly", b"body", NOW - 10_000);
1085 assert!(
1086 verify(&ring, b"body", &headers, NOW).is_ok(),
1087 "an enormous bound must read as permissive, not as inverted"
1088 );
1089 }
1090
1091 #[test]
1092 fn a_generated_key_round_trips_through_its_encoded_secret() {
1093 // The registry stores the encoded secret; if this did not round trip,
1094 // a backend would come back from a restart unable to sign and every
1095 // agent would start reporting unsigned traffic.
1096 let key = generate_keypair().expect("OS randomness");
1097 let restored = decode_secret(&encode_secret(&key)).expect("decodes");
1098 assert_eq!(restored.to_bytes(), key.to_bytes());
1099
1100 // And the restored key produces signatures the original's public half
1101 // accepts — the property that actually matters across a restart.
1102 let ring = ring_with("backend-1", key.verifying_key());
1103 let headers = sign(&restored, "backend-1", b"after a restart", NOW);
1104 assert!(verify(&ring, b"after a restart", &headers, NOW).is_ok());
1105 }
1106
1107 #[test]
1108 fn a_signer_built_from_the_stored_secret_verifies_against_its_own_ring() {
1109 // The whole backend-side path in one assertion: the encoded secret as
1110 // it rests in the registry, through `Signer`, out as headers, verified
1111 // by the public half an agent was given.
1112 let key = generate_keypair().unwrap();
1113 let signer = Signer::from_secret(&encode_secret(&key), "backend-1").expect("builds");
1114 let ring = ring_with("backend-1", key.verifying_key());
1115
1116 let body = br#"{"id":"job","request_id":"r1"}"#;
1117 let headers = signer.headers(body, NOW);
1118 assert_eq!(verify(&ring, body, &headers, NOW).unwrap().kid, "backend-1");
1119 }
1120
1121 #[test]
1122 fn a_signer_refuses_an_empty_kid_rather_than_signing_under_one() {
1123 // `Kanade-Sig-Kid: ""` matches no keyring entry, so every agent that
1124 // holds keys would report `unknown_key` — the alarm that is supposed to
1125 // mean a rotation went wrong. A backend typo must not be able to raise
1126 // it fleet-wide. (A machine holding none reports `unprovisioned`; the
1127 // fleet this harms is the already-provisioned one.)
1128 let secret = encode_secret(&generate_keypair().unwrap());
1129 assert!(Signer::from_secret(&secret, "").is_err());
1130 assert!(Signer::from_secret(&secret, " ").is_err());
1131 // And a bad secret is still rejected on its own terms.
1132 assert!(Signer::from_secret("not base64!!", "backend-1").is_err());
1133 }
1134
1135 #[test]
1136 fn debugging_a_signer_never_prints_the_key() {
1137 // `SigningKey` derives Debug and prints its bytes, so a derived impl
1138 // would leak the fleet's crown jewel into any log line that formats an
1139 // enclosing struct.
1140 let key = generate_keypair().unwrap();
1141 let signer = Signer::new(key.clone(), "backend-1");
1142 // Pinned exactly rather than by absence: a field added later would
1143 // otherwise have to be *remembered* to be excluded, and the failure
1144 // mode is a secret in a log file.
1145 assert_eq!(format!("{signer:?}"), r#"Signer { kid: "backend-1" }"#);
1146 assert!(!format!("{signer:?}").contains(&encode_secret(&key)));
1147 }
1148
1149 #[test]
1150 fn a_half_configured_pair_names_the_missing_half() {
1151 assert_eq!(
1152 pair(Some("secret"), Some("kid")),
1153 Ok(Some(("secret", "kid")))
1154 );
1155 assert_eq!(pair(None, None), Ok(None));
1156 // The two failures are distinguished because the fixes differ: one
1157 // needs a key generated, the other needs the id it was distributed
1158 // under.
1159 assert_eq!(pair(Some("secret"), None), Err(MissingHalf::Kid));
1160 assert_eq!(pair(None, Some("kid")), Err(MissingHalf::Key));
1161 }
1162
1163 #[test]
1164 fn a_break_glass_entry_carries_the_bound_and_not_the_audit_flag() {
1165 // `max_age_secs` is what makes the agent treat this as break-glass at
1166 // all (`parse_keyring` maps it to `KeyPolicy::break_glass`, which is
1167 // what turns auditing on). Emitting `audit_every_use` too would put a
1168 // field in the operator's file that the agent ignores — adjustable in
1169 // appearance, fixed in fact.
1170 let key = generate_keypair().unwrap();
1171 let entry = break_glass_keyring_entry(
1172 "break-glass-20260730",
1173 &key.verifying_key(),
1174 "break-glass",
1175 Duration::from_secs(900),
1176 );
1177 assert_eq!(entry["kid"], "break-glass-20260730");
1178 assert_eq!(entry["max_age_secs"], 900);
1179 assert_eq!(entry["public_key"], encode_public(&key.verifying_key()));
1180 assert!(
1181 entry.get("audit_every_use").is_none(),
1182 "must not print a field the agent overrides: {entry}"
1183 );
1184 }
1185
1186 #[test]
1187 fn two_generated_keys_differ() {
1188 // Cheap guard against a seeding mistake that returns a constant —
1189 // which would make every backend in existence share one key.
1190 let a = generate_keypair().unwrap();
1191 let b = generate_keypair().unwrap();
1192 assert_ne!(a.to_bytes(), b.to_bytes());
1193 }
1194
1195 #[test]
1196 fn a_malformed_secret_is_rejected_with_its_length() {
1197 assert!(decode_secret("not base64!!").is_err());
1198 let short = base64_encode(&[0u8; 31]);
1199 let err = decode_secret(&short).unwrap_err();
1200 assert!(
1201 err.contains("31"),
1202 "the error should name the length: {err}"
1203 );
1204 }
1205
1206 #[test]
1207 fn the_emitted_keyring_entry_is_what_the_agent_parses() {
1208 // The generator prints this for an operator to distribute. It has to
1209 // match `kanade-agent`'s `parse_keyring` shape exactly — a hand-fixed
1210 // entry that fails to parse takes the entire ring with it, and at
1211 // stage 3 an empty ring rejects every command on that machine.
1212 let key = generate_keypair().unwrap();
1213 let entry = keyring_entry("backend-20260728", &key.verifying_key(), "backend");
1214 assert_eq!(entry["kid"], "backend-20260728");
1215 assert_eq!(entry["label"], "backend");
1216 let pk = entry["public_key"]
1217 .as_str()
1218 .expect("public_key is a string");
1219 assert_eq!(pk, encode_public(&key.verifying_key()));
1220 // 32 bytes base64-encodes to 44 chars with padding.
1221 assert_eq!(pk.len(), 44);
1222 }
1223}