Skip to main content

plexus_core/plexus/
peer_token.rs

1//! DYNAUTH-12 (D3, TM-4) · peer tokens: what a service signs for the peer a
2//! call is forwarded to, so the peer can check what it is told rather than
3//! believe who told it.
4//!
5//! A token is a compact JWS (RFC 7515) of a JWT (RFC 7519), signed EdDSA
6//! (Ed25519, RFC 8037), header `{"alg":"EdDSA","typ":"plexus-peer+jwt","kid"}`:
7//!
8//! | claim | what |
9//! | -- | -- |
10//! | `iss` | the issuing service's key, `key:<hex>` |
11//! | `sub` | the original caller (the first hop's admitted principal) |
12//! | `act` | the actor chain, nearest first, nested as RFC 8693 §4.1 nests it |
13//! | `aud` | exactly one peer: its key (`key:<hex>`), or `pipe:<name>` for a child on the issuer's own pipe |
14//! | `scope` | space-separated `grant@scope` entries: the caller's reach ∩ the peer's needs ∩ consent |
15//! | `cnf.jkt` | the RFC 7638 thumbprint of the peer's Ed25519 key (RFC 7800, RFC 9449 §6); absent for a pipe |
16//! | `call`, `method` | the forwarded call's id and the method it names |
17//! | `jti`, `iat`, `exp` | unique; `exp − iat ≤ 60 s` |
18//!
19//! **Verifying** ([`Verifier`]): `alg` is pinned to EdDSA (never read from the
20//! token to choose an algorithm, RFC 8725 §3.1), `typ` must be
21//! `plexus-peer+jwt` (§3.11), `kid` must name a key the verifier trusts (a
22//! JWKS it was given or fetched, `dyn.jwks`), the signature is checked with
23//! `verify_strict`, `aud` must be the verifier's own, `iat`/`exp` within
24//! ±30 s of now and `exp − iat ≤ 60 s`, and a `jti` seen before is refused
25//! until its `exp` (a replay cache bounded by 60 s × the call rate).
26//!
27//! **Proof of possession** ([`prove`], [`check_proof`]): whoever *presents* a
28//! token bound to a key (`cnf.jkt`) — a remote peer calling its service back
29//! under the call the token was minted for — signs a proof with that key:
30//! a compact JWS, header `{"alg":"EdDSA","typ":"plexus-pop+jwt","jwk"}`,
31//! claims `{ath, jti, method, call, iat}` (`ath`: base64url sha256 of the
32//! token, as DPoP's, RFC 9449 §4.2). The proof's key must be the token's
33//! `cnf.jkt`, its `method` and `call` the ones it is presented for, its
34//! `iat` within ±30 s, its `jti` new. A peer on its issuer's own pipe needs
35//! no proof (D3: the pipe is the issuer's alone).
36//!
37//! **Exchange** ([`TokenIssuer::exchange`], RFC 8693 semantics): a token
38//! presented for an onward call becomes one for the next peer — the same
39//! `sub`, `act` extended by the presenter, `aud` the next peer, and a scope
40//! that is the presented one's or narrower, never wider ([`narrow`]).
41//!
42//! **Audit** (DYNAUTH-7, TM-7): every mint and exchange writes one
43//! [`AuditRecord`] — iss, sub, the actor chain, aud, scope, call, jti, exp,
44//! method — as a `tracing` event on target `plexus::audit` and to the
45//! issuer's [`TokenAudit`] sink. Never the token, never a proof.
46
47use std::collections::{BTreeMap, HashMap};
48use std::path::Path;
49use std::sync::{Arc, Mutex, RwLock};
50use std::time::{Duration, SystemTime, UNIX_EPOCH};
51
52use base64::Engine as _;
53use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey};
54use serde::{Deserialize, Serialize};
55use serde_json::{json, Value};
56use sha2::{Digest, Sha256};
57
58/// The `typ` of a peer token (RFC 8725 §3.11: explicit typing).
59pub const TOKEN_TYP: &str = "plexus-peer+jwt";
60/// The `typ` of a proof of possession.
61pub const PROOF_TYP: &str = "plexus-pop+jwt";
62/// The one algorithm: EdDSA over Ed25519 (RFC 8037).
63pub const ALG: &str = "EdDSA";
64/// A token lives at most this long (`exp − iat`), D3.
65pub const MAX_LIFETIME: Duration = Duration::from_secs(60);
66/// How far apart two clocks may be.
67pub const SKEW: Duration = Duration::from_secs(30);
68/// The method a proof of possession names to exchange a token
69/// ([`TokenIssuer::exchange`]), under the token's own `call`.
70pub const EXCHANGE: &str = "exchange";
71/// RFC 8693's identifier of the token type issued.
72pub const JWT_TOKEN_TYPE: &str = "urn:ietf:params:oauth:token-type:jwt";
73/// The context a peer's key proof at `_info` is signed over (domain
74/// separation: no other signature can be passed off as one).
75pub const KEY_PROOF_CONTEXT: &str = "plexus-peer-key/v1";
76
77fn b64(b: &[u8]) -> String {
78    base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(b)
79}
80
81fn unb64(s: &str) -> Result<Vec<u8>, TokenError> {
82    base64::engine::general_purpose::URL_SAFE_NO_PAD.decode(s).map_err(|_| TokenError::Malformed("not base64url".into()))
83}
84
85fn hex(b: &[u8]) -> String {
86    b.iter().map(|b| format!("{b:02x}")).collect()
87}
88
89/// Seconds since the epoch, now.
90pub fn now() -> u64 {
91    SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or_default()
92}
93
94/// A fresh random id (128 bits, base64url).
95fn random_id() -> String {
96    b64(uuid::Uuid::new_v4().as_bytes())
97}
98
99/// A fresh nonce (256 bits from the OS, base64url): what a mount asks a
100/// peer to sign at `_info`.
101pub fn random_nonce() -> String {
102    let mut n = [0u8; 32];
103    getrandom_02::getrandom(&mut n).expect("the OS's randomness");
104    b64(&n)
105}
106
107/// `key:<64 hex>` — the principal a key proves (spec/00's form).
108pub fn principal_of(key: &VerifyingKey) -> String {
109    format!("key:{}", hex(key.as_bytes()))
110}
111
112/// The key a `key:<64 hex>` principal names.
113pub fn key_of(principal: &str) -> Option<VerifyingKey> {
114    let h = principal.strip_prefix("key:")?;
115    if h.len() != 64 {
116        return None;
117    }
118    let mut bytes = [0u8; 32];
119    for (i, b) in bytes.iter_mut().enumerate() {
120        *b = u8::from_str_radix(h.get(2 * i..2 * i + 2)?, 16).ok()?;
121    }
122    VerifyingKey::from_bytes(&bytes).ok()
123}
124
125/// RFC 7638 thumbprint of an Ed25519 key (OKP, RFC 8037 §2):
126/// base64url(sha256(`{"crv":"Ed25519","kty":"OKP","x":"…"}`)).
127pub fn thumbprint(key: &VerifyingKey) -> String {
128    let canonical = format!(r#"{{"crv":"Ed25519","kty":"OKP","x":"{}"}}"#, b64(key.as_bytes()));
129    b64(&Sha256::digest(canonical.as_bytes()))
130}
131
132/// base64url(sha256(token)) — a proof's `ath`.
133pub fn token_hash(token: &str) -> String {
134    b64(&Sha256::digest(token.as_bytes()))
135}
136
137// ------------------------------------------------------------------ keys
138
139/// An Ed25519 key with its id (`key:<hex>`): a service's signing key, or a
140/// peer's own. `Debug` never shows the seed.
141#[derive(Clone)]
142pub struct PeerKey {
143    signing: SigningKey,
144    kid: String,
145}
146
147impl std::fmt::Debug for PeerKey {
148    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
149        f.debug_struct("PeerKey").field("kid", &self.kid).finish_non_exhaustive()
150    }
151}
152
153impl PeerKey {
154    /// A new key from the OS's randomness.
155    pub fn generate() -> Self {
156        let mut seed = [0u8; 32];
157        getrandom_02::getrandom(&mut seed).expect("the OS's randomness");
158        Self::from_seed(seed)
159    }
160
161    /// The key a 32-byte seed makes.
162    pub fn from_seed(seed: [u8; 32]) -> Self {
163        let signing = SigningKey::from_bytes(&seed);
164        let kid = principal_of(&signing.verifying_key());
165        Self { signing, kid }
166    }
167
168    /// The key in `path` (a 32-byte seed, raw or base64 — synapse's key
169    /// file), made there (0600) when there is none. A file readable by
170    /// others is refused.
171    pub fn load_or_create(path: &Path) -> Result<Self, String> {
172        let shown = path.display();
173        if !path.exists() {
174            let key = Self::generate();
175            if let Some(dir) = path.parent() {
176                std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
177            }
178            let text = base64::engine::general_purpose::STANDARD.encode(key.signing.to_bytes());
179            write_private(path, text.as_bytes()).map_err(|e| format!("the key file {shown}: {e}"))?;
180            return Ok(key);
181        }
182        #[cfg(unix)]
183        {
184            use std::os::unix::fs::PermissionsExt;
185            let mode = std::fs::metadata(path).map_err(|e| format!("the key file {shown}: {e}"))?.permissions().mode();
186            if mode & 0o077 != 0 {
187                return Err(format!("the key file {shown} is readable by others (mode {:o}); a key is kept 0600", mode & 0o777));
188            }
189        }
190        let raw = std::fs::read(path).map_err(|e| format!("the key file {shown}: {e}"))?;
191        let text: Vec<u8> = raw.iter().copied().filter(|b| !b.is_ascii_whitespace()).collect();
192        let engines = [
193            &base64::engine::general_purpose::STANDARD,
194            &base64::engine::general_purpose::URL_SAFE,
195            &base64::engine::general_purpose::STANDARD_NO_PAD,
196            &base64::engine::general_purpose::URL_SAFE_NO_PAD,
197        ];
198        let seed: [u8; 32] = engines
199            .iter()
200            .find_map(|e| e.decode(&text).ok().and_then(|b| <[u8; 32]>::try_from(b.as_slice()).ok()))
201            .or_else(|| <[u8; 32]>::try_from(raw.as_slice()).ok())
202            .ok_or_else(|| format!("the key file {shown} holds no 32-byte seed"))?;
203        Ok(Self::from_seed(seed))
204    }
205
206    /// DYNAUTH-7: write it to `path`, replacing what is there (a new file
207    /// beside it, 0600, renamed into place).
208    pub fn save(&self, path: &Path) -> Result<(), String> {
209        let tmp = path.with_extension("key.tmp");
210        let _ = std::fs::remove_file(&tmp);
211        let text = base64::engine::general_purpose::STANDARD.encode(self.signing.to_bytes());
212        write_private(&tmp, text.as_bytes()).map_err(|e| format!("{}: {e}", tmp.display()))?;
213        std::fs::rename(&tmp, path).map_err(|e| format!("{}: {e}", path.display()))
214    }
215
216    /// Its id: `key:<hex>` of its public half.
217    pub fn kid(&self) -> &str {
218        &self.kid
219    }
220
221    /// Its public half.
222    pub fn public(&self) -> VerifyingKey {
223        self.signing.verifying_key()
224    }
225
226    /// Its RFC 7638 thumbprint.
227    pub fn thumbprint(&self) -> String {
228        thumbprint(&self.public())
229    }
230
231    /// Its public half as a JWK.
232    pub fn jwk(&self) -> Jwk {
233        Jwk::of(&self.public())
234    }
235
236    /// A compact JWS of `claims` under `header` (whose `alg` this sets).
237    fn sign_compact(&self, mut header: Value, claims: &Value) -> String {
238        header["alg"] = json!(ALG);
239        let input = format!("{}.{}", b64(header.to_string().as_bytes()), b64(claims.to_string().as_bytes()));
240        let sig = self.signing.sign(input.as_bytes());
241        format!("{input}.{}", b64(&sig.to_bytes()))
242    }
243
244    /// The `_info` key proof: a signature over
245    /// `plexus-peer-key/v1\n<nonce>\n<backend>`, base64url.
246    pub fn key_proof(&self, nonce: &str, backend: &str) -> String {
247        b64(&self.signing.sign(format!("{KEY_PROOF_CONTEXT}\n{nonce}\n{backend}").as_bytes()).to_bytes())
248    }
249}
250
251/// Check a peer's `_info` key proof: `key` (`key:<hex>`) signed `nonce` and
252/// `backend` with [`PeerKey::key_proof`].
253pub fn check_key_proof(key: &str, proof: &str, nonce: &str, backend: &str) -> Result<VerifyingKey, TokenError> {
254    let vk = key_of(key).ok_or_else(|| TokenError::Malformed(format!("`{key}` is not an Ed25519 key")))?;
255    let sig = signature_of(proof)?;
256    vk.verify_strict(format!("{KEY_PROOF_CONTEXT}\n{nonce}\n{backend}").as_bytes(), &sig).map_err(|_| TokenError::Signature)?;
257    Ok(vk)
258}
259
260fn write_private(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
261    use std::io::Write;
262    let mut o = std::fs::OpenOptions::new();
263    o.write(true).create_new(true);
264    #[cfg(unix)]
265    {
266        use std::os::unix::fs::OpenOptionsExt;
267        o.mode(0o600);
268    }
269    o.open(path)?.write_all(bytes)
270}
271
272fn signature_of(s: &str) -> Result<Signature, TokenError> {
273    let bytes = unb64(s)?;
274    let arr: [u8; 64] = bytes.as_slice().try_into().map_err(|_| TokenError::Malformed("a signature is 64 bytes".into()))?;
275    Ok(Signature::from_bytes(&arr))
276}
277
278/// A public key as a JWK (RFC 8037: `kty` OKP, `crv` Ed25519).
279#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
280pub struct Jwk {
281    pub kty: String,
282    pub crv: String,
283    pub x: String,
284    #[serde(default, skip_serializing_if = "Option::is_none")]
285    pub kid: Option<String>,
286    #[serde(default, skip_serializing_if = "Option::is_none")]
287    pub alg: Option<String>,
288    #[serde(rename = "use", default, skip_serializing_if = "Option::is_none")]
289    pub use_: Option<String>,
290}
291
292impl Jwk {
293    /// `key` as a signing JWK, its `kid` its principal.
294    pub fn of(key: &VerifyingKey) -> Self {
295        Self { kty: "OKP".into(), crv: "Ed25519".into(), x: b64(key.as_bytes()), kid: Some(principal_of(key)), alg: Some(ALG.into()), use_: Some("sig".into()) }
296    }
297
298    /// The key it holds, if it is an Ed25519 one.
299    pub fn key(&self) -> Result<VerifyingKey, TokenError> {
300        if self.kty != "OKP" || self.crv != "Ed25519" || self.alg.as_deref().is_some_and(|a| a != ALG) {
301            return Err(TokenError::Algorithm(format!("a JWK of kty {} crv {}: only OKP Ed25519 (EdDSA)", self.kty, self.crv)));
302        }
303        let bytes = unb64(&self.x)?;
304        let arr: [u8; 32] = bytes.as_slice().try_into().map_err(|_| TokenError::Malformed("an Ed25519 key is 32 bytes".into()))?;
305        VerifyingKey::from_bytes(&arr).map_err(|_| TokenError::Malformed("not an Ed25519 point".into()))
306    }
307}
308
309/// A JWK Set (RFC 7517 §5): what `dyn.jwks` answers.
310#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
311pub struct Jwks {
312    pub keys: Vec<Jwk>,
313}
314
315// ------------------------------------------------------------------ claims
316
317/// One actor of the chain (RFC 8693 §4.1), the prior ones nested.
318#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
319pub struct Actor {
320    pub sub: String,
321    #[serde(default, skip_serializing_if = "Option::is_none")]
322    pub act: Option<Box<Actor>>,
323}
324
325impl Actor {
326    /// The chain, nearest first.
327    pub fn chain(&self) -> Vec<String> {
328        let mut out = vec![self.sub.clone()];
329        let mut next = self.act.as_deref();
330        while let Some(a) = next {
331            out.push(a.sub.clone());
332            next = a.act.as_deref();
333        }
334        out
335    }
336
337    /// `sub` acting, after `prior`.
338    pub fn after(sub: impl Into<String>, prior: Option<Actor>) -> Self {
339        Self { sub: sub.into(), act: prior.map(Box::new) }
340    }
341}
342
343/// The key a token is bound to (RFC 7800 `cnf`, RFC 9449 `jkt`).
344#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
345pub struct Cnf {
346    pub jkt: String,
347}
348
349/// A peer token's claims.
350#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
351pub struct PeerClaims {
352    pub iss: String,
353    pub sub: String,
354    #[serde(default, skip_serializing_if = "Option::is_none")]
355    pub act: Option<Actor>,
356    pub aud: String,
357    /// `grant@scope` entries; on the wire one space-separated string
358    /// (RFC 8693 §4.2).
359    #[serde(with = "space_separated")]
360    pub scope: Vec<String>,
361    #[serde(default, skip_serializing_if = "Option::is_none")]
362    pub cnf: Option<Cnf>,
363    pub call: String,
364    pub method: String,
365    pub jti: String,
366    pub iat: u64,
367    pub exp: u64,
368}
369
370mod space_separated {
371    use serde::{Deserialize, Deserializer, Serializer};
372    pub fn serialize<S: Serializer>(v: &[String], s: S) -> Result<S::Ok, S::Error> {
373        s.serialize_str(&v.join(" "))
374    }
375    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<String>, D::Error> {
376        let s = String::deserialize(d)?;
377        Ok(s.split(' ').filter(|x| !x.is_empty()).map(str::to_string).collect())
378    }
379}
380
381impl PeerClaims {
382    /// The actor chain, nearest first (empty when nobody acted).
383    pub fn actors(&self) -> Vec<String> {
384        self.act.as_ref().map(Actor::chain).unwrap_or_default()
385    }
386
387    /// The scopes the token holds `grant` on (`["*"]`, `["MENGER"]`, `[]`).
388    pub fn scopes_for(&self, grant: &str) -> Vec<String> {
389        self.scope.iter().filter_map(|e| e.rsplit_once('@').filter(|(g, _)| *g == grant).map(|(_, s)| s.to_string())).collect()
390    }
391}
392
393/// `grant@scope` split.
394fn entry(e: &str) -> Option<(&str, &str)> {
395    e.rsplit_once('@')
396}
397
398/// Whether `inner`'s scope lies within `outer`'s (`*` holds every one).
399fn scope_within(inner: &str, outer: &str) -> bool {
400    outer == "*" || inner == outer
401}
402
403/// Whether every entry of `inner` is held by `outer`: the same grant, on
404/// the same scope or within one `outer` holds (`*`).
405pub fn is_within(inner: &[String], outer: &[String]) -> bool {
406    inner.iter().all(|i| match entry(i) {
407        Some((g, s)) => outer.iter().filter_map(|o| entry(o)).any(|(og, os)| og == g && scope_within(s, os)),
408        None => false,
409    })
410}
411
412/// The scope an exchange may give: `requested` (all of `presented` when
413/// `None`), each entry kept only where `presented` holds it — narrowed to
414/// the inner scope, never widened. RFC 8693 §2.1 downscoping.
415pub fn narrow(requested: Option<&[String]>, presented: &[String]) -> Vec<String> {
416    let Some(req) = requested else { return presented.to_vec() };
417    let mut out: Vec<String> = Vec::new();
418    for r in req {
419        let Some((g, s)) = entry(r) else { continue };
420        for (pg, ps) in presented.iter().filter_map(|p| entry(p)) {
421            if pg != g {
422                continue;
423            }
424            let kept = if scope_within(s, ps) {
425                Some(s)
426            } else if scope_within(ps, s) {
427                Some(ps)
428            } else {
429                None
430            };
431            if let Some(k) = kept {
432                let e = format!("{g}@{k}");
433                if !out.contains(&e) {
434                    out.push(e);
435                }
436            }
437        }
438    }
439    out
440}
441
442/// The scope a forwarded call's token holds (D3: the caller's reach ∩ the
443/// peer's needs ∩ consent): the forwarded grant on each scope the call was
444/// admitted on (`reach`, `["*"]` when everywhere), and each need's grant on
445/// each scope both its consent and the reach hold. Never a scope the reach
446/// does not hold.
447pub fn mint_scope(forwarded: Option<&str>, reach: &[String], needs: &[(String, Vec<String>)]) -> Vec<String> {
448    let mut out: Vec<String> = Vec::new();
449    let mut push = |g: &str, s: &str| {
450        let e = format!("{g}@{s}");
451        if !out.contains(&e) {
452            out.push(e);
453        }
454    };
455    let everywhere = reach.iter().any(|r| r == "*");
456    if let Some(g) = forwarded {
457        for r in reach {
458            push(g, r);
459        }
460    }
461    for (g, consented) in needs {
462        let any = consented.iter().any(|c| c == "*");
463        let scopes: Vec<&String> = match (everywhere, any) {
464            (true, _) => consented.iter().collect(),
465            (false, true) => reach.iter().collect(),
466            (false, false) => consented.iter().filter(|c| reach.contains(c)).collect(),
467        };
468        for s in scopes {
469            push(g, s);
470        }
471    }
472    out
473}
474
475/// DYNAUTH-6 (RFC 8693): the scope of the token for an onward call — one a
476/// peer made back through its service under `presented`, which reaches
477/// another peer. Never wider than `presented`: each need of the next peer
478/// only where `presented` holds the same grant ([`narrow`]); the forwarded
479/// grant (the next peer's terms) only on the scopes where `presented` holds
480/// `admitted` — the grant the service admitted the onward call on, in its
481/// own terms (`dyn.{peer}`). Within `reach` as [`mint_scope`] is.
482pub fn onward_scope(presented: &PeerClaims, admitted: Option<&str>, forwarded: Option<&str>, reach: &[String], needs: &[(String, Vec<String>)]) -> Vec<String> {
483    let mut out = narrow(Some(&mint_scope(None, reach, needs)), &presented.scope);
484    if let (Some(a), Some(f)) = (admitted, forwarded) {
485        for held in presented.scopes_for(a) {
486            for r in reach {
487                let s = if scope_within(r, &held) {
488                    r.as_str()
489                } else if scope_within(&held, r) {
490                    held.as_str()
491                } else {
492                    continue;
493                };
494                let e = format!("{f}@{s}");
495                if !out.contains(&e) {
496                    out.push(e);
497                }
498            }
499        }
500    }
501    out
502}
503
504// ------------------------------------------------------------------ errors
505
506/// Why a token or a proof is refused. Says what, never the token.
507#[derive(Debug, Clone, PartialEq, Eq)]
508pub enum TokenError {
509    Malformed(String),
510    /// `alg` not EdDSA, or a key of another kind.
511    Algorithm(String),
512    /// `typ` not the one expected.
513    Type(String),
514    /// `kid` names no key the verifier trusts.
515    UnknownKey(String),
516    Signature,
517    /// `aud` is another's.
518    Audience { want: String, got: String },
519    Expired,
520    /// `iat` in the future, past the skew.
521    NotYet,
522    /// `exp − iat` past [`MAX_LIFETIME`].
523    Lifetime(u64),
524    Replayed,
525    /// Presented for another call or method than it names.
526    Binding(String),
527    /// A proof of possession missing or wrong.
528    Proof(String),
529    /// A scope that is not within the one it must be.
530    Scope(String),
531    /// The issuer refuses to mint (revoked, no caller).
532    Refused(String),
533}
534
535impl std::fmt::Display for TokenError {
536    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
537        match self {
538            Self::Malformed(w) => write!(f, "a malformed token: {w}"),
539            Self::Algorithm(w) => write!(f, "algorithm refused: {w}"),
540            Self::Type(w) => write!(f, "type refused: {w}"),
541            Self::UnknownKey(k) => write!(f, "signed by a key not trusted here ({k})"),
542            Self::Signature => write!(f, "the signature does not verify"),
543            Self::Audience { want, got } => write!(f, "addressed to {got}, not to {want}"),
544            Self::Expired => write!(f, "expired"),
545            Self::NotYet => write!(f, "issued in the future"),
546            Self::Lifetime(s) => write!(f, "lives {s} s, past {} s", MAX_LIFETIME.as_secs()),
547            Self::Replayed => write!(f, "already used (replayed)"),
548            Self::Binding(w) => write!(f, "presented for another call: {w}"),
549            Self::Proof(w) => write!(f, "no valid proof of possession: {w}"),
550            Self::Scope(w) => write!(f, "scope refused: {w}"),
551            Self::Refused(w) => write!(f, "{w}"),
552        }
553    }
554}
555
556impl std::error::Error for TokenError {}
557
558// ------------------------------------------------------------------ JWS
559
560struct Parsed {
561    header: Value,
562    payload: Vec<u8>,
563    input: String,
564    sig: Signature,
565}
566
567/// Split and decode a compact JWS; the algorithm checked here, before
568/// anything else is believed: `alg` must be exactly `EdDSA` (`none`,
569/// `HS256`, anything else refused — the verifier chooses the algorithm,
570/// never the token), and no `jku`/`x5u`/`crit` is honoured.
571fn parse(token: &str, typ: &str) -> Result<Parsed, TokenError> {
572    let mut parts = token.split('.');
573    let (Some(h), Some(p), Some(s), None) = (parts.next(), parts.next(), parts.next(), parts.next()) else {
574        return Err(TokenError::Malformed("a compact JWS has three parts".into()));
575    };
576    let header: Value = serde_json::from_slice(&unb64(h)?).map_err(|_| TokenError::Malformed("the header is not JSON".into()))?;
577    match header.get("alg").and_then(Value::as_str) {
578        Some(ALG) => {}
579        other => return Err(TokenError::Algorithm(format!("alg {:?}: only EdDSA", other.unwrap_or("(none)")))),
580    }
581    if header.get("crit").is_some() {
582        return Err(TokenError::Malformed("`crit` is not understood here".into()));
583    }
584    match header.get("typ").and_then(Value::as_str) {
585        Some(t) if t.eq_ignore_ascii_case(typ) => {}
586        other => return Err(TokenError::Type(format!("typ {:?}, not {typ}", other.unwrap_or("(none)")))),
587    }
588    Ok(Parsed { header, payload: unb64(p)?, input: format!("{h}.{p}"), sig: signature_of(s)? })
589}
590
591// ------------------------------------------------------------------ verify
592
593/// What a token must also say to be taken for this presentation.
594#[derive(Debug, Clone, Default)]
595pub struct Expect<'a> {
596    /// The forwarded call's id (`hop.call`).
597    pub call: Option<&'a str>,
598    /// The method it is presented for (in the verifier's terms).
599    pub method: Option<&'a str>,
600}
601
602/// Checks tokens addressed to one audience, from the issuers it trusts,
603/// each `jti` once.
604pub struct Verifier {
605    audience: String,
606    issuers: RwLock<BTreeMap<String, VerifyingKey>>,
607    seen: Mutex<HashMap<String, u64>>,
608}
609
610impl std::fmt::Debug for Verifier {
611    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
612        f.debug_struct("Verifier").field("audience", &self.audience).field("issuers", &self.issuers.read().unwrap().keys().collect::<Vec<_>>()).finish()
613    }
614}
615
616impl Verifier {
617    /// A verifier for tokens addressed to `audience`, trusting `jwks`.
618    pub fn new(audience: impl Into<String>, jwks: &Jwks) -> Result<Self, TokenError> {
619        let v = Self { audience: audience.into(), issuers: RwLock::default(), seen: Mutex::default() };
620        v.trust(jwks)?;
621        Ok(v)
622    }
623
624    /// The audience it takes.
625    pub fn audience(&self) -> &str {
626        &self.audience
627    }
628
629    /// Trust exactly `jwks` from now (a rotation: the old key goes once the
630    /// issuer's JWKS drops it).
631    pub fn trust(&self, jwks: &Jwks) -> Result<(), TokenError> {
632        let mut keys = BTreeMap::new();
633        for k in &jwks.keys {
634            let vk = k.key()?;
635            keys.insert(k.kid.clone().unwrap_or_else(|| principal_of(&vk)), vk);
636        }
637        *self.issuers.write().unwrap() = keys;
638        Ok(())
639    }
640
641    /// Verify `token` now.
642    pub fn verify(&self, token: &str, expect: &Expect<'_>) -> Result<PeerClaims, TokenError> {
643        self.verify_at(token, expect, now())
644    }
645
646    /// Verify `token` as of `now` (seconds since the epoch).
647    pub fn verify_at(&self, token: &str, expect: &Expect<'_>, now: u64) -> Result<PeerClaims, TokenError> {
648        let parsed = parse(token, TOKEN_TYP)?;
649        let kid = parsed.header.get("kid").and_then(Value::as_str).unwrap_or_default().to_string();
650        let key = self.issuers.read().unwrap().get(&kid).copied().ok_or(TokenError::UnknownKey(kid.clone()))?;
651        key.verify_strict(parsed.input.as_bytes(), &parsed.sig).map_err(|_| TokenError::Signature)?;
652        let claims: PeerClaims = serde_json::from_slice(&parsed.payload).map_err(|e| TokenError::Malformed(format!("its claims: {e}")))?;
653        if claims.iss != kid {
654            return Err(TokenError::Malformed("`iss` is not the key that signed it".into()));
655        }
656        check_times(&claims, now)?;
657        if claims.aud != self.audience {
658            return Err(TokenError::Audience { want: self.audience.clone(), got: claims.aud });
659        }
660        if let Some(call) = expect.call.filter(|c| *c != claims.call) {
661            return Err(TokenError::Binding(format!("it names call {}, presented under {call}", claims.call)));
662        }
663        if let Some(method) = expect.method.filter(|m| *m != claims.method) {
664            return Err(TokenError::Binding(format!("it names {}, presented for {method}", claims.method)));
665        }
666        let mut seen = self.seen.lock().unwrap();
667        seen.retain(|_, exp| *exp + SKEW.as_secs() >= now);
668        if seen.insert(claims.jti.clone(), claims.exp).is_some() {
669            return Err(TokenError::Replayed);
670        }
671        Ok(claims)
672    }
673
674    /// `jti`s held now (the replay cache's size).
675    pub fn held(&self) -> usize {
676        self.seen.lock().unwrap().len()
677    }
678}
679
680fn check_times(claims: &PeerClaims, now: u64) -> Result<(), TokenError> {
681    if claims.exp < claims.iat || claims.exp - claims.iat > MAX_LIFETIME.as_secs() {
682        return Err(TokenError::Lifetime(claims.exp.saturating_sub(claims.iat)));
683    }
684    if claims.iat > now + SKEW.as_secs() {
685        return Err(TokenError::NotYet);
686    }
687    if now > claims.exp + SKEW.as_secs() {
688        return Err(TokenError::Expired);
689    }
690    Ok(())
691}
692
693// ------------------------------------------------------------------ proof
694
695/// A proof of possession by `key` for presenting `token` for `method`
696/// under `call` (see the module docs).
697pub fn prove(key: &PeerKey, token: &str, method: &str, call: &str) -> String {
698    prove_at(key, token, method, call, now())
699}
700
701/// [`prove`] as of `iat`.
702pub fn prove_at(key: &PeerKey, token: &str, method: &str, call: &str, iat: u64) -> String {
703    let header = json!({ "typ": PROOF_TYP, "jwk": key.jwk() });
704    let claims = json!({ "ath": token_hash(token), "jti": random_id(), "method": method, "call": call, "iat": iat });
705    key.sign_compact(header, &claims)
706}
707
708/// The proofs a presenter's side has seen, each once (by its `jti`, kept
709/// for twice the skew).
710#[derive(Debug, Default)]
711pub struct ProofCache(Mutex<HashMap<String, u64>>);
712
713/// Check `proof` for presenting `token` (whose claims are `claims`) for
714/// `method` under `call`, as of `now`: signed by the key `claims.cnf.jkt`
715/// names, over this token, method and call, fresh, and not seen before.
716pub fn check_proof(proof: &str, token: &str, claims: &PeerClaims, method: &str, call: &str, now: u64, seen: &ProofCache) -> Result<(), TokenError> {
717    let jkt = claims.cnf.as_ref().map(|c| c.jkt.as_str()).ok_or_else(|| TokenError::Proof("the token is bound to no key".into()))?;
718    let parsed = parse(proof, PROOF_TYP).map_err(|e| TokenError::Proof(e.to_string()))?;
719    let jwk: Jwk = parsed.header.get("jwk").cloned().and_then(|j| serde_json::from_value(j).ok()).ok_or_else(|| TokenError::Proof("no `jwk` in its header".into()))?;
720    let key = jwk.key().map_err(|e| TokenError::Proof(e.to_string()))?;
721    if thumbprint(&key) != jkt {
722        return Err(TokenError::Proof("signed by another key than the token is bound to".into()));
723    }
724    key.verify_strict(parsed.input.as_bytes(), &parsed.sig).map_err(|_| TokenError::Proof("its signature does not verify".into()))?;
725    let c: Value = serde_json::from_slice(&parsed.payload).map_err(|_| TokenError::Proof("its claims are not JSON".into()))?;
726    let s = |k: &str| c.get(k).and_then(Value::as_str).unwrap_or_default();
727    if s("ath") != token_hash(token) {
728        return Err(TokenError::Proof("made for another token".into()));
729    }
730    if s("method") != method || s("call") != call {
731        return Err(TokenError::Proof(format!("made for {} under {}, presented for {method} under {call}", s("method"), s("call"))));
732    }
733    let iat = c.get("iat").and_then(Value::as_u64).unwrap_or_default();
734    if iat + SKEW.as_secs() < now || iat > now + SKEW.as_secs() {
735        return Err(TokenError::Proof("not fresh (iat past the skew)".into()));
736    }
737    let jti = s("jti");
738    if jti.is_empty() {
739        return Err(TokenError::Proof("no `jti`".into()));
740    }
741    let mut seen = seen.0.lock().unwrap();
742    seen.retain(|_, t| *t + 2 * SKEW.as_secs() >= now);
743    if seen.insert(jti.to_string(), iat).is_some() {
744        return Err(TokenError::Proof("replayed".into()));
745    }
746    Ok(())
747}
748
749// ------------------------------------------------------------------ audit
750
751/// What was done with a token.
752#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
753#[serde(rename_all = "snake_case")]
754pub enum AuditKind {
755    Mint,
756    Exchange,
757}
758
759/// One audit record (TM-7): who acted through whom, for what. Never the
760/// token, a signature or a proof.
761#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
762pub struct AuditRecord {
763    pub kind: AuditKind,
764    pub iss: String,
765    pub sub: String,
766    /// The actor chain, nearest first.
767    pub act: Vec<String>,
768    pub aud: String,
769    pub scope: Vec<String>,
770    pub call: String,
771    pub jti: String,
772    pub exp: u64,
773    pub method: String,
774    /// For an exchange: the call of the token presented — what joins this
775    /// hop's record to the one before it.
776    #[serde(default, skip_serializing_if = "Option::is_none")]
777    pub presented_call: Option<String>,
778}
779
780impl AuditRecord {
781    fn of(kind: AuditKind, c: &PeerClaims, presented: Option<&PeerClaims>) -> Self {
782        Self {
783            kind,
784            iss: c.iss.clone(),
785            sub: c.sub.clone(),
786            act: c.actors(),
787            aud: c.aud.clone(),
788            scope: c.scope.clone(),
789            call: c.call.clone(),
790            jti: c.jti.clone(),
791            exp: c.exp,
792            method: c.method.clone(),
793            presented_call: presented.map(|p| p.call.clone()),
794        }
795    }
796}
797
798/// Where audit records go besides `tracing` (PRIVACY-1's sink, when it is).
799pub trait TokenAudit: Send + Sync {
800    fn record(&self, r: &AuditRecord);
801}
802
803fn audit(sink: Option<&Arc<dyn TokenAudit>>, r: AuditRecord) {
804    tracing::info!(
805        target: "plexus::audit",
806        kind = ?r.kind, iss = %r.iss, sub = %r.sub, act = ?r.act, aud = %r.aud,
807        scope = %r.scope.join(" "), call = %r.call, jti = %r.jti, exp = r.exp, method = %r.method,
808        presented_call = r.presented_call.as_deref().unwrap_or(""),
809        "peer token"
810    );
811    if let Some(s) = sink {
812        s.record(&r);
813    }
814}
815
816// ------------------------------------------------------------------ issue
817
818/// What one forwarded call's token is minted from.
819#[derive(Debug, Clone)]
820pub struct MintRequest {
821    /// The original caller.
822    pub sub: String,
823    /// The peer: its key (`key:<hex>`), or `None` for a child on the
824    /// issuer's own pipe (`aud` `pipe:<name>`, no `cnf`).
825    pub peer_key: Option<String>,
826    /// The mount's name (a pipe child's audience).
827    pub name: String,
828    pub scope: Vec<String>,
829    pub call: String,
830    pub method: String,
831    /// When this mint is an exchange: the token presented, already
832    /// verified, and who presented it (its audience).
833    pub presented: Option<PeerClaims>,
834}
835
836/// A service's token issuer: its signing key (rotatable, the old one kept
837/// in the JWKS for one token lifetime and the skew), the lifetime it
838/// mints, and the audit sink.
839pub struct TokenIssuer {
840    key: RwLock<PeerKey>,
841    retired: Mutex<Vec<(PeerKey, u64)>>,
842    ttl: Duration,
843    sink: Option<Arc<dyn TokenAudit>>,
844}
845
846impl std::fmt::Debug for TokenIssuer {
847    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
848        f.debug_struct("TokenIssuer").field("kid", &self.kid()).field("ttl", &self.ttl).finish_non_exhaustive()
849    }
850}
851
852impl TokenIssuer {
853    /// An issuer signing with `key`, minting tokens of [`MAX_LIFETIME`].
854    pub fn new(key: PeerKey) -> Self {
855        Self { key: RwLock::new(key), retired: Mutex::default(), ttl: MAX_LIFETIME, sink: None }
856    }
857
858    /// Tokens of `ttl` (at most [`MAX_LIFETIME`]).
859    pub fn with_ttl(mut self, ttl: Duration) -> Self {
860        self.ttl = ttl.min(MAX_LIFETIME);
861        self
862    }
863
864    /// Audit records also to `sink`.
865    pub fn with_audit(mut self, sink: Arc<dyn TokenAudit>) -> Self {
866        self.sink = Some(sink);
867        self
868    }
869
870    /// The signing key's id now.
871    pub fn kid(&self) -> String {
872        self.key.read().unwrap().kid().to_string()
873    }
874
875    /// The lifetime it mints.
876    pub fn ttl(&self) -> Duration {
877        self.ttl
878    }
879
880    /// The keys a peer verifies with: the current one, and each retired one
881    /// while a token it signed may still be presented.
882    pub fn jwks(&self) -> Jwks {
883        let now = now();
884        let mut retired = self.retired.lock().unwrap();
885        retired.retain(|(_, until)| *until >= now);
886        let mut keys = vec![self.key.read().unwrap().jwk()];
887        keys.extend(retired.iter().map(|(k, _)| k.jwk()));
888        Jwks { keys }
889    }
890
891    /// Sign with `new` from now; the old key stays in [`Self::jwks`] for one
892    /// token lifetime and the skew, then goes.
893    pub fn rotate(&self, new: PeerKey) -> String {
894        let old = std::mem::replace(&mut *self.key.write().unwrap(), new);
895        let until = now() + self.ttl.as_secs() + SKEW.as_secs();
896        self.retired.lock().unwrap().push((old, until));
897        self.kid()
898    }
899
900    /// Mint one forwarded call's token (an exchange when `req.presented`).
901    pub fn mint(&self, req: MintRequest) -> Result<(String, PeerClaims), TokenError> {
902        self.mint_at(req, now())
903    }
904
905    /// [`Self::mint`] as of `now`.
906    pub fn mint_at(&self, req: MintRequest, now: u64) -> Result<(String, PeerClaims), TokenError> {
907        let key = self.key.read().unwrap().clone();
908        let (aud, cnf) = match &req.peer_key {
909            Some(k) => {
910                let vk = key_of(k).ok_or_else(|| TokenError::Malformed(format!("`{k}` is not an Ed25519 key")))?;
911                (k.clone(), Some(Cnf { jkt: thumbprint(&vk) }))
912            }
913            None => (format!("pipe:{}", req.name), None),
914        };
915        let (sub, act, scope, kind) = match &req.presented {
916            None => (req.sub.clone(), Some(Actor::after(key.kid(), None)), req.scope.clone(), AuditKind::Mint),
917            Some(p) => {
918                // RFC 8693: the subject stays; the presenter joins the
919                // chain. The scope is the caller's to narrow (`exchange`,
920                // `onward_scope`): never wider than the presented one's.
921                let prior = Actor::after(p.aud.clone(), p.act.clone());
922                (p.sub.clone(), Some(Actor::after(key.kid(), Some(prior))), req.scope.clone(), AuditKind::Exchange)
923            }
924        };
925        let claims = PeerClaims {
926            iss: key.kid().to_string(),
927            sub,
928            act,
929            aud,
930            scope,
931            cnf,
932            call: req.call,
933            method: req.method,
934            jti: random_id(),
935            iat: now,
936            exp: now + self.ttl.as_secs(),
937        };
938        let token = key.sign_compact(json!({ "typ": TOKEN_TYP, "kid": key.kid() }), &serde_json::to_value(&claims).unwrap_or_default());
939        audit(self.sink.as_ref(), AuditRecord::of(kind, &claims, req.presented.as_ref()));
940        Ok((token, claims))
941    }
942
943    /// RFC 8693 token exchange, as a method answers it: `subject` (a token
944    /// this issuer minted, presented by its audience with `proof` when it is
945    /// key-bound) becomes a token for `audience` (`peer_key`, a name for a
946    /// pipe), its scope `requested` narrowed by the presented one.
947    #[allow(clippy::too_many_arguments)]
948    pub fn exchange(&self, subject: &str, proof: Option<&str>, name: &str, peer_key: Option<String>, requested: Option<&[String]>, call: &str, method: &str, seen: &ProofCache) -> Result<(String, PeerClaims), TokenError> {
949        let presented = self.verify_own(subject)?;
950        // A token bound to no key (a pipe's) is its pipe's alone: it is
951        // never exchanged by whoever holds its bytes.
952        if presented.cnf.is_none() {
953            return Err(TokenError::Proof("a token bound to no key (a pipe's) is not exchanged".into()));
954        }
955        let proof = proof.ok_or_else(|| TokenError::Proof("a key-bound token is exchanged with a proof".into()))?;
956        check_proof(proof, subject, &presented, EXCHANGE, &presented.call, now(), seen)?;
957        let scope = narrow(requested, &presented.scope);
958        self.mint(MintRequest { sub: presented.sub.clone(), peer_key, name: name.into(), scope, call: call.into(), method: method.into(), presented: Some(presented) })
959    }
960
961    /// A token this issuer minted (any audience), signature and times
962    /// checked — what the issuer reads back when a peer presents it.
963    pub fn verify_own(&self, token: &str) -> Result<PeerClaims, TokenError> {
964        let parsed = parse(token, TOKEN_TYP)?;
965        let kid = parsed.header.get("kid").and_then(Value::as_str).unwrap_or_default();
966        let jwks = self.jwks();
967        let key = jwks.keys.iter().find(|k| k.kid.as_deref() == Some(kid)).ok_or_else(|| TokenError::UnknownKey(kid.to_string()))?.key()?;
968        key.verify_strict(parsed.input.as_bytes(), &parsed.sig).map_err(|_| TokenError::Signature)?;
969        let claims: PeerClaims = serde_json::from_slice(&parsed.payload).map_err(|e| TokenError::Malformed(format!("its claims: {e}")))?;
970        check_times(&claims, now())?;
971        Ok(claims)
972    }
973}
974
975#[cfg(test)]
976mod tests {
977    use super::*;
978
979    fn req(peer: &PeerKey) -> MintRequest {
980        MintRequest {
981            sub: "key:caller".into(),
982            peer_key: Some(peer.kid().to_string()),
983            name: "w".into(),
984            scope: vec!["weather.forecast@*".into(), "shop.items@MENGER".into()],
985            call: "call-1".into(),
986            method: "far.weather.forecast".into(),
987            presented: None,
988        }
989    }
990
991    fn header_of(token: &str) -> Value {
992        serde_json::from_slice(&unb64(token.split('.').next().unwrap()).unwrap()).unwrap()
993    }
994
995    fn claims_part(token: &str) -> Value {
996        serde_json::from_slice(&unb64(token.split('.').nth(1).unwrap()).unwrap()).unwrap()
997    }
998
999    /// Re-sign `token`'s parts as given — a forger with some key.
1000    fn forge(key: &PeerKey, header: Value, claims: Value) -> String {
1001        let input = format!("{}.{}", b64(header.to_string().as_bytes()), b64(claims.to_string().as_bytes()));
1002        format!("{input}.{}", b64(&key.signing.sign(input.as_bytes()).to_bytes()))
1003    }
1004
1005    #[test]
1006    fn a_token_signs_and_verifies() {
1007        let (host, peer) = (PeerKey::generate(), PeerKey::generate());
1008        let issuer = TokenIssuer::new(host.clone());
1009        let (token, minted) = issuer.mint(req(&peer)).unwrap();
1010        let h = header_of(&token);
1011        assert_eq!((h["alg"].as_str(), h["typ"].as_str(), h["kid"].as_str()), (Some("EdDSA"), Some(TOKEN_TYP), Some(host.kid())));
1012        let c = claims_part(&token);
1013        assert_eq!(c["scope"], "weather.forecast@* shop.items@MENGER", "space-separated on the wire");
1014        assert_eq!(c["cnf"]["jkt"], peer.thumbprint());
1015        assert_eq!(c["act"], json!({ "sub": host.kid() }));
1016        assert!(minted.exp - minted.iat <= 60);
1017        let v = Verifier::new(peer.kid(), &issuer.jwks()).unwrap();
1018        let got = v.verify(&token, &Expect { call: Some("call-1"), method: Some("far.weather.forecast") }).unwrap();
1019        assert_eq!(got, minted);
1020        assert_eq!(got.scopes_for("shop.items"), ["MENGER"]);
1021    }
1022
1023    #[test]
1024    fn a_token_for_another_audience_is_refused() {
1025        let (host, a, b) = (PeerKey::generate(), PeerKey::generate(), PeerKey::generate());
1026        let issuer = TokenIssuer::new(host);
1027        let (for_a, _) = issuer.mint(req(&a)).unwrap();
1028        let at_b = Verifier::new(b.kid(), &issuer.jwks()).unwrap();
1029        assert!(matches!(at_b.verify(&for_a, &Expect::default()), Err(TokenError::Audience { .. })));
1030    }
1031
1032    #[test]
1033    fn an_expired_or_future_or_long_token_is_refused() {
1034        let (host, peer) = (PeerKey::generate(), PeerKey::generate());
1035        let issuer = TokenIssuer::new(host.clone());
1036        let v = Verifier::new(peer.kid(), &issuer.jwks()).unwrap();
1037        let t0 = now();
1038        let (old, _) = issuer.mint_at(req(&peer), t0 - 200).unwrap();
1039        assert_eq!(v.verify_at(&old, &Expect::default(), t0), Err(TokenError::Expired));
1040        // Within the skew past `exp`, still taken; past it, not.
1041        let (t, c) = issuer.mint_at(req(&peer), t0).unwrap();
1042        assert!(v.verify_at(&t, &Expect::default(), c.exp + 29).is_ok());
1043        let (t, c) = issuer.mint_at(req(&peer), t0).unwrap();
1044        assert_eq!(v.verify_at(&t, &Expect::default(), c.exp + 31), Err(TokenError::Expired));
1045        let (future, _) = issuer.mint_at(req(&peer), t0 + 120).unwrap();
1046        assert_eq!(v.verify_at(&future, &Expect::default(), t0), Err(TokenError::NotYet));
1047        // A token that claims to live past 60 s, even signed by the host.
1048        let mut c = claims_part(&future);
1049        c["iat"] = json!(t0);
1050        c["exp"] = json!(t0 + 3600);
1051        let long = forge(&host, json!({ "alg": "EdDSA", "typ": TOKEN_TYP, "kid": host.kid() }), c);
1052        assert_eq!(v.verify_at(&long, &Expect::default(), t0), Err(TokenError::Lifetime(3600)));
1053    }
1054
1055    #[test]
1056    fn a_replayed_jti_is_refused() {
1057        let (host, peer) = (PeerKey::generate(), PeerKey::generate());
1058        let issuer = TokenIssuer::new(host);
1059        let v = Verifier::new(peer.kid(), &issuer.jwks()).unwrap();
1060        let (t, _) = issuer.mint(req(&peer)).unwrap();
1061        assert!(v.verify(&t, &Expect::default()).is_ok());
1062        assert_eq!(v.verify(&t, &Expect::default()), Err(TokenError::Replayed));
1063        assert_eq!(v.held(), 1);
1064    }
1065
1066    #[test]
1067    fn a_token_presented_for_another_call_or_method_is_refused() {
1068        let (host, peer) = (PeerKey::generate(), PeerKey::generate());
1069        let issuer = TokenIssuer::new(host);
1070        let v = Verifier::new(peer.kid(), &issuer.jwks()).unwrap();
1071        let (t, _) = issuer.mint(req(&peer)).unwrap();
1072        assert!(matches!(v.verify(&t, &Expect { call: Some("call-2"), method: None }), Err(TokenError::Binding(_))));
1073        let (t, _) = issuer.mint(req(&peer)).unwrap();
1074        assert!(matches!(v.verify(&t, &Expect { call: None, method: Some("far.weather.secret") }), Err(TokenError::Binding(_))));
1075    }
1076
1077    #[test]
1078    fn alg_confusion_and_forgeries_are_refused() {
1079        let (host, peer, other) = (PeerKey::generate(), PeerKey::generate(), PeerKey::generate());
1080        let issuer = TokenIssuer::new(host.clone());
1081        let v = Verifier::new(peer.kid(), &issuer.jwks()).unwrap();
1082        let (t, _) = issuer.mint(req(&peer)).unwrap();
1083        let (h, c) = (header_of(&t), claims_part(&t));
1084        let parts: Vec<&str> = t.split('.').collect();
1085        // `alg: none`, no signature.
1086        let mut none = h.clone();
1087        none["alg"] = json!("none");
1088        let unsigned = format!("{}.{}.", b64(none.to_string().as_bytes()), parts[1]);
1089        assert!(matches!(v.verify(&unsigned, &Expect::default()), Err(TokenError::Algorithm(_))), "alg none");
1090        // HS256 "signed" with the public key as an HMAC secret: refused on
1091        // its alg before any key is looked at.
1092        let mut hs = h.clone();
1093        hs["alg"] = json!("HS256");
1094        let hs_token = format!("{}.{}.{}", b64(hs.to_string().as_bytes()), parts[1], parts[2]);
1095        assert!(matches!(v.verify(&hs_token, &Expect::default()), Err(TokenError::Algorithm(_))), "HS256");
1096        // No typ, another typ (a proof passed off as a token).
1097        let mut typ = h.clone();
1098        typ["typ"] = json!(PROOF_TYP);
1099        assert!(matches!(v.verify(&forge(&host, typ, c.clone()), &Expect::default()), Err(TokenError::Type(_))));
1100        // Signed by another key under the host's kid.
1101        assert_eq!(v.verify(&forge(&other, h.clone(), c.clone()), &Expect::default()), Err(TokenError::Signature));
1102        // Signed by another key under its own kid: not trusted.
1103        let mut own = h.clone();
1104        own["kid"] = json!(other.kid());
1105        let mut c2 = c.clone();
1106        c2["iss"] = json!(other.kid());
1107        assert!(matches!(v.verify(&forge(&other, own, c2), &Expect::default()), Err(TokenError::UnknownKey(_))));
1108        // A claim changed after signing.
1109        let mut wider = c.clone();
1110        wider["scope"] = json!("admin@*");
1111        let tampered = format!("{}.{}.{}", parts[0], b64(wider.to_string().as_bytes()), parts[2]);
1112        assert_eq!(v.verify(&tampered, &Expect::default()), Err(TokenError::Signature));
1113        // `crit` and garbage.
1114        let mut crit = h.clone();
1115        crit["crit"] = json!(["exp"]);
1116        assert!(matches!(v.verify(&forge(&host, crit, c), &Expect::default()), Err(TokenError::Malformed(_))));
1117        assert!(matches!(v.verify("a.b", &Expect::default()), Err(TokenError::Malformed(_))));
1118        // A JWKS offering another kind of key is refused outright.
1119        let rsa = Jwks { keys: vec![Jwk { kty: "RSA".into(), crv: String::new(), x: String::new(), kid: None, alg: Some("RS256".into()), use_: None }] };
1120        assert!(matches!(Verifier::new(peer.kid(), &rsa), Err(TokenError::Algorithm(_))));
1121    }
1122
1123    #[test]
1124    fn the_proof_of_possession_is_the_bound_key_s_for_this_call() {
1125        let (host, peer, thief) = (PeerKey::generate(), PeerKey::generate(), PeerKey::generate());
1126        let issuer = TokenIssuer::new(host);
1127        let (t, c) = issuer.mint(req(&peer)).unwrap();
1128        let seen = ProofCache::default();
1129        let n = now();
1130        let p = prove(&peer, &t, "shop.items", "call-1");
1131        assert_eq!(check_proof(&p, &t, &c, "shop.items", "call-1", n, &seen), Ok(()));
1132        assert!(matches!(check_proof(&p, &t, &c, "shop.items", "call-1", n, &seen), Err(TokenError::Proof(w)) if w.contains("replayed")));
1133        // The thief has the token's bytes, not the peer's key.
1134        let stolen = prove(&thief, &t, "shop.items", "call-1");
1135        assert!(matches!(check_proof(&stolen, &t, &c, "shop.items", "call-1", n, &seen), Err(TokenError::Proof(w)) if w.contains("another key")));
1136        // A proof for another method, call or token.
1137        let p = prove(&peer, &t, "shop.items", "call-1");
1138        assert!(check_proof(&p, &t, &c, "shop.secret", "call-1", n, &seen).is_err());
1139        let p = prove(&peer, &t, "shop.items", "call-9");
1140        assert!(check_proof(&p, &t, &c, "shop.items", "call-1", n, &seen).is_err());
1141        let (t2, _) = issuer.mint(req(&peer)).unwrap();
1142        let p = prove(&peer, &t2, "shop.items", "call-1");
1143        assert!(matches!(check_proof(&p, &t, &c, "shop.items", "call-1", n, &seen), Err(TokenError::Proof(w)) if w.contains("another token")));
1144        // Stale.
1145        let p = prove_at(&peer, &t, "shop.items", "call-1", n - 120);
1146        assert!(matches!(check_proof(&p, &t, &c, "shop.items", "call-1", n, &seen), Err(TokenError::Proof(w)) if w.contains("fresh")));
1147        // A pipe's token is bound to no key: no proof can be checked for it.
1148        let pipe = issuer.mint(MintRequest { peer_key: None, ..req(&peer) }).unwrap().1;
1149        assert_eq!(pipe.aud, "pipe:w");
1150        assert!(pipe.cnf.is_none());
1151    }
1152
1153    #[test]
1154    fn a_key_proof_at_info_is_checked() {
1155        let peer = PeerKey::generate();
1156        let p = peer.key_proof("n0nce", "far");
1157        assert!(check_key_proof(peer.kid(), &p, "n0nce", "far").is_ok());
1158        assert_eq!(check_key_proof(peer.kid(), &p, "other", "far").map(|_| ()), Err(TokenError::Signature));
1159        assert_eq!(check_key_proof(PeerKey::generate().kid(), &p, "n0nce", "far").map(|_| ()), Err(TokenError::Signature));
1160    }
1161
1162    #[test]
1163    fn an_exchange_narrows_and_never_widens() {
1164        let (host, a, b) = (PeerKey::generate(), PeerKey::generate(), PeerKey::generate());
1165        let issuer = TokenIssuer::new(host.clone());
1166        let (t, c) = issuer.mint(req(&a)).unwrap();
1167        let seen = ProofCache::default();
1168        // No proof: refused (the token is bound to a's key).
1169        assert!(matches!(issuer.exchange(&t, None, "b", Some(b.kid().into()), None, "call-2", "far.x", &seen), Err(TokenError::Proof(_))));
1170        // Asking for more than was presented: only the overlap is given.
1171        let ask = vec!["shop.items@*".to_string(), "auth.grant@*".to_string(), "weather.forecast@LISBON".to_string()];
1172        let proof = prove(&a, &t, "exchange", &c.call);
1173        let (t2, c2) = issuer.exchange(&t, Some(&proof), "b", Some(b.kid().into()), Some(&ask), "call-2", "far.x", &seen).unwrap();
1174        assert_eq!(c2.scope, ["shop.items@MENGER", "weather.forecast@LISBON"]);
1175        assert!(is_within(&c2.scope, &c.scope));
1176        assert_eq!(c2.sub, c.sub, "the subject survives every hop");
1177        assert_eq!(c2.actors(), [host.kid().to_string(), a.kid().to_string(), host.kid().to_string()], "act names each hop, nearest first");
1178        assert_eq!(c2.aud, b.kid());
1179        let at_b = Verifier::new(b.kid(), &issuer.jwks()).unwrap();
1180        assert_eq!(at_b.verify(&t2, &Expect::default()).unwrap(), c2);
1181        // A pipe's token (bound to no key) is never exchanged.
1182        let (pipe, _) = issuer.mint(MintRequest { peer_key: None, ..req(&a) }).unwrap();
1183        assert!(matches!(issuer.exchange(&pipe, None, "b", Some(b.kid().into()), None, "c", "m", &seen), Err(TokenError::Proof(w)) if w.contains("pipe")));
1184        // Nothing asked: the presented scope, no wider.
1185        let proof = prove(&a, &t, "exchange", &c.call);
1186        let (_, c3) = issuer.exchange(&t, Some(&proof), "b", Some(b.kid().into()), None, "call-3", "far.x", &seen).unwrap();
1187        assert_eq!(c3.scope, c.scope);
1188        // narrow, exhaustively over a small lattice.
1189        let all = ["g@*", "g@A", "g@B", "h@*", "h@A"];
1190        for p in 0..(1 << all.len()) {
1191            let presented: Vec<String> = (0..all.len()).filter(|i| p & (1 << i) != 0).map(|i| all[i].to_string()).collect();
1192            for r in 0..(1 << all.len()) {
1193                let requested: Vec<String> = (0..all.len()).filter(|i| r & (1 << i) != 0).map(|i| all[i].to_string()).collect();
1194                let got = narrow(Some(&requested), &presented);
1195                assert!(is_within(&got, &presented), "{requested:?} from {presented:?} gave {got:?}");
1196            }
1197        }
1198    }
1199
1200    #[test]
1201    fn a_rotated_key_verifies_for_one_lifetime_then_goes() {
1202        let (old, new, peer) = (PeerKey::generate(), PeerKey::generate(), PeerKey::generate());
1203        let issuer = TokenIssuer::new(old.clone());
1204        let (t_old, _) = issuer.mint(req(&peer)).unwrap();
1205        issuer.rotate(new.clone());
1206        let jwks = issuer.jwks();
1207        assert_eq!(jwks.keys.iter().map(|k| k.kid.clone().unwrap()).collect::<Vec<_>>(), [new.kid().to_string(), old.kid().to_string()]);
1208        let v = Verifier::new(peer.kid(), &jwks).unwrap();
1209        assert!(v.verify(&t_old, &Expect::default()).is_ok(), "an old token still verifies while it lives");
1210        let (t_new, c) = issuer.mint(req(&peer)).unwrap();
1211        assert_eq!(c.iss, new.kid());
1212        assert!(v.verify(&t_new, &Expect::default()).is_ok());
1213        // Once the old key leaves the JWKS, a verifier that refreshed refuses it.
1214        issuer.retired.lock().unwrap().clear();
1215        v.trust(&issuer.jwks()).unwrap();
1216        let (t, _) = (t_old, ());
1217        assert!(matches!(v.verify(&t, &Expect::default()), Err(TokenError::UnknownKey(_)) | Err(TokenError::Replayed)));
1218    }
1219
1220    #[test]
1221    fn every_mint_and_exchange_is_audited_without_a_secret() {
1222        #[derive(Default)]
1223        struct Sink(Mutex<Vec<AuditRecord>>);
1224        impl TokenAudit for Sink {
1225            fn record(&self, r: &AuditRecord) {
1226                self.0.lock().unwrap().push(r.clone());
1227            }
1228        }
1229        let sink = Arc::new(Sink::default());
1230        let (host, a, b) = (PeerKey::generate(), PeerKey::generate(), PeerKey::generate());
1231        let issuer = TokenIssuer::new(host).with_audit(sink.clone());
1232        let (t, c) = issuer.mint(req(&a)).unwrap();
1233        let proof = prove(&a, &t, "exchange", &c.call);
1234        let (t2, _) = issuer.exchange(&t, Some(&proof), "b", Some(b.kid().into()), None, "call-2", "far.y", &ProofCache::default()).unwrap();
1235        let records = sink.0.lock().unwrap().clone();
1236        assert_eq!(records.iter().map(|r| r.kind).collect::<Vec<_>>(), [AuditKind::Mint, AuditKind::Exchange]);
1237        assert_eq!(records[1].act.len(), 3);
1238        assert_eq!(records[1].presented_call.as_deref(), Some(c.call.as_str()), "an exchange's record is joined to the hop before it");
1239        assert_eq!(records[0].presented_call, None);
1240        let text = serde_json::to_string(&records).unwrap();
1241        for secret in [&t, &t2, &proof] {
1242            for part in secret.split('.').filter(|p| p.len() > 8) {
1243                assert!(!text.contains(part), "an audit record holds a token's or a proof's bytes");
1244            }
1245        }
1246    }
1247
1248    /// DYNAUTH-12's property: `scope ⊆ reach` for every mint — over every
1249    /// reach, forwarded grant and consent drawn from a small lattice.
1250    #[test]
1251    fn every_mint_s_scope_is_within_the_reach() {
1252        let scopes = ["*", "A", "B", "C"];
1253        let subsets = |n: usize| -> Vec<Vec<String>> {
1254            (0..(1usize << n)).map(|m| (0..n).filter(|i| m & (1 << i) != 0).map(|i| scopes[i].to_string()).collect()).collect()
1255        };
1256        let (host, peer) = (PeerKey::generate(), PeerKey::generate());
1257        let issuer = TokenIssuer::new(host);
1258        let mut minted = 0;
1259        for reach in subsets(scopes.len()) {
1260            for consent_a in subsets(scopes.len()) {
1261                for consent_b in subsets(3) {
1262                    for forwarded in [None, Some("far.m")] {
1263                        let needs = vec![("shop.items".to_string(), consent_a.clone()), ("dyn.{peer}".to_string(), consent_b.clone())];
1264                        let scope = mint_scope(forwarded, &reach, &needs);
1265                        let (_, c) = issuer.mint(MintRequest { scope, ..req(&peer) }).unwrap();
1266                        minted += 1;
1267                        for e in &c.scope {
1268                            let (g, s) = e.rsplit_once('@').unwrap();
1269                            assert!(reach.iter().any(|r| r == "*" || r == s), "{e} outside the reach {reach:?}");
1270                            if g != "far.m" {
1271                                let consent = needs.iter().find(|(n, _)| n == g).map(|(_, c)| c).unwrap();
1272                                assert!(consent.iter().any(|c| c == "*" || c == s), "{e} outside its consent {consent:?}");
1273                            }
1274                        }
1275                    }
1276                }
1277            }
1278        }
1279        assert_eq!(minted, 16 * 16 * 8 * 2);
1280    }
1281
1282    /// DYNAUTH-6: an onward token never holds more than the presented one —
1283    /// a need only where it held the same grant, the forwarded grant only
1284    /// where it held the grant the onward call was admitted on.
1285    #[test]
1286    fn an_onward_scope_never_widens() {
1287        let scopes = ["*", "A", "B"];
1288        let subsets = |n: usize| -> Vec<Vec<String>> {
1289            (0..(1usize << n)).map(|m| (0..n).filter(|i| m & (1 << i) != 0).map(|i| scopes[i].to_string()).collect()).collect()
1290        };
1291        let peer = PeerKey::generate();
1292        let issuer = TokenIssuer::new(PeerKey::generate());
1293        for held_slot in subsets(3) {
1294            for held_need in subsets(3) {
1295                let mut presented_scope: Vec<String> = held_slot.iter().map(|s| format!("dyn.{{peer}}@{s}")).collect();
1296                presented_scope.extend(held_need.iter().map(|s| format!("shop.items@{s}")));
1297                let (_, presented) = issuer.mint(MintRequest { scope: presented_scope.clone(), ..req(&peer) }).unwrap();
1298                for reach in subsets(3) {
1299                    for consent in subsets(3) {
1300                        let needs = vec![("shop.items".to_string(), consent.clone()), ("auth.grant".to_string(), vec!["*".to_string()])];
1301                        let got = onward_scope(&presented, Some("dyn.{peer}"), Some("far.forecast"), &reach, &needs);
1302                        for e in &got {
1303                            let (g, s) = e.rsplit_once('@').unwrap();
1304                            let host_grant = if g == "far.forecast" { "dyn.{peer}" } else { g };
1305                            assert!(presented.scopes_for(host_grant).iter().any(|h| h == "*" || h == s), "{e} wider than {presented_scope:?}");
1306                            assert!(reach.iter().any(|r| r == "*" || r == s), "{e} outside the reach {reach:?}");
1307                            assert_ne!(g, "auth.grant", "a need the presented token did not hold");
1308                        }
1309                    }
1310                }
1311            }
1312        }
1313    }
1314
1315    #[test]
1316    fn a_key_file_is_made_private_and_read_back() {
1317        let dir = tempfile::tempdir().unwrap();
1318        let path = dir.path().join("k/dyn.key");
1319        let a = PeerKey::load_or_create(&path).unwrap();
1320        let b = PeerKey::load_or_create(&path).unwrap();
1321        assert_eq!(a.kid(), b.kid());
1322        #[cfg(unix)]
1323        {
1324            use std::os::unix::fs::PermissionsExt;
1325            assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
1326            std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();
1327            assert!(PeerKey::load_or_create(&path).is_err());
1328        }
1329        assert!(!format!("{a:?}").contains(&b64(&a.signing.to_bytes())));
1330        // Replaced in place, still private.
1331        #[cfg(unix)]
1332        std::fs::set_permissions(&path, std::os::unix::fs::PermissionsExt::from_mode(0o600)).unwrap();
1333        let c = PeerKey::generate();
1334        c.save(&path).unwrap();
1335        assert_eq!(PeerKey::load_or_create(&path).unwrap().kid(), c.kid());
1336    }
1337}