Skip to main content

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
190/// Why a message was not accepted as backend-authored.
191///
192/// Deliberately distinguishes "carries no signature" from every other case.
193/// During stages 1–2 of the rollout `Unsigned` is expected and benign, while
194/// the rest mean something is wrong — conflating them would hide a real
195/// failure inside a normal one for the whole migration window.
196#[derive(Debug, Clone, PartialEq, Eq)]
197pub enum VerifyError {
198    /// No signature headers at all. Normal until enforcement is switched on.
199    Unsigned,
200    /// Signed, but the `kid` is not on this agent's ring.
201    ///
202    /// The operationally dangerous case: an agent that never received a new
203    /// key looks, from the operator's side, exactly like a backend that is not
204    /// sending commands — and a mid-rotation fleet is full of agents in that
205    /// state. Callers must surface this, not just log it locally.
206    UnknownKid { kid: String },
207    /// Signed with an algorithm this build does not implement.
208    UnsupportedAlg { alg: String },
209    /// Signature header present but not decodable as a signature.
210    Malformed(String),
211    /// Cryptographically invalid for the bytes received.
212    BadSignature { kid: String },
213    /// Valid, by a key whose policy bounds how old a signature may be, and
214    /// this one is older. Distinct from [`VerifyError::BadSignature`] because
215    /// the signature is genuine — what failed is the policy, and the two want
216    /// different responses.
217    Stale {
218        kid: String,
219        age_ms: i64,
220        max_age_ms: u128,
221    },
222}
223
224impl std::fmt::Display for VerifyError {
225    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
226        match self {
227            VerifyError::Unsigned => write!(f, "no signature"),
228            VerifyError::UnknownKid { kid } => {
229                write!(
230                    f,
231                    "signed by unknown key id {kid} — is this agent's keyring current?"
232                )
233            }
234            VerifyError::UnsupportedAlg { alg } => {
235                write!(f, "unsupported signature algorithm {alg}")
236            }
237            VerifyError::Malformed(e) => write!(f, "malformed signature: {e}"),
238            VerifyError::BadSignature { kid } => {
239                write!(f, "signature by {kid} does not match these bytes")
240            }
241            VerifyError::Stale {
242                kid,
243                age_ms,
244                max_age_ms,
245            } => write!(
246                f,
247                "signature by {kid} is {age_ms}ms old, past its {max_age_ms}ms bound"
248            ),
249        }
250    }
251}
252
253impl std::error::Error for VerifyError {}
254
255/// A verified message: which key vouched for it, and under what policy.
256#[derive(Debug, Clone, PartialEq, Eq)]
257pub struct Verified<'a> {
258    pub kid: &'a str,
259    pub policy: &'a KeyPolicy,
260}
261
262/// The signature headers carried alongside a message body.
263///
264/// Extracted from the transport by the caller so this module stays free of a
265/// NATS dependency and is testable without a broker.
266#[derive(Debug, Clone, Default, PartialEq, Eq)]
267pub struct SigHeaders {
268    pub sig_b64: Option<String>,
269    pub kid: Option<String>,
270    pub alg: Option<String>,
271    /// Decimal milliseconds since the Unix epoch, as sent. Parsed rather than
272    /// trusted — it is covered by the signature, so a value that does not
273    /// reconstruct the signed material simply fails verification.
274    pub at_ms: Option<String>,
275}
276
277impl SigHeaders {
278    /// True only when the message makes **no signing claim at all**.
279    ///
280    /// Any one of these headers means the sender is asserting the message is
281    /// signed, so a partial set is a broken claim rather than an absent one.
282    /// `alg` counts for the same reason `kid` does: the rule has to be "no
283    /// signing headers at all", not "none of the two I happened to think of",
284    /// or stripping whichever header is unchecked reclassifies a malformed
285    /// message as an unsigned one — and unsigned is the accepted case for the
286    /// whole of stages 1-2.
287    pub fn is_absent(&self) -> bool {
288        self.sig_b64.is_none() && self.kid.is_none() && self.alg.is_none() && self.at_ms.is_none()
289    }
290}
291
292/// Verify `body` against the signature headers using `ring`.
293///
294/// Verification is over the **exact received bytes**; deserialization happens
295/// afterwards, at the caller. That ordering is what removes canonicalisation
296/// from the problem — there is no need for serde to produce byte-identical
297/// output on both sides, only for the bytes to arrive unchanged.
298pub fn verify<'a>(
299    ring: &'a KeyRing,
300    body: &[u8],
301    headers: &SigHeaders,
302    now_ms: i64,
303) -> Result<Verified<'a>, VerifyError> {
304    if headers.is_absent() {
305        return Err(VerifyError::Unsigned);
306    }
307    // A signature with no kid cannot be attributed, so it is not "unsigned" —
308    // it is a signed message we cannot route to a key.
309    let kid = headers
310        .kid
311        .as_deref()
312        .ok_or_else(|| VerifyError::Malformed("signature without a key id".into()))?;
313    let sig_b64 = headers
314        .sig_b64
315        .as_deref()
316        .ok_or_else(|| VerifyError::Malformed("key id without a signature".into()))?;
317    let at_raw = headers
318        .at_ms
319        .as_deref()
320        .ok_or_else(|| VerifyError::Malformed("signature without a signing time".into()))?;
321    let at_ms: i64 = at_raw
322        .parse()
323        .map_err(|_| VerifyError::Malformed(format!("signing time {at_raw} is not a number")))?;
324
325    // Absent alg means the original single-algorithm shape; anything else must
326    // match exactly rather than being guessed at.
327    if let Some(alg) = headers.alg.as_deref()
328        && alg != ALG_ED25519
329    {
330        return Err(VerifyError::UnsupportedAlg {
331            alg: alg.to_owned(),
332        });
333    }
334
335    // The kid is a key-selection hint and is NOT covered by the signature.
336    // That is safe: rewriting it can only select a key under which
337    // verification fails, never make an invalid signature pass. The signing
338    // time is the opposite case and IS covered — see `signed_material`.
339    let (ring_kid, key, policy) = ring.get(kid).ok_or_else(|| VerifyError::UnknownKid {
340        kid: kid.to_owned(),
341    })?;
342
343    let raw = base64_decode(sig_b64).map_err(VerifyError::Malformed)?;
344    let sig = Signature::from_slice(&raw).map_err(|e| VerifyError::Malformed(e.to_string()))?;
345    key.verify(&signed_material(at_ms, body), &sig)
346        .map_err(|_| VerifyError::BadSignature {
347            kid: kid.to_owned(),
348        })?;
349
350    // Freshness is checked only AFTER the signature holds, so a stale verdict
351    // is always about a genuine message. Checking it first would let anyone
352    // provoke a `Stale` report by sending garbage with an old timestamp.
353    if let Some(max_age) = policy.max_age {
354        let age_ms = now_ms - at_ms;
355        let max_age_ms = max_age.as_millis();
356        // Compared in i128 rather than casting the bound down to i64. A
357        // `max_age_secs` large enough to overflow the cast is nonsense config
358        // rather than an attack (the registry holding it is ACL'd), but the
359        // truncation would silently turn a bound into its opposite — a
360        // negative limit that nothing can satisfy, or one so large the key is
361        // effectively unbounded — and `-(x as i64)` can panic outright on
362        // i64::MIN in a debug build. i128 holds every value `Duration::as_millis`
363        // can produce, so there is nothing left to get wrong.
364        let age = age_ms as i128;
365        let bound = max_age_ms as i128;
366        // A signature from the future is not "fresh" — it is a clock that
367        // disagrees, and treating it as valid would let a skewed or hostile
368        // signer mint credentials that outlive the bound. Bound both ends.
369        if age > bound || age < -bound {
370            return Err(VerifyError::Stale {
371                kid: kid.to_owned(),
372                age_ms,
373                max_age_ms,
374            });
375        }
376    }
377
378    Ok(Verified {
379        kid: ring_kid,
380        policy,
381    })
382}
383
384/// Sign `body`, producing the headers to publish alongside it.
385///
386/// Lives here rather than in the backend so the signing and verifying halves
387/// cannot drift — a round-trip test in this module covers both at once.
388pub fn sign(key: &SigningKey, kid: &str, body: &[u8], at_ms: i64) -> SigHeaders {
389    let sig = key.sign(&signed_material(at_ms, body));
390    SigHeaders {
391        sig_b64: Some(base64_encode(&sig.to_bytes())),
392        kid: Some(kid.to_owned()),
393        alg: Some(ALG_ED25519.to_owned()),
394        at_ms: Some(at_ms.to_string()),
395    }
396}
397
398/// The signing half, bound to the id agents know it by.
399///
400/// The key and its `kid` are only meaningful together, so nothing here hands
401/// out one without the other. Signing under an id whose public half agents
402/// hold for a *different* key produces `command_signature_invalid` on every
403/// machine at once — which reads as a fleet-wide forgery, not as the
404/// misconfiguration it is. Any API that lets the two be supplied separately is
405/// a way to reach that state, and `resolve_kid` on the generating side already
406/// refuses the other way in (two keys sharing one id).
407pub struct Signer {
408    key: SigningKey,
409    kid: String,
410}
411
412impl Signer {
413    pub fn new(key: SigningKey, kid: impl Into<String>) -> Self {
414        Self {
415            key,
416            kid: kid.into(),
417        }
418    }
419
420    /// Build from the encoded secret as it rests in the registry or the
421    /// environment, rejecting an empty `kid` rather than signing under one.
422    ///
423    /// An empty id is not a cosmetic problem: `Kanade-Sig-Kid: ""` matches no
424    /// keyring entry, so every agent reports `command_signature_unknown_key` —
425    /// the signal that is supposed to mean "this agent missed a rotation".
426    /// Producing it from a backend-side typo would train operators to ignore
427    /// the one alarm the rotation procedure depends on.
428    pub fn from_secret(secret: &str, kid: &str) -> Result<Self, String> {
429        if kid.trim().is_empty() {
430            return Err("the signing key id is empty".to_string());
431        }
432        Ok(Self::new(decode_secret(secret)?, kid))
433    }
434
435    pub fn kid(&self) -> &str {
436        &self.kid
437    }
438
439    pub fn verifying_key(&self) -> VerifyingKey {
440        self.key.verifying_key()
441    }
442
443    /// Sign `body` as of `at_ms`, yielding the headers to publish with it.
444    pub fn headers(&self, body: &[u8], at_ms: i64) -> SigHeaders {
445        sign(&self.key, &self.kid, body, at_ms)
446    }
447}
448
449/// Hand-written so the private key cannot reach a log line.
450///
451/// `SigningKey` derives `Debug` and prints its bytes, so a derived impl here
452/// would put the fleet's crown jewel into any `tracing` call that formats the
453/// struct — including the ones nobody writes deliberately, like a `#[derive(
454/// Debug)]` on an enclosing type.
455impl std::fmt::Debug for Signer {
456    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
457        f.debug_struct("Signer").field("kid", &self.kid).finish()
458    }
459}
460
461/// Registry subkey + value holding the backend's **private** signing key.
462///
463/// Lives beside `StaticToken` / `JwtSecret` in the key `deploy-backend.ps1`
464/// already hardens to SYSTEM + Administrators. Registry ACLs are per-key, not
465/// per-value, so a value written into that key inherits the protection — which
466/// is why the writer must refuse to *create* the key: creating it would
467/// produce an unhardened one and leave the signing key world-readable.
468pub const REG_BACKEND_SUBKEY: &str = r"SOFTWARE\kanade\backend";
469pub const REG_SIGNING_KEY: &str = "CommandSigningKey";
470/// Registry value holding the `kid` that names the key beside it.
471///
472/// Persisted rather than re-derived. The signing path needs it to fill
473/// `Kanade-Sig-Kid`, and it is the operator's choice — re-deriving a date
474/// stamp at signing time would produce a different id than the one already
475/// distributed to agents whenever a key is generated on one day and first used
476/// on another. An id that disagrees with the fleet's keyring is
477/// indistinguishable, from the agent's side, from an unknown signer.
478pub const REG_SIGNING_KID: &str = "CommandSigningKid";
479
480/// Mint a fresh signing keypair.
481pub fn generate_keypair() -> Result<SigningKey, String> {
482    // Seeded from the OS CSPRNG directly rather than through
483    // `SigningKey::generate`, which wants a `rand_core` RNG — and this
484    // workspace carries three incompatible `rand_core` majors transitively.
485    // Filling 32 bytes sidesteps the version pairing entirely, and the seed
486    // *is* the key, so nothing is lost.
487    let mut seed = [0u8; 32];
488    getrandom::fill(&mut seed).map_err(|e| format!("OS randomness unavailable: {e}"))?;
489    Ok(SigningKey::from_bytes(&seed))
490}
491
492/// Base64 of the 32-byte seed. This is the secret; it is written to the
493/// registry and never printed by any code path that logs.
494pub fn encode_secret(key: &SigningKey) -> String {
495    base64_encode(&key.to_bytes())
496}
497
498pub fn decode_secret(raw: &str) -> Result<SigningKey, String> {
499    let bytes = base64_decode(raw)?;
500    let arr: [u8; 32] = bytes
501        .as_slice()
502        .try_into()
503        .map_err(|_| format!("signing key must be 32 bytes, got {}", bytes.len()))?;
504    Ok(SigningKey::from_bytes(&arr))
505}
506
507pub fn encode_public(key: &VerifyingKey) -> String {
508    base64_encode(key.as_bytes())
509}
510
511/// The JSON object an agent's `CommandKeys` array holds for this key.
512///
513/// Emitted by the generator so the operator distributes a value that is
514/// correct by construction rather than assembling it by hand — the shape is
515/// parsed by `kanade-agent`'s `parse_keyring`, and a hand-built entry that
516/// fails to parse takes the whole ring with it.
517pub fn keyring_entry(kid: &str, key: &VerifyingKey, label: &str) -> serde_json::Value {
518    serde_json::json!({
519        "kid": kid,
520        "public_key": encode_public(key),
521        "label": label,
522    })
523}
524
525fn base64_encode(bytes: &[u8]) -> String {
526    use base64::Engine;
527    base64::engine::general_purpose::STANDARD.encode(bytes)
528}
529
530fn base64_decode(s: &str) -> Result<Vec<u8>, String> {
531    use base64::Engine;
532    base64::engine::general_purpose::STANDARD
533        .decode(s)
534        .map_err(|e| e.to_string())
535}
536
537#[cfg(test)]
538mod tests {
539    use super::*;
540
541    /// A fixed "now" so the tests never depend on wall-clock time.
542    const NOW: i64 = 1_700_000_000_000;
543
544    fn keypair(seed: u8) -> (SigningKey, VerifyingKey) {
545        let sk = SigningKey::from_bytes(&[seed; 32]);
546        let vk = sk.verifying_key();
547        (sk, vk)
548    }
549
550    fn ring_with(kid: &str, vk: VerifyingKey) -> KeyRing {
551        let mut r = KeyRing::new();
552        r.insert(kid, vk, KeyPolicy::backend("backend"));
553        r
554    }
555
556    #[test]
557    fn round_trip_accepts_the_bytes_that_were_signed() {
558        let (sk, vk) = keypair(1);
559        let ring = ring_with("backend-1", vk);
560        let body = br#"{"id":"job","request_id":"r1"}"#;
561
562        let headers = sign(&sk, "backend-1", body, NOW);
563        let ok = verify(&ring, body, &headers, NOW).expect("verifies");
564        assert_eq!(ok.kid, "backend-1");
565        assert_eq!(ok.policy.label, "backend");
566    }
567
568    #[test]
569    fn a_single_flipped_byte_fails() {
570        let (sk, vk) = keypair(1);
571        let ring = ring_with("backend-1", vk);
572        let headers = sign(&sk, "backend-1", b"run this", NOW);
573        // The whole point: bytes the backend did not author must not execute.
574        assert_eq!(
575            verify(&ring, b"run thit", &headers, NOW),
576            Err(VerifyError::BadSignature {
577                kid: "backend-1".into()
578            })
579        );
580    }
581
582    #[test]
583    fn a_forged_command_from_another_key_fails() {
584        // The #1155 attacker: holds a NATS credential, can place bytes on a
585        // command subject, and signs with a key of their own.
586        let (_, backend_vk) = keypair(1);
587        let (attacker_sk, _) = keypair(9);
588        let ring = ring_with("backend-1", backend_vk);
589
590        let body = b"malicious";
591        // Signed with the attacker's key but claiming the backend's kid — the
592        // kid being outside the signature buys them nothing.
593        let headers = sign(&attacker_sk, "backend-1", body, NOW);
594        assert_eq!(
595            verify(&ring, body, &headers, NOW),
596            Err(VerifyError::BadSignature {
597                kid: "backend-1".into()
598            })
599        );
600    }
601
602    #[test]
603    fn unsigned_is_distinct_from_every_failure() {
604        let (_, vk) = keypair(1);
605        let ring = ring_with("backend-1", vk);
606        // Stages 1–2 deliver unsigned commands as a matter of course. If this
607        // collapsed into the same error as a bad signature, a real forgery
608        // would be indistinguishable from normal traffic for the whole
609        // migration window.
610        assert_eq!(
611            verify(&ring, b"anything", &SigHeaders::default(), NOW),
612            Err(VerifyError::Unsigned)
613        );
614    }
615
616    #[test]
617    fn an_unknown_kid_is_its_own_error() {
618        let (sk, vk) = keypair(1);
619        let ring = ring_with("backend-1", vk);
620        let headers = sign(&sk, "backend-2", b"body", NOW);
621        // The mid-rotation state: correctly signed, but this agent has not
622        // been given the new key. Reported distinctly because "your keyring is
623        // stale" and "someone forged this" need opposite responses.
624        assert_eq!(
625            verify(&ring, b"body", &headers, NOW),
626            Err(VerifyError::UnknownKid {
627                kid: "backend-2".into()
628            })
629        );
630    }
631
632    #[test]
633    fn rotation_is_two_kids_on_one_ring() {
634        // Rotation shares its implementation with multi-signer rather than
635        // being a separate mechanism — this is that claim, as a test.
636        let (old_sk, old_vk) = keypair(1);
637        let (new_sk, new_vk) = keypair(2);
638        let mut ring = ring_with("backend-1", old_vk);
639        ring.insert("backend-2", new_vk, KeyPolicy::backend("backend (new)"));
640
641        for (sk, kid) in [(&old_sk, "backend-1"), (&new_sk, "backend-2")] {
642            let headers = sign(sk, kid, b"during the window", NOW);
643            assert_eq!(
644                verify(&ring, b"during the window", &headers, NOW)
645                    .unwrap()
646                    .kid,
647                kid
648            );
649        }
650    }
651
652    #[test]
653    fn policies_are_per_key_not_per_ring() {
654        // Without this, "multiple signers" means "more keys that can do
655        // everything", which is worse than one key.
656        let (_, backend_vk) = keypair(1);
657        let (bg_sk, bg_vk) = keypair(3);
658        let mut ring = ring_with("backend-1", backend_vk);
659        ring.insert(
660            "break-glass",
661            bg_vk,
662            KeyPolicy::break_glass("break-glass", Duration::from_secs(300)),
663        );
664
665        let headers = sign(&bg_sk, "break-glass", b"emergency", NOW);
666        let ok = verify(&ring, b"emergency", &headers, NOW).unwrap();
667        assert!(
668            ok.policy.audit_every_use,
669            "break-glass use must be recorded"
670        );
671        assert_eq!(ok.policy.max_age, Some(Duration::from_secs(300)));
672
673        // The ordinary signer keeps the ordinary policy.
674        let (sk, vk) = keypair(1);
675        let mut r2 = KeyRing::new();
676        r2.insert("backend-1", vk, KeyPolicy::backend("backend"));
677        let h = sign(&sk, "backend-1", b"routine", NOW);
678        assert!(
679            !verify(&r2, b"routine", &h, NOW)
680                .unwrap()
681                .policy
682                .audit_every_use
683        );
684    }
685
686    #[test]
687    fn partial_or_unreadable_headers_are_rejected_rather_than_ignored() {
688        let (_, vk) = keypair(1);
689        let ring = ring_with("backend-1", vk);
690
691        // A signature with no kid cannot be attributed. Treating it as
692        // "unsigned" would let an attacker strip the kid to slip a message
693        // through the stage-1/2 accept-unsigned path.
694        let no_kid = SigHeaders {
695            sig_b64: Some("AAAA".into()),
696            kid: None,
697            alg: None,
698            at_ms: None,
699        };
700        assert!(matches!(
701            verify(&ring, b"x", &no_kid, NOW),
702            Err(VerifyError::Malformed(_))
703        ));
704
705        // A kid with no signature is equally not "unsigned".
706        let no_sig = SigHeaders {
707            sig_b64: None,
708            kid: Some("backend-1".into()),
709            alg: None,
710            at_ms: None,
711        };
712        assert!(matches!(
713            verify(&ring, b"x", &no_sig, NOW),
714            Err(VerifyError::Malformed(_))
715        ));
716
717        // Only the algorithm header, with nothing to verify. It still claims
718        // to be signed, so it must not fall through to the accept-unsigned
719        // path: the rule is "no signing headers at all", not "none of the two
720        // that carry the signature".
721        let alg_only = SigHeaders {
722            sig_b64: None,
723            kid: None,
724            alg: Some(ALG_ED25519.into()),
725            at_ms: None,
726        };
727        assert!(matches!(
728            verify(&ring, b"x", &alg_only, NOW),
729            Err(VerifyError::Malformed(_))
730        ));
731
732        // Not base64 at all.
733        let junk = SigHeaders {
734            sig_b64: Some("!!!not base64!!!".into()),
735            kid: Some("backend-1".into()),
736            alg: None,
737            at_ms: Some(NOW.to_string()),
738        };
739        assert!(matches!(
740            verify(&ring, b"x", &junk, NOW),
741            Err(VerifyError::Malformed(_))
742        ));
743    }
744
745    #[test]
746    fn an_unexpected_algorithm_is_refused_not_assumed() {
747        let (sk, vk) = keypair(1);
748        let ring = ring_with("backend-1", vk);
749        let mut headers = sign(&sk, "backend-1", b"body", NOW);
750        headers.alg = Some("hmac-sha256".into());
751        assert_eq!(
752            verify(&ring, b"body", &headers, NOW),
753            Err(VerifyError::UnsupportedAlg {
754                alg: "hmac-sha256".into()
755            })
756        );
757    }
758
759    #[test]
760    fn an_absent_alg_header_means_the_original_shape() {
761        // Forward compatibility in the other direction: a signer that predates
762        // the alg header must still verify.
763        let (sk, vk) = keypair(1);
764        let ring = ring_with("backend-1", vk);
765        let mut headers = sign(&sk, "backend-1", b"body", NOW);
766        headers.alg = None;
767        assert!(verify(&ring, b"body", &headers, NOW).is_ok());
768    }
769
770    #[test]
771    fn the_signing_time_is_covered_by_the_signature() {
772        // The asymmetry with `kid`: rewriting the timestamp must not verify,
773        // or a captured message could be replayed by simply making it look
774        // fresh. This is the whole reason `at` sits inside the signed
775        // material.
776        let (sk, vk) = keypair(1);
777        let ring = ring_with("backend-1", vk);
778        let mut headers = sign(&sk, "backend-1", b"body", NOW);
779        headers.at_ms = Some((NOW + 1).to_string());
780        assert_eq!(
781            verify(&ring, b"body", &headers, NOW),
782            Err(VerifyError::BadSignature {
783                kid: "backend-1".into()
784            })
785        );
786    }
787
788    #[test]
789    fn the_ordinary_signer_accepts_a_week_old_command() {
790        // Not a nicety: the agent's JetStream replay redelivers the retained
791        // command per subject for 7 days, so an agent reconnecting after a
792        // week legitimately receives week-old commands. A freshness bound on
793        // the backend key would reject exactly that traffic.
794        let (sk, vk) = keypair(1);
795        let ring = ring_with("backend-1", vk);
796        let week = 7 * 24 * 60 * 60 * 1000;
797        let headers = sign(&sk, "backend-1", b"scheduled job", NOW - week);
798        assert!(verify(&ring, b"scheduled job", &headers, NOW).is_ok());
799    }
800
801    #[test]
802    fn a_bounded_key_rejects_an_old_signature() {
803        let (sk, vk) = keypair(3);
804        let mut ring = KeyRing::new();
805        ring.insert(
806            "break-glass",
807            vk,
808            KeyPolicy::break_glass("break-glass", Duration::from_secs(300)),
809        );
810
811        // Inside the window.
812        let fresh = sign(&sk, "break-glass", b"emergency", NOW - 60_000);
813        assert!(verify(&ring, b"emergency", &fresh, NOW).is_ok());
814
815        // Past it. This is the case that stops a first-boot agent executing a
816        // week-old emergency command: its dedup cache is empty, so freshness
817        // is the only thing left.
818        let old = sign(&sk, "break-glass", b"emergency", NOW - 600_000);
819        assert_eq!(
820            verify(&ring, b"emergency", &old, NOW),
821            Err(VerifyError::Stale {
822                kid: "break-glass".into(),
823                age_ms: 600_000,
824                max_age_ms: 300_000,
825            })
826        );
827    }
828
829    #[test]
830    fn a_signature_from_the_future_is_not_fresh() {
831        // A clock that disagrees, or a signer trying to mint something that
832        // outlives its bound. Bounding only the old side would let a
833        // far-future timestamp stay valid indefinitely.
834        let (sk, vk) = keypair(3);
835        let mut ring = KeyRing::new();
836        ring.insert(
837            "break-glass",
838            vk,
839            KeyPolicy::break_glass("break-glass", Duration::from_secs(300)),
840        );
841        let ahead = sign(&sk, "break-glass", b"emergency", NOW + 3_600_000);
842        assert!(matches!(
843            verify(&ring, b"emergency", &ahead, NOW),
844            Err(VerifyError::Stale { .. })
845        ));
846        // Modest skew inside the window still passes, so a machine a few
847        // seconds ahead is not locked out.
848        let skewed = sign(&sk, "break-glass", b"emergency", NOW + 5_000);
849        assert!(verify(&ring, b"emergency", &skewed, NOW).is_ok());
850    }
851
852    #[test]
853    fn freshness_is_only_judged_after_the_signature_holds() {
854        // Otherwise anyone could provoke a `Stale` report — which at stage 3
855        // is a rejection an operator has to investigate — by sending garbage
856        // with an old timestamp.
857        let (_, vk) = keypair(3);
858        let mut ring = KeyRing::new();
859        ring.insert(
860            "break-glass",
861            vk,
862            KeyPolicy::break_glass("break-glass", Duration::from_secs(300)),
863        );
864        let forged = SigHeaders {
865            sig_b64: Some(base64_encode(&[7u8; 64])),
866            kid: Some("break-glass".into()),
867            alg: Some(ALG_ED25519.into()),
868            at_ms: Some((NOW - 600_000).to_string()),
869        };
870        assert_eq!(
871            verify(&ring, b"x", &forged, NOW),
872            Err(VerifyError::BadSignature {
873                kid: "break-glass".into()
874            })
875        );
876    }
877
878    #[test]
879    fn a_missing_or_unparseable_signing_time_is_malformed() {
880        let (sk, vk) = keypair(1);
881        let ring = ring_with("backend-1", vk);
882
883        let mut no_at = sign(&sk, "backend-1", b"body", NOW);
884        no_at.at_ms = None;
885        assert!(matches!(
886            verify(&ring, b"body", &no_at, NOW),
887            Err(VerifyError::Malformed(_))
888        ));
889
890        let mut junk_at = sign(&sk, "backend-1", b"body", NOW);
891        junk_at.at_ms = Some("yesterday".into());
892        assert!(matches!(
893            verify(&ring, b"body", &junk_at, NOW),
894            Err(VerifyError::Malformed(_))
895        ));
896
897        // And a lone `at` header still counts as a signing claim rather than
898        // an absent one.
899        let at_only = SigHeaders {
900            sig_b64: None,
901            kid: None,
902            alg: None,
903            at_ms: Some(NOW.to_string()),
904        };
905        assert!(matches!(
906            verify(&ring, b"body", &at_only, NOW),
907            Err(VerifyError::Malformed(_))
908        ));
909    }
910
911    #[test]
912    fn an_absurd_bound_neither_panics_nor_inverts() {
913        // `max_age_secs` reaches this from JSON with no upper bound. A value
914        // this large is a typo rather than an attack, but the old `as i64`
915        // cast would have truncated it into a negative limit that nothing can
916        // satisfy — turning "almost never expires" into "always expired" —
917        // and could panic on the negation in a debug build.
918        let (sk, vk) = keypair(5);
919        let mut ring = KeyRing::new();
920        ring.insert(
921            "silly",
922            vk,
923            KeyPolicy::break_glass("silly", Duration::from_secs(u64::MAX / 1000)),
924        );
925        let headers = sign(&sk, "silly", b"body", NOW - 10_000);
926        assert!(
927            verify(&ring, b"body", &headers, NOW).is_ok(),
928            "an enormous bound must read as permissive, not as inverted"
929        );
930    }
931
932    #[test]
933    fn a_generated_key_round_trips_through_its_encoded_secret() {
934        // The registry stores the encoded secret; if this did not round trip,
935        // a backend would come back from a restart unable to sign and every
936        // agent would start reporting unsigned traffic.
937        let key = generate_keypair().expect("OS randomness");
938        let restored = decode_secret(&encode_secret(&key)).expect("decodes");
939        assert_eq!(restored.to_bytes(), key.to_bytes());
940
941        // And the restored key produces signatures the original's public half
942        // accepts — the property that actually matters across a restart.
943        let ring = ring_with("backend-1", key.verifying_key());
944        let headers = sign(&restored, "backend-1", b"after a restart", NOW);
945        assert!(verify(&ring, b"after a restart", &headers, NOW).is_ok());
946    }
947
948    #[test]
949    fn a_signer_built_from_the_stored_secret_verifies_against_its_own_ring() {
950        // The whole backend-side path in one assertion: the encoded secret as
951        // it rests in the registry, through `Signer`, out as headers, verified
952        // by the public half an agent was given.
953        let key = generate_keypair().unwrap();
954        let signer = Signer::from_secret(&encode_secret(&key), "backend-1").expect("builds");
955        let ring = ring_with("backend-1", key.verifying_key());
956
957        let body = br#"{"id":"job","request_id":"r1"}"#;
958        let headers = signer.headers(body, NOW);
959        assert_eq!(verify(&ring, body, &headers, NOW).unwrap().kid, "backend-1");
960    }
961
962    #[test]
963    fn a_signer_refuses_an_empty_kid_rather_than_signing_under_one() {
964        // `Kanade-Sig-Kid: ""` matches no keyring entry, so every agent would
965        // report `unknown_key` — the alarm that is supposed to mean a rotation
966        // went wrong. A backend typo must not be able to raise it fleet-wide.
967        let secret = encode_secret(&generate_keypair().unwrap());
968        assert!(Signer::from_secret(&secret, "").is_err());
969        assert!(Signer::from_secret(&secret, "   ").is_err());
970        // And a bad secret is still rejected on its own terms.
971        assert!(Signer::from_secret("not base64!!", "backend-1").is_err());
972    }
973
974    #[test]
975    fn debugging_a_signer_never_prints_the_key() {
976        // `SigningKey` derives Debug and prints its bytes, so a derived impl
977        // would leak the fleet's crown jewel into any log line that formats an
978        // enclosing struct.
979        let key = generate_keypair().unwrap();
980        let signer = Signer::new(key.clone(), "backend-1");
981        // Pinned exactly rather than by absence: a field added later would
982        // otherwise have to be *remembered* to be excluded, and the failure
983        // mode is a secret in a log file.
984        assert_eq!(format!("{signer:?}"), r#"Signer { kid: "backend-1" }"#);
985        assert!(!format!("{signer:?}").contains(&encode_secret(&key)));
986    }
987
988    #[test]
989    fn two_generated_keys_differ() {
990        // Cheap guard against a seeding mistake that returns a constant —
991        // which would make every backend in existence share one key.
992        let a = generate_keypair().unwrap();
993        let b = generate_keypair().unwrap();
994        assert_ne!(a.to_bytes(), b.to_bytes());
995    }
996
997    #[test]
998    fn a_malformed_secret_is_rejected_with_its_length() {
999        assert!(decode_secret("not base64!!").is_err());
1000        let short = base64_encode(&[0u8; 31]);
1001        let err = decode_secret(&short).unwrap_err();
1002        assert!(
1003            err.contains("31"),
1004            "the error should name the length: {err}"
1005        );
1006    }
1007
1008    #[test]
1009    fn the_emitted_keyring_entry_is_what_the_agent_parses() {
1010        // The generator prints this for an operator to distribute. It has to
1011        // match `kanade-agent`'s `parse_keyring` shape exactly — a hand-fixed
1012        // entry that fails to parse takes the entire ring with it, and at
1013        // stage 3 an empty ring rejects every command on that machine.
1014        let key = generate_keypair().unwrap();
1015        let entry = keyring_entry("backend-20260728", &key.verifying_key(), "backend");
1016        assert_eq!(entry["kid"], "backend-20260728");
1017        assert_eq!(entry["label"], "backend");
1018        let pk = entry["public_key"]
1019            .as_str()
1020            .expect("public_key is a string");
1021        assert_eq!(pk, encode_public(&key.verifying_key()));
1022        // 32 bytes base64-encodes to 44 chars with padding.
1023        assert_eq!(pk.len(), 44);
1024    }
1025}