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 key that presents it (RFC 7800, RFC 9449 §6): the peer's own for a token the service forwards; the presenter's for an exchanged one (KEEL-19); 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). KEEL-19: the other way, a
36//! service sends each forwarded hop with its own proof
37//! ([`TokenIssuer::prove_forward`], by the key that signed the token), and
38//! a verifying child takes the hop only with it.
39//!
40//! **Exchange** ([`TokenIssuer::exchange`], RFC 8693 semantics): a token
41//! presented for an onward call becomes one for the next peer — the same
42//! `sub`, `act` extended by the presenter, `aud` the next peer, and a scope
43//! that is the presented one's or narrower, never wider ([`narrow`]).
44//! KEEL-19: as a method ([`TokenIssuer::exchange_decided`]) it is the
45//! service's decision whether the presenter may reach that peer at all; the
46//! token is bound to the presenter's key (`cnf`), so the next peer takes it
47//! only with the presenter's proof; and a subject token is exchanged once
48//! per (`jti`, audience, method).
49//!
50//! **Audit** (DYNAUTH-7, TM-7): every mint and exchange writes one
51//! [`AuditRecord`] — iss, sub, the actor chain, aud, scope, call, jti, exp,
52//! method — as a `tracing` event on target `plexus::audit` and to the
53//! issuer's [`TokenAudit`] sink. Never the token, never a proof.
54
55use std::collections::{BTreeMap, HashMap};
56use std::path::Path;
57use std::sync::{Arc, Mutex, RwLock};
58use std::time::{Duration, SystemTime, UNIX_EPOCH};
59
60use base64::Engine as _;
61use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey};
62use serde::{Deserialize, Serialize};
63use serde_json::{json, Value};
64use sha2::{Digest, Sha256};
65
66/// The `typ` of a peer token (RFC 8725 §3.11: explicit typing).
67pub const TOKEN_TYP: &str = "plexus-peer+jwt";
68/// The `typ` of a proof of possession.
69pub const PROOF_TYP: &str = "plexus-pop+jwt";
70/// The one algorithm: EdDSA over Ed25519 (RFC 8037).
71pub const ALG: &str = "EdDSA";
72/// A token lives at most this long (`exp − iat`), D3.
73pub const MAX_LIFETIME: Duration = Duration::from_secs(60);
74/// How far apart two clocks may be.
75pub const SKEW: Duration = Duration::from_secs(30);
76/// The method a proof of possession names to exchange a token
77/// ([`TokenIssuer::exchange`]), under the token's own `call`.
78pub const EXCHANGE: &str = "exchange";
79/// RFC 8693's identifier of the token type issued.
80pub const JWT_TOKEN_TYPE: &str = "urn:ietf:params:oauth:token-type:jwt";
81/// The context a peer's key proof at `_info` is signed over (domain
82/// separation: no other signature can be passed off as one). KEEL-19: v2
83/// binds the proof to its asker (a v1 proof is refused).
84pub const KEY_PROOF_CONTEXT: &str = "plexus-peer-key/v2";
85
86fn b64(b: &[u8]) -> String {
87    base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(b)
88}
89
90fn unb64(s: &str) -> Result<Vec<u8>, TokenError> {
91    base64::engine::general_purpose::URL_SAFE_NO_PAD.decode(s).map_err(|_| TokenError::Malformed("not base64url".into()))
92}
93
94fn hex(b: &[u8]) -> String {
95    b.iter().map(|b| format!("{b:02x}")).collect()
96}
97
98/// Seconds since the epoch, now.
99pub fn now() -> u64 {
100    SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or_default()
101}
102
103/// A fresh random id (128 bits, base64url).
104fn random_id() -> String {
105    b64(uuid::Uuid::new_v4().as_bytes())
106}
107
108/// A fresh nonce (256 bits from the OS, base64url): what a mount asks a
109/// peer to sign at `_info`.
110pub fn random_nonce() -> String {
111    let mut n = [0u8; 32];
112    getrandom_02::getrandom(&mut n).expect("the OS's randomness");
113    b64(&n)
114}
115
116/// `key:<64 hex>` — the principal a key proves (spec/00's form).
117pub fn principal_of(key: &VerifyingKey) -> String {
118    format!("key:{}", hex(key.as_bytes()))
119}
120
121/// The key a `key:<64 hex>` principal names.
122pub fn key_of(principal: &str) -> Option<VerifyingKey> {
123    let h = principal.strip_prefix("key:")?;
124    if h.len() != 64 {
125        return None;
126    }
127    let mut bytes = [0u8; 32];
128    for (i, b) in bytes.iter_mut().enumerate() {
129        *b = u8::from_str_radix(h.get(2 * i..2 * i + 2)?, 16).ok()?;
130    }
131    VerifyingKey::from_bytes(&bytes).ok()
132}
133
134/// RFC 7638 thumbprint of an Ed25519 key (OKP, RFC 8037 §2):
135/// base64url(sha256(`{"crv":"Ed25519","kty":"OKP","x":"…"}`)).
136pub fn thumbprint(key: &VerifyingKey) -> String {
137    let canonical = format!(r#"{{"crv":"Ed25519","kty":"OKP","x":"{}"}}"#, b64(key.as_bytes()));
138    b64(&Sha256::digest(canonical.as_bytes()))
139}
140
141/// base64url(sha256(token)) — a proof's `ath`.
142pub fn token_hash(token: &str) -> String {
143    b64(&Sha256::digest(token.as_bytes()))
144}
145
146// ------------------------------------------------------------------ keys
147
148/// An Ed25519 key with its id (`key:<hex>`): a service's signing key, or a
149/// peer's own. `Debug` never shows the seed.
150#[derive(Clone)]
151pub struct PeerKey {
152    signing: SigningKey,
153    kid: String,
154}
155
156impl std::fmt::Debug for PeerKey {
157    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
158        f.debug_struct("PeerKey").field("kid", &self.kid).finish_non_exhaustive()
159    }
160}
161
162impl PeerKey {
163    /// A new key from the OS's randomness.
164    pub fn generate() -> Self {
165        let mut seed = [0u8; 32];
166        getrandom_02::getrandom(&mut seed).expect("the OS's randomness");
167        Self::from_seed(seed)
168    }
169
170    /// The key a 32-byte seed makes.
171    pub fn from_seed(seed: [u8; 32]) -> Self {
172        let signing = SigningKey::from_bytes(&seed);
173        let kid = principal_of(&signing.verifying_key());
174        Self { signing, kid }
175    }
176
177    /// The key in `path` (a 32-byte seed, raw or base64 — synapse's key
178    /// file), made there (0600) when there is none. A file readable by
179    /// others is refused.
180    pub fn load_or_create(path: &Path) -> Result<Self, String> {
181        let shown = path.display();
182        // KEEL-19 (P5): asked of the path itself, never what a link names.
183        let missing = matches!(std::fs::symlink_metadata(path), Err(e) if e.kind() == std::io::ErrorKind::NotFound);
184        if missing {
185            let key = Self::generate();
186            if let Some(dir) = path.parent() {
187                std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
188            }
189            let text = base64::engine::general_purpose::STANDARD.encode(key.signing.to_bytes());
190            write_private(path, text.as_bytes()).map_err(|e| format!("the key file {shown}: {e}"))?;
191            return Ok(key);
192        }
193        let raw = read_private(path).map_err(|e| format!("the key file {e}"))?;
194        let text: Vec<u8> = raw.iter().copied().filter(|b| !b.is_ascii_whitespace()).collect();
195        let engines = [
196            &base64::engine::general_purpose::STANDARD,
197            &base64::engine::general_purpose::URL_SAFE,
198            &base64::engine::general_purpose::STANDARD_NO_PAD,
199            &base64::engine::general_purpose::URL_SAFE_NO_PAD,
200        ];
201        let seed: [u8; 32] = engines
202            .iter()
203            .find_map(|e| e.decode(&text).ok().and_then(|b| <[u8; 32]>::try_from(b.as_slice()).ok()))
204            .or_else(|| <[u8; 32]>::try_from(raw.as_slice()).ok())
205            .ok_or_else(|| format!("the key file {shown} holds no 32-byte seed"))?;
206        Ok(Self::from_seed(seed))
207    }
208
209    /// DYNAUTH-7: write it to `path`, replacing what is there (a new file
210    /// beside it, 0600, renamed into place).
211    pub fn save(&self, path: &Path) -> Result<(), String> {
212        let tmp = path.with_extension("key.tmp");
213        let _ = std::fs::remove_file(&tmp);
214        let text = base64::engine::general_purpose::STANDARD.encode(self.signing.to_bytes());
215        write_private(&tmp, text.as_bytes()).map_err(|e| format!("{}: {e}", tmp.display()))?;
216        std::fs::rename(&tmp, path).map_err(|e| format!("{}: {e}", path.display()))
217    }
218
219    /// Its id: `key:<hex>` of its public half.
220    pub fn kid(&self) -> &str {
221        &self.kid
222    }
223
224    /// Its public half.
225    pub fn public(&self) -> VerifyingKey {
226        self.signing.verifying_key()
227    }
228
229    /// Its signing half, inside the crate (KEEL-19: a child dial's proof).
230    pub(crate) fn signing(&self) -> &SigningKey {
231        &self.signing
232    }
233
234    /// Its RFC 7638 thumbprint.
235    pub fn thumbprint(&self) -> String {
236        thumbprint(&self.public())
237    }
238
239    /// Its public half as a JWK.
240    pub fn jwk(&self) -> Jwk {
241        Jwk::of(&self.public())
242    }
243
244    /// A compact JWS of `claims` under `header` (whose `alg` this sets).
245    fn sign_compact(&self, mut header: Value, claims: &Value) -> String {
246        header["alg"] = json!(ALG);
247        let input = format!("{}.{}", b64(header.to_string().as_bytes()), b64(claims.to_string().as_bytes()));
248        let sig = self.signing.sign(input.as_bytes());
249        format!("{input}.{}", b64(&sig.to_bytes()))
250    }
251
252    /// The `_info` key proof: a signature over
253    /// `plexus-peer-key/v2\n<nonce>\n<backend>\n<asker>`, base64url —
254    /// KEEL-19: `asker` the principal of whoever asked, **as the prover
255    /// knows it**: the principal its connection proved (a mount's, a dialing
256    /// peer's), or, on its parent's own pipe, the one the parent names. A
257    /// proof made for one asker is refused by any other
258    /// ([`check_key_proof`]), so a peer cannot relay another's proof and be
259    /// registered under its key. The one form for a mount's child and a
260    /// dial-out's relay (KEEL-8).
261    pub fn key_proof_for(&self, nonce: &str, backend: &str, asker: &str) -> String {
262        b64(&self.signing.sign(key_proof_input(nonce, backend, asker).as_bytes()).to_bytes())
263    }
264
265    /// 0.11.0's `_info` key proof, bound to no asker (`plexus-peer-key/v1`):
266    /// nothing in 0.11.1 accepts it. KEEL-19: use [`Self::key_proof_for`].
267    #[deprecated(since = "0.11.1", note = "a key proof bound to no asker can be relayed; use `key_proof_for(nonce, backend, asker)`")]
268    pub fn key_proof(&self, nonce: &str, backend: &str) -> String {
269        b64(&self.signing.sign(format!("plexus-peer-key/v1\n{nonce}\n{backend}").as_bytes()).to_bytes())
270    }
271}
272
273fn key_proof_input(nonce: &str, backend: &str, asker: &str) -> String {
274    format!("{KEY_PROOF_CONTEXT}\n{nonce}\n{backend}\n{asker}")
275}
276
277/// 0.11.0's check of a key proof bound to no asker. KEEL-19: it refuses
278/// every proof — an unbound proof can be relayed by another peer — naming
279/// [`check_key_proof_for`].
280#[deprecated(since = "0.11.1", note = "refuses every proof: use `check_key_proof_for(key, proof, nonce, backend, asker)`")]
281pub fn check_key_proof(key: &str, _proof: &str, _nonce: &str, _backend: &str) -> Result<VerifyingKey, TokenError> {
282    Err(TokenError::Refused(format!("a key proof bound to no asker is refused (the key {key}): check it with `check_key_proof_for`, over the asker it was made for")))
283}
284
285/// Check a peer's `_info` key proof: `key` (`key:<hex>`) signed `nonce`,
286/// `backend` and `asker` — the checker's own principal, as the prover was
287/// to know it — with [`PeerKey::key_proof`]. A proof made for another
288/// asker does not verify.
289pub fn check_key_proof_for(key: &str, proof: &str, nonce: &str, backend: &str, asker: &str) -> Result<VerifyingKey, TokenError> {
290    let vk = key_of(key).ok_or_else(|| TokenError::Malformed(format!("`{key}` is not an Ed25519 key")))?;
291    let sig = signature_of(proof)?;
292    vk.verify_strict(key_proof_input(nonce, backend, asker).as_bytes(), &sig).map_err(|_| TokenError::Signature)?;
293    Ok(vk)
294}
295
296fn write_private(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
297    use std::io::Write;
298    let mut o = std::fs::OpenOptions::new();
299    // `create_new` is O_CREAT|O_EXCL: it never opens what is there, a link
300    // included.
301    o.write(true).create_new(true);
302    #[cfg(unix)]
303    {
304        use std::os::unix::fs::OpenOptionsExt;
305        o.mode(0o600).custom_flags(libc::O_NOFOLLOW);
306    }
307    o.open(path)?.write_all(bytes)
308}
309
310/// KEEL-19 (P5): a private file's bytes — opened without following a
311/// symbolic link (`O_NOFOLLOW`), a regular file, owned by this process's
312/// effective user, and neither group nor others with any access. The error
313/// names the path.
314pub(crate) fn read_private(path: &Path) -> Result<Vec<u8>, String> {
315    use std::io::Read;
316    let shown = path.display();
317    let mut o = std::fs::OpenOptions::new();
318    o.read(true);
319    #[cfg(unix)]
320    {
321        use std::os::unix::fs::OpenOptionsExt;
322        o.custom_flags(libc::O_NOFOLLOW);
323    }
324    let mut f = o.open(path).map_err(|e| match e.raw_os_error() {
325        #[cfg(unix)]
326        Some(libc::ELOOP) => format!("{shown} is a symbolic link: a private file is never read through one"),
327        _ => format!("{shown}: {e}"),
328    })?;
329    let md = f.metadata().map_err(|e| format!("{shown}: {e}"))?;
330    if !md.is_file() {
331        return Err(format!("{shown} is not a regular file"));
332    }
333    #[cfg(unix)]
334    {
335        use std::os::unix::fs::MetadataExt;
336        // SAFETY: geteuid has no preconditions and cannot fail.
337        let me = unsafe { libc::geteuid() };
338        if md.uid() != me {
339            return Err(format!("{shown} is owned by uid {}, not by this user ({me})", md.uid()));
340        }
341        if md.mode() & 0o077 != 0 {
342            return Err(format!("{shown} is readable by others (mode {:o}); a key is kept 0600", md.mode() & 0o777));
343        }
344    }
345    let mut out = Vec::new();
346    f.read_to_end(&mut out).map_err(|e| format!("{shown}: {e}"))?;
347    Ok(out)
348}
349
350/// KEEL-19 (P5, KEEL-25) · `dir` as a private directory: made (0700, its
351/// parents as the umask makes them) when missing; refused — naming it —
352/// when it is a symbolic link, not a directory, not this process's
353/// effective user's, or open to group or others in any way.
354pub fn ensure_private_dir(dir: &Path) -> Result<(), String> {
355    let shown = dir.display();
356    match std::fs::symlink_metadata(dir) {
357        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
358            if let Some(parent) = dir.parent().filter(|p| !p.as_os_str().is_empty()) {
359                std::fs::create_dir_all(parent).map_err(|e| format!("{}: {e}", parent.display()))?;
360            }
361            let mut b = std::fs::DirBuilder::new();
362            #[cfg(unix)]
363            {
364                use std::os::unix::fs::DirBuilderExt;
365                b.mode(0o700);
366            }
367            b.create(dir).map_err(|e| format!("{shown}: {e}"))?;
368            ensure_private_dir(dir)
369        }
370        Err(e) => Err(format!("{shown}: {e}")),
371        Ok(md) => {
372            if md.file_type().is_symlink() {
373                return Err(format!("{shown} is a symbolic link: a private directory is never one"));
374            }
375            if !md.is_dir() {
376                return Err(format!("{shown} is not a directory"));
377            }
378            #[cfg(unix)]
379            {
380                use std::os::unix::fs::MetadataExt;
381                // SAFETY: geteuid has no preconditions and cannot fail.
382                let me = unsafe { libc::geteuid() };
383                if md.uid() != me {
384                    return Err(format!("{shown} is owned by uid {}, not by this user ({me})", md.uid()));
385                }
386                if md.mode() & 0o077 != 0 {
387                    return Err(format!("{shown} is open to others (mode {:o}); it is kept 0700", md.mode() & 0o777));
388                }
389            }
390            Ok(())
391        }
392    }
393}
394
395/// KEEL-19 (P5): [`read_private`] for a file that may be missing (`None`).
396pub fn read_private_if_any(path: &Path) -> Result<Option<Vec<u8>>, String> {
397    match std::fs::symlink_metadata(path) {
398        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
399        _ => read_private(path).map(Some),
400    }
401}
402
403fn signature_of(s: &str) -> Result<Signature, TokenError> {
404    let bytes = unb64(s)?;
405    let arr: [u8; 64] = bytes.as_slice().try_into().map_err(|_| TokenError::Malformed("a signature is 64 bytes".into()))?;
406    Ok(Signature::from_bytes(&arr))
407}
408
409/// A public key as a JWK (RFC 8037: `kty` OKP, `crv` Ed25519).
410#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
411pub struct Jwk {
412    pub kty: String,
413    pub crv: String,
414    pub x: String,
415    #[serde(default, skip_serializing_if = "Option::is_none")]
416    pub kid: Option<String>,
417    #[serde(default, skip_serializing_if = "Option::is_none")]
418    pub alg: Option<String>,
419    #[serde(rename = "use", default, skip_serializing_if = "Option::is_none")]
420    pub use_: Option<String>,
421}
422
423impl Jwk {
424    /// `key` as a signing JWK, its `kid` its principal.
425    pub fn of(key: &VerifyingKey) -> Self {
426        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()) }
427    }
428
429    /// The key it holds, if it is an Ed25519 one.
430    pub fn key(&self) -> Result<VerifyingKey, TokenError> {
431        if self.kty != "OKP" || self.crv != "Ed25519" || self.alg.as_deref().is_some_and(|a| a != ALG) {
432            return Err(TokenError::Algorithm(format!("a JWK of kty {} crv {}: only OKP Ed25519 (EdDSA)", self.kty, self.crv)));
433        }
434        let bytes = unb64(&self.x)?;
435        let arr: [u8; 32] = bytes.as_slice().try_into().map_err(|_| TokenError::Malformed("an Ed25519 key is 32 bytes".into()))?;
436        VerifyingKey::from_bytes(&arr).map_err(|_| TokenError::Malformed("not an Ed25519 point".into()))
437    }
438}
439
440/// A JWK Set (RFC 7517 §5): what `dyn.jwks` answers.
441#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
442pub struct Jwks {
443    pub keys: Vec<Jwk>,
444}
445
446// ------------------------------------------------------------------ claims
447
448/// One actor of the chain (RFC 8693 §4.1), the prior ones nested.
449#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
450pub struct Actor {
451    pub sub: String,
452    #[serde(default, skip_serializing_if = "Option::is_none")]
453    pub act: Option<Box<Actor>>,
454}
455
456impl Actor {
457    /// The chain, nearest first.
458    pub fn chain(&self) -> Vec<String> {
459        let mut out = vec![self.sub.clone()];
460        let mut next = self.act.as_deref();
461        while let Some(a) = next {
462            out.push(a.sub.clone());
463            next = a.act.as_deref();
464        }
465        out
466    }
467
468    /// `sub` acting, after `prior`.
469    pub fn after(sub: impl Into<String>, prior: Option<Actor>) -> Self {
470        Self { sub: sub.into(), act: prior.map(Box::new) }
471    }
472}
473
474/// The key a token is bound to (RFC 7800 `cnf`, RFC 9449 `jkt`).
475#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
476pub struct Cnf {
477    pub jkt: String,
478}
479
480/// A peer token's claims.
481#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
482pub struct PeerClaims {
483    pub iss: String,
484    pub sub: String,
485    #[serde(default, skip_serializing_if = "Option::is_none")]
486    pub act: Option<Actor>,
487    pub aud: String,
488    /// `grant@scope` entries; on the wire one space-separated string
489    /// (RFC 8693 §4.2).
490    #[serde(with = "space_separated")]
491    pub scope: Vec<String>,
492    #[serde(default, skip_serializing_if = "Option::is_none")]
493    pub cnf: Option<Cnf>,
494    pub call: String,
495    pub method: String,
496    pub jti: String,
497    pub iat: u64,
498    pub exp: u64,
499}
500
501mod space_separated {
502    use serde::{Deserialize, Deserializer, Serializer};
503    pub fn serialize<S: Serializer>(v: &[String], s: S) -> Result<S::Ok, S::Error> {
504        s.serialize_str(&v.join(" "))
505    }
506    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<String>, D::Error> {
507        let s = String::deserialize(d)?;
508        Ok(s.split(' ').filter(|x| !x.is_empty()).map(str::to_string).collect())
509    }
510}
511
512impl PeerClaims {
513    /// The actor chain, nearest first (empty when nobody acted).
514    pub fn actors(&self) -> Vec<String> {
515        self.act.as_ref().map(Actor::chain).unwrap_or_default()
516    }
517
518    /// The scopes the token holds `grant` on (`["*"]`, `["MENGER"]`, `[]`).
519    pub fn scopes_for(&self, grant: &str) -> Vec<String> {
520        self.scope.iter().filter_map(|e| e.rsplit_once('@').filter(|(g, _)| *g == grant).map(|(_, s)| s.to_string())).collect()
521    }
522}
523
524/// `grant@scope` split.
525fn entry(e: &str) -> Option<(&str, &str)> {
526    e.rsplit_once('@')
527}
528
529/// Whether `inner`'s scope lies within `outer`'s (`*` holds every one).
530fn scope_within(inner: &str, outer: &str) -> bool {
531    outer == "*" || inner == outer
532}
533
534/// Whether every entry of `inner` is held by `outer`: the same grant, on
535/// the same scope or within one `outer` holds (`*`).
536pub fn is_within(inner: &[String], outer: &[String]) -> bool {
537    inner.iter().all(|i| match entry(i) {
538        Some((g, s)) => outer.iter().filter_map(|o| entry(o)).any(|(og, os)| og == g && scope_within(s, os)),
539        None => false,
540    })
541}
542
543/// The scope an exchange may give: `requested` (all of `presented` when
544/// `None`), each entry kept only where `presented` holds it — narrowed to
545/// the inner scope, never widened. RFC 8693 §2.1 downscoping.
546pub fn narrow(requested: Option<&[String]>, presented: &[String]) -> Vec<String> {
547    let Some(req) = requested else { return presented.to_vec() };
548    let mut out: Vec<String> = Vec::new();
549    for r in req {
550        let Some((g, s)) = entry(r) else { continue };
551        for (pg, ps) in presented.iter().filter_map(|p| entry(p)) {
552            if pg != g {
553                continue;
554            }
555            let kept = if scope_within(s, ps) {
556                Some(s)
557            } else if scope_within(ps, s) {
558                Some(ps)
559            } else {
560                None
561            };
562            if let Some(k) = kept {
563                let e = format!("{g}@{k}");
564                if !out.contains(&e) {
565                    out.push(e);
566                }
567            }
568        }
569    }
570    out
571}
572
573/// The scope a forwarded call's token holds (D3: the caller's reach ∩ the
574/// peer's needs ∩ consent): the forwarded grant on each scope the call was
575/// admitted on (`reach`, `["*"]` when everywhere), and each need's grant on
576/// each scope both its consent and the reach hold. Never a scope the reach
577/// does not hold.
578pub fn mint_scope(forwarded: Option<&str>, reach: &[String], needs: &[(String, Vec<String>)]) -> Vec<String> {
579    let mut out: Vec<String> = Vec::new();
580    let mut push = |g: &str, s: &str| {
581        let e = format!("{g}@{s}");
582        if !out.contains(&e) {
583            out.push(e);
584        }
585    };
586    let everywhere = reach.iter().any(|r| r == "*");
587    if let Some(g) = forwarded {
588        for r in reach {
589            push(g, r);
590        }
591    }
592    for (g, consented) in needs {
593        let any = consented.iter().any(|c| c == "*");
594        let scopes: Vec<&String> = match (everywhere, any) {
595            (true, _) => consented.iter().collect(),
596            (false, true) => reach.iter().collect(),
597            (false, false) => consented.iter().filter(|c| reach.contains(c)).collect(),
598        };
599        for s in scopes {
600            push(g, s);
601        }
602    }
603    out
604}
605
606/// DYNAUTH-6 (RFC 8693): the scope of the token for an onward call — one a
607/// peer made back through its service under `presented`, which reaches
608/// another peer. Never wider than `presented`: each need of the next peer
609/// only where `presented` holds the same grant ([`narrow`]); the forwarded
610/// grant (the next peer's terms) only on the scopes where `presented` holds
611/// `admitted` — the grant the service admitted the onward call on, in its
612/// own terms (`dyn.{peer}`). Within `reach` as [`mint_scope`] is.
613pub fn onward_scope(presented: &PeerClaims, admitted: Option<&str>, forwarded: Option<&str>, reach: &[String], needs: &[(String, Vec<String>)]) -> Vec<String> {
614    let mut out = narrow(Some(&mint_scope(None, reach, needs)), &presented.scope);
615    if let (Some(a), Some(f)) = (admitted, forwarded) {
616        for held in presented.scopes_for(a) {
617            for r in reach {
618                let s = if scope_within(r, &held) {
619                    r.as_str()
620                } else if scope_within(&held, r) {
621                    held.as_str()
622                } else {
623                    continue;
624                };
625                let e = format!("{f}@{s}");
626                if !out.contains(&e) {
627                    out.push(e);
628                }
629            }
630        }
631    }
632    out
633}
634
635// ------------------------------------------------------------------ errors
636
637/// Why a token or a proof is refused. Says what, never the token.
638#[derive(Debug, Clone, PartialEq, Eq)]
639pub enum TokenError {
640    Malformed(String),
641    /// `alg` not EdDSA, or a key of another kind.
642    Algorithm(String),
643    /// `typ` not the one expected.
644    Type(String),
645    /// `kid` names no key the verifier trusts.
646    UnknownKey(String),
647    Signature,
648    /// `aud` is another's.
649    Audience { want: String, got: String },
650    Expired,
651    /// `iat` in the future, past the skew.
652    NotYet,
653    /// `exp − iat` past [`MAX_LIFETIME`].
654    Lifetime(u64),
655    Replayed,
656    /// Presented for another call or method than it names.
657    Binding(String),
658    /// A proof of possession missing or wrong.
659    Proof(String),
660    /// A scope that is not within the one it must be.
661    Scope(String),
662    /// The issuer refuses to mint (revoked, no caller).
663    Refused(String),
664}
665
666impl std::fmt::Display for TokenError {
667    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
668        match self {
669            Self::Malformed(w) => write!(f, "a malformed token: {w}"),
670            Self::Algorithm(w) => write!(f, "algorithm refused: {w}"),
671            Self::Type(w) => write!(f, "type refused: {w}"),
672            Self::UnknownKey(k) => write!(f, "signed by a key not trusted here ({k})"),
673            Self::Signature => write!(f, "the signature does not verify"),
674            Self::Audience { want, got } => write!(f, "addressed to {got}, not to {want}"),
675            Self::Expired => write!(f, "expired"),
676            Self::NotYet => write!(f, "issued in the future"),
677            Self::Lifetime(s) => write!(f, "lives {s} s, past {} s", MAX_LIFETIME.as_secs()),
678            Self::Replayed => write!(f, "already used (replayed)"),
679            Self::Binding(w) => write!(f, "presented for another call: {w}"),
680            Self::Proof(w) => write!(f, "no valid proof of possession: {w}"),
681            Self::Scope(w) => write!(f, "scope refused: {w}"),
682            Self::Refused(w) => write!(f, "{w}"),
683        }
684    }
685}
686
687impl std::error::Error for TokenError {}
688
689// ------------------------------------------------------------------ JWS
690
691struct Parsed {
692    header: Value,
693    payload: Vec<u8>,
694    input: String,
695    sig: Signature,
696}
697
698/// Split and decode a compact JWS; the algorithm checked here, before
699/// anything else is believed: `alg` must be exactly `EdDSA` (`none`,
700/// `HS256`, anything else refused — the verifier chooses the algorithm,
701/// never the token), and no `jku`/`x5u`/`crit` is honoured.
702fn parse(token: &str, typ: &str) -> Result<Parsed, TokenError> {
703    let mut parts = token.split('.');
704    let (Some(h), Some(p), Some(s), None) = (parts.next(), parts.next(), parts.next(), parts.next()) else {
705        return Err(TokenError::Malformed("a compact JWS has three parts".into()));
706    };
707    let header: Value = serde_json::from_slice(&unb64(h)?).map_err(|_| TokenError::Malformed("the header is not JSON".into()))?;
708    match header.get("alg").and_then(Value::as_str) {
709        Some(ALG) => {}
710        other => return Err(TokenError::Algorithm(format!("alg {:?}: only EdDSA", other.unwrap_or("(none)")))),
711    }
712    if header.get("crit").is_some() {
713        return Err(TokenError::Malformed("`crit` is not understood here".into()));
714    }
715    match header.get("typ").and_then(Value::as_str) {
716        Some(t) if t.eq_ignore_ascii_case(typ) => {}
717        other => return Err(TokenError::Type(format!("typ {:?}, not {typ}", other.unwrap_or("(none)")))),
718    }
719    Ok(Parsed { header, payload: unb64(p)?, input: format!("{h}.{p}"), sig: signature_of(s)? })
720}
721
722// ------------------------------------------------------------------ verify
723
724/// What a token must also say to be taken for this presentation.
725#[derive(Debug, Clone, Default)]
726pub struct Expect<'a> {
727    /// The forwarded call's id (`hop.call`).
728    pub call: Option<&'a str>,
729    /// The method it is presented for (in the verifier's terms).
730    pub method: Option<&'a str>,
731}
732
733/// Checks tokens addressed to one audience, from the issuers it trusts,
734/// each `jti` once.
735pub struct Verifier {
736    audience: String,
737    issuers: RwLock<BTreeMap<String, VerifyingKey>>,
738    seen: Mutex<HashMap<String, u64>>,
739}
740
741impl std::fmt::Debug for Verifier {
742    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
743        f.debug_struct("Verifier").field("audience", &self.audience).field("issuers", &self.issuers.read().unwrap().keys().collect::<Vec<_>>()).finish()
744    }
745}
746
747impl Verifier {
748    /// A verifier for tokens addressed to `audience`, trusting `jwks`.
749    pub fn new(audience: impl Into<String>, jwks: &Jwks) -> Result<Self, TokenError> {
750        let v = Self { audience: audience.into(), issuers: RwLock::default(), seen: Mutex::default() };
751        v.trust(jwks)?;
752        Ok(v)
753    }
754
755    /// The audience it takes.
756    pub fn audience(&self) -> &str {
757        &self.audience
758    }
759
760    /// Trust exactly `jwks` from now (a rotation: the old key goes once the
761    /// issuer's JWKS drops it).
762    pub fn trust(&self, jwks: &Jwks) -> Result<(), TokenError> {
763        let mut keys = BTreeMap::new();
764        for k in &jwks.keys {
765            let vk = k.key()?;
766            keys.insert(k.kid.clone().unwrap_or_else(|| principal_of(&vk)), vk);
767        }
768        *self.issuers.write().unwrap() = keys;
769        Ok(())
770    }
771
772    /// Verify `token` now.
773    pub fn verify(&self, token: &str, expect: &Expect<'_>) -> Result<PeerClaims, TokenError> {
774        self.verify_at(token, expect, now())
775    }
776
777    /// Verify `token` as of `now` (seconds since the epoch).
778    pub fn verify_at(&self, token: &str, expect: &Expect<'_>, now: u64) -> Result<PeerClaims, TokenError> {
779        let claims = self.inspect_at(token, expect, now)?;
780        self.admit(&claims, now)?;
781        Ok(claims)
782    }
783
784    /// KEEL-19: every check of [`Self::verify_at`] but the replay cache —
785    /// nothing is recorded, so a presentation refused afterwards (no proof
786    /// by its sender) does not burn the token for the one who may present
787    /// it. [`Self::admit`] records it once the presentation is taken.
788    pub(crate) fn inspect_at(&self, token: &str, expect: &Expect<'_>, now: u64) -> Result<PeerClaims, TokenError> {
789        let parsed = parse(token, TOKEN_TYP)?;
790        let kid = parsed.header.get("kid").and_then(Value::as_str).unwrap_or_default().to_string();
791        let key = self.issuers.read().unwrap().get(&kid).copied().ok_or(TokenError::UnknownKey(kid.clone()))?;
792        key.verify_strict(parsed.input.as_bytes(), &parsed.sig).map_err(|_| TokenError::Signature)?;
793        let claims: PeerClaims = serde_json::from_slice(&parsed.payload).map_err(|e| TokenError::Malformed(format!("its claims: {e}")))?;
794        if claims.iss != kid {
795            return Err(TokenError::Malformed("`iss` is not the key that signed it".into()));
796        }
797        check_times(&claims, now)?;
798        if claims.aud != self.audience {
799            return Err(TokenError::Audience { want: self.audience.clone(), got: claims.aud });
800        }
801        if let Some(call) = expect.call.filter(|c| *c != claims.call) {
802            return Err(TokenError::Binding(format!("it names call {}, presented under {call}", claims.call)));
803        }
804        if let Some(method) = expect.method.filter(|m| *m != claims.method) {
805            return Err(TokenError::Binding(format!("it names {}, presented for {method}", claims.method)));
806        }
807        Ok(claims)
808    }
809
810    /// KEEL-19: record `claims`' `jti` as used: refused when it was before.
811    pub(crate) fn admit(&self, claims: &PeerClaims, now: u64) -> Result<(), TokenError> {
812        let mut seen = self.seen.lock().unwrap();
813        seen.retain(|_, exp| *exp + SKEW.as_secs() >= now);
814        if seen.insert(claims.jti.clone(), claims.exp).is_some() {
815            return Err(TokenError::Replayed);
816        }
817        Ok(())
818    }
819
820    /// `jti`s held now (the replay cache's size).
821    pub fn held(&self) -> usize {
822        self.seen.lock().unwrap().len()
823    }
824}
825
826fn check_times(claims: &PeerClaims, now: u64) -> Result<(), TokenError> {
827    if claims.exp < claims.iat || claims.exp - claims.iat > MAX_LIFETIME.as_secs() {
828        return Err(TokenError::Lifetime(claims.exp.saturating_sub(claims.iat)));
829    }
830    if claims.iat > now + SKEW.as_secs() {
831        return Err(TokenError::NotYet);
832    }
833    if now > claims.exp + SKEW.as_secs() {
834        return Err(TokenError::Expired);
835    }
836    Ok(())
837}
838
839// ------------------------------------------------------------------ proof
840
841/// A proof of possession by `key` for presenting `token` for `method`
842/// under `call` (see the module docs).
843pub fn prove(key: &PeerKey, token: &str, method: &str, call: &str) -> String {
844    prove_at(key, token, method, call, now())
845}
846
847/// [`prove`] as of `iat`.
848pub fn prove_at(key: &PeerKey, token: &str, method: &str, call: &str, iat: u64) -> String {
849    let header = json!({ "typ": PROOF_TYP, "jwk": key.jwk() });
850    let claims = json!({ "ath": token_hash(token), "jti": random_id(), "method": method, "call": call, "iat": iat });
851    key.sign_compact(header, &claims)
852}
853
854/// The proofs a presenter's side has seen, each once (by its `jti`, kept
855/// for twice the skew).
856#[derive(Debug, Default)]
857pub struct ProofCache(Mutex<HashMap<String, u64>>);
858
859/// Check `proof` for presenting `token` (whose claims are `claims`) for
860/// `method` under `call`, as of `now`: signed by the key `claims.cnf.jkt`
861/// names, over this token, method and call, fresh, and not seen before.
862pub fn check_proof(proof: &str, token: &str, claims: &PeerClaims, method: &str, call: &str, now: u64, seen: &ProofCache) -> Result<(), TokenError> {
863    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()))?;
864    check_proof_by(proof, token, jkt, method, call, now, seen)
865}
866
867/// KEEL-19: [`check_proof`] by the key whose thumbprint is `jkt` (the
868/// issuer's, for a forwarded hop's proof).
869pub(crate) fn check_proof_by(proof: &str, token: &str, jkt: &str, method: &str, call: &str, now: u64, seen: &ProofCache) -> Result<(), TokenError> {
870    let parsed = parse(proof, PROOF_TYP).map_err(|e| TokenError::Proof(e.to_string()))?;
871    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()))?;
872    let key = jwk.key().map_err(|e| TokenError::Proof(e.to_string()))?;
873    if thumbprint(&key) != jkt {
874        return Err(TokenError::Proof("signed by another key than the token is bound to".into()));
875    }
876    key.verify_strict(parsed.input.as_bytes(), &parsed.sig).map_err(|_| TokenError::Proof("its signature does not verify".into()))?;
877    let c: Value = serde_json::from_slice(&parsed.payload).map_err(|_| TokenError::Proof("its claims are not JSON".into()))?;
878    let s = |k: &str| c.get(k).and_then(Value::as_str).unwrap_or_default();
879    if s("ath") != token_hash(token) {
880        return Err(TokenError::Proof("made for another token".into()));
881    }
882    if s("method") != method || s("call") != call {
883        return Err(TokenError::Proof(format!("made for {} under {}, presented for {method} under {call}", s("method"), s("call"))));
884    }
885    let iat = c.get("iat").and_then(Value::as_u64).unwrap_or_default();
886    if iat + SKEW.as_secs() < now || iat > now + SKEW.as_secs() {
887        return Err(TokenError::Proof("not fresh (iat past the skew)".into()));
888    }
889    let jti = s("jti");
890    if jti.is_empty() {
891        return Err(TokenError::Proof("no `jti`".into()));
892    }
893    let mut seen = seen.0.lock().unwrap();
894    seen.retain(|_, t| *t + 2 * SKEW.as_secs() >= now);
895    if seen.insert(jti.to_string(), iat).is_some() {
896        return Err(TokenError::Proof("replayed".into()));
897    }
898    Ok(())
899}
900
901// ------------------------------------------------------------------ audit
902
903/// What was done with a token.
904#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
905#[serde(rename_all = "snake_case")]
906pub enum AuditKind {
907    Mint,
908    Exchange,
909}
910
911/// One audit record (TM-7): who acted through whom, for what. Never the
912/// token, a signature or a proof.
913#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
914pub struct AuditRecord {
915    pub kind: AuditKind,
916    pub iss: String,
917    pub sub: String,
918    /// The actor chain, nearest first.
919    pub act: Vec<String>,
920    pub aud: String,
921    pub scope: Vec<String>,
922    pub call: String,
923    pub jti: String,
924    pub exp: u64,
925    pub method: String,
926    /// For an exchange: the call of the token presented — what joins this
927    /// hop's record to the one before it.
928    #[serde(default, skip_serializing_if = "Option::is_none")]
929    pub presented_call: Option<String>,
930}
931
932impl AuditRecord {
933    fn of(kind: AuditKind, c: &PeerClaims, presented: Option<&PeerClaims>) -> Self {
934        Self {
935            kind,
936            iss: c.iss.clone(),
937            sub: c.sub.clone(),
938            act: c.actors(),
939            aud: c.aud.clone(),
940            scope: c.scope.clone(),
941            call: c.call.clone(),
942            jti: c.jti.clone(),
943            exp: c.exp,
944            method: c.method.clone(),
945            presented_call: presented.map(|p| p.call.clone()),
946        }
947    }
948}
949
950/// KEEL-19: why an exchange was refused, as a word.
951#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
952#[serde(rename_all = "snake_case")]
953#[non_exhaustive]
954pub enum ExchangeRefusal {
955    /// The subject token is not one this issuer minted, or no longer lives.
956    Subject,
957    /// No proof of possession by the subject token's key, or a wrong one.
958    Proof,
959    /// The presenter is not a peer mounted in this service.
960    Presenter,
961    /// The presenter (or the audience) is revoked.
962    Revoked,
963    /// The presenter holds no consented need that covers the audience and
964    /// the method asked.
965    NotConsented,
966    /// The audience is not a peer that proved a key.
967    Audience,
968    /// This subject token was exchanged for this audience and method before.
969    Again,
970}
971
972impl ExchangeRefusal {
973    /// The word (`not_consented`).
974    pub fn as_str(&self) -> &'static str {
975        match self {
976            Self::Subject => "subject",
977            Self::Proof => "proof",
978            Self::Presenter => "presenter",
979            Self::Revoked => "revoked",
980            Self::NotConsented => "not_consented",
981            Self::Audience => "audience",
982            Self::Again => "again",
983        }
984    }
985}
986
987impl std::fmt::Display for ExchangeRefusal {
988    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
989        f.write_str(self.as_str())
990    }
991}
992
993/// KEEL-19: one refused exchange (TM-7): who presented what, for whom, and
994/// why it was refused. Never the token, a signature or a proof.
995#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
996pub struct ExchangeRefused {
997    pub iss: String,
998    /// The presenter: the subject token's audience (empty when the subject
999    /// token could not be read).
1000    pub presenter: String,
1001    pub sub: String,
1002    /// The audience asked for (a peer's name, as the exchange named it).
1003    pub aud: String,
1004    pub method: String,
1005    /// The call and `jti` of the subject token.
1006    pub presented_call: String,
1007    pub presented_jti: String,
1008    pub reason: ExchangeRefusal,
1009    pub why: String,
1010}
1011
1012/// Where audit records go besides `tracing` (PRIVACY-1's sink, when it is).
1013pub trait TokenAudit: Send + Sync {
1014    fn record(&self, r: &AuditRecord);
1015    /// KEEL-19: an exchange refused. Nothing by default (the `tracing`
1016    /// event is always written).
1017    fn refused(&self, _r: &ExchangeRefused) {}
1018}
1019
1020fn audit_refused(sink: Option<&Arc<dyn TokenAudit>>, r: ExchangeRefused) {
1021    tracing::warn!(
1022        target: "plexus::audit",
1023        iss = %r.iss, presenter = %r.presenter, sub = %r.sub, aud = %r.aud, method = %r.method,
1024        presented_call = %r.presented_call, presented_jti = %r.presented_jti, reason = %r.reason, why = %r.why,
1025        "peer token exchange refused"
1026    );
1027    if let Some(s) = sink {
1028        s.refused(&r);
1029    }
1030}
1031
1032/// KEEL-19: what a service decided an exchange may give — the audience (its
1033/// name and the key it proved) and the scope of the token for it.
1034#[derive(Debug, Clone, PartialEq, Eq)]
1035pub struct Onward {
1036    /// The audience's name in the service (what the refusal and audit say).
1037    pub name: String,
1038    /// The audience's key (`key:<hex>`): `aud`; `None` for a child on the
1039    /// issuer's own pipe (`pipe:<name>`).
1040    pub peer_key: Option<String>,
1041    /// The scope of the token for it, decided (never read back from the
1042    /// subject token here: the decision is the service's).
1043    pub scope: Vec<String>,
1044}
1045
1046fn audit(sink: Option<&Arc<dyn TokenAudit>>, r: AuditRecord) {
1047    tracing::info!(
1048        target: "plexus::audit",
1049        kind = ?r.kind, iss = %r.iss, sub = %r.sub, act = ?r.act, aud = %r.aud,
1050        scope = %r.scope.join(" "), call = %r.call, jti = %r.jti, exp = r.exp, method = %r.method,
1051        presented_call = r.presented_call.as_deref().unwrap_or(""),
1052        "peer token"
1053    );
1054    if let Some(s) = sink {
1055        s.record(&r);
1056    }
1057}
1058
1059// ------------------------------------------------------------------ issue
1060
1061/// What one forwarded call's token is minted from.
1062#[derive(Debug, Clone)]
1063pub struct MintRequest {
1064    /// The original caller.
1065    pub sub: String,
1066    /// The peer: its key (`key:<hex>`), or `None` for a child on the
1067    /// issuer's own pipe (`aud` `pipe:<name>`, no `cnf`).
1068    pub peer_key: Option<String>,
1069    /// The mount's name (a pipe child's audience).
1070    pub name: String,
1071    pub scope: Vec<String>,
1072    pub call: String,
1073    pub method: String,
1074    /// When this mint is an exchange: the token presented, already
1075    /// verified, and who presented it (its audience).
1076    pub presented: Option<PeerClaims>,
1077}
1078
1079/// A service's token issuer: its signing key (rotatable, the old one kept
1080/// in the JWKS for one token lifetime and the skew), the lifetime it
1081/// mints, and the audit sink.
1082pub struct TokenIssuer {
1083    key: RwLock<PeerKey>,
1084    retired: Mutex<Vec<(PeerKey, u64)>>,
1085    ttl: Duration,
1086    sink: Option<Arc<dyn TokenAudit>>,
1087    /// KEEL-19: each (subject `jti`, audience, method) exchanged, until the
1088    /// subject token's `exp` and the skew: a subject is exchanged once each.
1089    exchanged: Mutex<HashMap<String, u64>>,
1090}
1091
1092impl std::fmt::Debug for TokenIssuer {
1093    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1094        f.debug_struct("TokenIssuer").field("kid", &self.kid()).field("ttl", &self.ttl).finish_non_exhaustive()
1095    }
1096}
1097
1098impl TokenIssuer {
1099    /// An issuer signing with `key`, minting tokens of [`MAX_LIFETIME`].
1100    pub fn new(key: PeerKey) -> Self {
1101        Self { key: RwLock::new(key), retired: Mutex::default(), ttl: MAX_LIFETIME, sink: None, exchanged: Mutex::default() }
1102    }
1103
1104    /// Tokens of `ttl` (at most [`MAX_LIFETIME`]).
1105    pub fn with_ttl(mut self, ttl: Duration) -> Self {
1106        self.ttl = ttl.min(MAX_LIFETIME);
1107        self
1108    }
1109
1110    /// Audit records also to `sink`.
1111    pub fn with_audit(mut self, sink: Arc<dyn TokenAudit>) -> Self {
1112        self.sink = Some(sink);
1113        self
1114    }
1115
1116    /// The signing key's id now.
1117    pub fn kid(&self) -> String {
1118        self.key.read().unwrap().kid().to_string()
1119    }
1120
1121    /// The lifetime it mints.
1122    pub fn ttl(&self) -> Duration {
1123        self.ttl
1124    }
1125
1126    /// The keys a peer verifies with: the current one, and each retired one
1127    /// while a token it signed may still be presented.
1128    pub fn jwks(&self) -> Jwks {
1129        let now = now();
1130        let mut retired = self.retired.lock().unwrap();
1131        retired.retain(|(_, until)| *until >= now);
1132        let mut keys = vec![self.key.read().unwrap().jwk()];
1133        keys.extend(retired.iter().map(|(k, _)| k.jwk()));
1134        Jwks { keys }
1135    }
1136
1137    /// Sign with `new` from now; the old key stays in [`Self::jwks`] for one
1138    /// token lifetime and the skew, then goes.
1139    pub fn rotate(&self, new: PeerKey) -> String {
1140        let old = std::mem::replace(&mut *self.key.write().unwrap(), new);
1141        let until = now() + self.ttl.as_secs() + SKEW.as_secs();
1142        self.retired.lock().unwrap().push((old, until));
1143        self.kid()
1144    }
1145
1146    /// KEEL-19: the service's proof that it sends this forwarded hop — a
1147    /// proof of possession ([`prove`]) by the key that signed `claims`'
1148    /// token (its `iss`), over the token, its method and its call. A
1149    /// verifying child takes a token bound to its own key only with this
1150    /// proof (`hop.proof`), checked against the JWKS it trusts: on a pipe and
1151    /// on a connection alike, whoever holds the token's bytes alone cannot
1152    /// present it.
1153    pub fn prove_forward(&self, token: &str, claims: &PeerClaims) -> Result<String, TokenError> {
1154        let key = {
1155            let now_key = self.key.read().unwrap();
1156            if now_key.kid() == claims.iss {
1157                now_key.clone()
1158            } else {
1159                self.retired.lock().unwrap().iter().find(|(k, _)| k.kid() == claims.iss).map(|(k, _)| k.clone()).ok_or_else(|| TokenError::UnknownKey(claims.iss.clone()))?
1160            }
1161        };
1162        Ok(prove(&key, token, &claims.method, &claims.call))
1163    }
1164
1165    /// Mint one forwarded call's token (an exchange when `req.presented`).
1166    pub fn mint(&self, req: MintRequest) -> Result<(String, PeerClaims), TokenError> {
1167        self.mint_at(req, now())
1168    }
1169
1170    /// [`Self::mint`] as of `now`.
1171    pub fn mint_at(&self, req: MintRequest, now: u64) -> Result<(String, PeerClaims), TokenError> {
1172        self.mint_bound(req, None, now)
1173    }
1174
1175    /// [`Self::mint_at`], its `cnf` the presenter's key when `presenter`
1176    /// names one (KEEL-19: a token its holder presents to the audience
1177    /// itself), else the audience's own (a token the service forwards).
1178    fn mint_bound(&self, req: MintRequest, presenter: Option<Cnf>, now: u64) -> Result<(String, PeerClaims), TokenError> {
1179        let key = self.key.read().unwrap().clone();
1180        let (aud, cnf) = match &req.peer_key {
1181            Some(k) => {
1182                let vk = key_of(k).ok_or_else(|| TokenError::Malformed(format!("`{k}` is not an Ed25519 key")))?;
1183                (k.clone(), Some(presenter.unwrap_or(Cnf { jkt: thumbprint(&vk) })))
1184            }
1185            None => (format!("pipe:{}", req.name), presenter),
1186        };
1187        let (sub, act, scope, kind) = match &req.presented {
1188            None => (req.sub.clone(), Some(Actor::after(key.kid(), None)), req.scope.clone(), AuditKind::Mint),
1189            Some(p) => {
1190                // RFC 8693: the subject stays; the presenter joins the
1191                // chain. The scope is the caller's to narrow (`exchange`,
1192                // `onward_scope`): never wider than the presented one's.
1193                let prior = Actor::after(p.aud.clone(), p.act.clone());
1194                (p.sub.clone(), Some(Actor::after(key.kid(), Some(prior))), req.scope.clone(), AuditKind::Exchange)
1195            }
1196        };
1197        let claims = PeerClaims {
1198            iss: key.kid().to_string(),
1199            sub,
1200            act,
1201            aud,
1202            scope,
1203            cnf,
1204            call: req.call,
1205            method: req.method,
1206            jti: random_id(),
1207            iat: now,
1208            exp: now + self.ttl.as_secs(),
1209        };
1210        let token = key.sign_compact(json!({ "typ": TOKEN_TYP, "kid": key.kid() }), &serde_json::to_value(&claims).unwrap_or_default());
1211        audit(self.sink.as_ref(), AuditRecord::of(kind, &claims, req.presented.as_ref()));
1212        Ok((token, claims))
1213    }
1214
1215    /// RFC 8693 token exchange, the primitive: `subject` (a token this
1216    /// issuer minted, presented by its audience with `proof`) becomes a
1217    /// token for `audience` (`peer_key`; `name` its name), its scope
1218    /// `requested` narrowed by the presented one — with no decision of
1219    /// whether the presenter may reach that audience. A service decides that
1220    /// with [`Self::exchange_decided`] (plexus-dyn's `dyn.exchange` does);
1221    /// the token is bound to the presenter's key and taken once per
1222    /// (subject `jti`, audience, method) either way.
1223    ///
1224    /// KEEL-19: **not for a service's method** — it decides nothing about
1225    /// the presenter. Kept public (hidden, deprecated) only because removing
1226    /// it would break 0.11's API.
1227    #[deprecated(since = "0.11.1", note = "undecided: a service exchanges with `exchange_decided`, which asks whether the presenter may reach the audience")]
1228    #[doc(hidden)]
1229    #[allow(clippy::too_many_arguments)]
1230    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> {
1231        let name = name.to_string();
1232        self.exchange_decided(subject, proof, &name, call, method, seen, |presented| {
1233            Ok(Onward { name: name.clone(), peer_key, scope: narrow(requested, &presented.scope) })
1234        })
1235    }
1236
1237    /// KEEL-19 · RFC 8693 token exchange, decided by the service: `subject`
1238    /// (a token this issuer minted, bound to its audience's key) presented
1239    /// with `proof` (by that key, for [`EXCHANGE`] under the token's `call`)
1240    /// becomes a token for the audience `decide` names, of the scope it
1241    /// decides — `decide` is handed the subject's claims (its `aud` is the
1242    /// presenter) and refuses with a [`ExchangeRefusal`] and why. The token
1243    /// is **bound to the presenter**: its `cnf` is the subject's, so the
1244    /// audience takes it only with the presenter's proof (`hop.proof`). A
1245    /// subject is exchanged once per (`jti`, audience, `method`). Every
1246    /// refusal is audited ([`ExchangeRefused`]); every exchange too.
1247    /// `audience` is the name asked for (what a refusal's record says).
1248    #[allow(clippy::too_many_arguments)]
1249    pub fn exchange_decided<F>(&self, subject: &str, proof: Option<&str>, audience: &str, call: &str, method: &str, seen: &ProofCache, decide: F) -> Result<(String, PeerClaims), TokenError>
1250    where
1251        F: FnOnce(&PeerClaims) -> Result<Onward, (ExchangeRefusal, String)>,
1252    {
1253        let refused = |p: Option<&PeerClaims>, reason: ExchangeRefusal, err: TokenError| {
1254            audit_refused(
1255                self.sink.as_ref(),
1256                ExchangeRefused {
1257                    iss: self.kid(),
1258                    presenter: p.map(|p| p.aud.clone()).unwrap_or_default(),
1259                    sub: p.map(|p| p.sub.clone()).unwrap_or_default(),
1260                    aud: audience.to_string(),
1261                    method: method.to_string(),
1262                    presented_call: p.map(|p| p.call.clone()).unwrap_or_default(),
1263                    presented_jti: p.map(|p| p.jti.clone()).unwrap_or_default(),
1264                    reason,
1265                    why: err.to_string(),
1266                },
1267            );
1268            err
1269        };
1270        let presented = self.verify_own(subject).map_err(|e| refused(None, ExchangeRefusal::Subject, e))?;
1271        // A token bound to no key (a pipe's) is its pipe's alone: it is
1272        // never exchanged by whoever holds its bytes.
1273        let Some(presenter) = presented.cnf.clone() else {
1274            return Err(refused(Some(&presented), ExchangeRefusal::Proof, TokenError::Proof("a token bound to no key (a pipe's) is not exchanged".into())));
1275        };
1276        let Some(proof) = proof.filter(|p| !p.is_empty()) else {
1277            return Err(refused(Some(&presented), ExchangeRefusal::Proof, TokenError::Proof("a key-bound token is exchanged with a proof".into())));
1278        };
1279        check_proof(proof, subject, &presented, EXCHANGE, &presented.call, now(), seen).map_err(|e| refused(Some(&presented), ExchangeRefusal::Proof, e))?;
1280        let onward = decide(&presented).map_err(|(reason, why)| refused(Some(&presented), reason, TokenError::Refused(why)))?;
1281        {
1282            let now = now();
1283            let mut done = self.exchanged.lock().unwrap();
1284            done.retain(|_, exp| *exp + SKEW.as_secs() >= now);
1285            let once = format!("{}\n{}\n{method}", presented.jti, onward.peer_key.as_deref().unwrap_or(&onward.name));
1286            if done.insert(once, presented.exp).is_some() {
1287                let why = format!("this token was exchanged for `{}` and `{method}` already: a subject token is exchanged once for each", onward.name);
1288                return Err(refused(Some(&presented), ExchangeRefusal::Again, TokenError::Refused(why)));
1289            }
1290        }
1291        let req = MintRequest { sub: presented.sub.clone(), peer_key: onward.peer_key, name: onward.name, scope: onward.scope, call: call.into(), method: method.into(), presented: Some(presented) };
1292        self.mint_bound(req, Some(presenter), now())
1293    }
1294
1295    /// A token this issuer minted (any audience), signature and times
1296    /// checked — what the issuer reads back when a peer presents it.
1297    pub fn verify_own(&self, token: &str) -> Result<PeerClaims, TokenError> {
1298        let parsed = parse(token, TOKEN_TYP)?;
1299        let kid = parsed.header.get("kid").and_then(Value::as_str).unwrap_or_default();
1300        let jwks = self.jwks();
1301        let key = jwks.keys.iter().find(|k| k.kid.as_deref() == Some(kid)).ok_or_else(|| TokenError::UnknownKey(kid.to_string()))?.key()?;
1302        key.verify_strict(parsed.input.as_bytes(), &parsed.sig).map_err(|_| TokenError::Signature)?;
1303        let claims: PeerClaims = serde_json::from_slice(&parsed.payload).map_err(|e| TokenError::Malformed(format!("its claims: {e}")))?;
1304        check_times(&claims, now())?;
1305        Ok(claims)
1306    }
1307}
1308
1309#[cfg(test)]
1310#[allow(deprecated)] // the undecided `exchange` primitive is tested as it is
1311mod tests {
1312    use super::*;
1313
1314    fn req(peer: &PeerKey) -> MintRequest {
1315        MintRequest {
1316            sub: "key:caller".into(),
1317            peer_key: Some(peer.kid().to_string()),
1318            name: "w".into(),
1319            scope: vec!["weather.forecast@*".into(), "shop.items@MENGER".into()],
1320            call: "call-1".into(),
1321            method: "far.weather.forecast".into(),
1322            presented: None,
1323        }
1324    }
1325
1326    fn header_of(token: &str) -> Value {
1327        serde_json::from_slice(&unb64(token.split('.').next().unwrap()).unwrap()).unwrap()
1328    }
1329
1330    fn claims_part(token: &str) -> Value {
1331        serde_json::from_slice(&unb64(token.split('.').nth(1).unwrap()).unwrap()).unwrap()
1332    }
1333
1334    /// Re-sign `token`'s parts as given — a forger with some key.
1335    fn forge(key: &PeerKey, header: Value, claims: Value) -> String {
1336        let input = format!("{}.{}", b64(header.to_string().as_bytes()), b64(claims.to_string().as_bytes()));
1337        format!("{input}.{}", b64(&key.signing.sign(input.as_bytes()).to_bytes()))
1338    }
1339
1340    #[test]
1341    fn a_token_signs_and_verifies() {
1342        let (host, peer) = (PeerKey::generate(), PeerKey::generate());
1343        let issuer = TokenIssuer::new(host.clone());
1344        let (token, minted) = issuer.mint(req(&peer)).unwrap();
1345        let h = header_of(&token);
1346        assert_eq!((h["alg"].as_str(), h["typ"].as_str(), h["kid"].as_str()), (Some("EdDSA"), Some(TOKEN_TYP), Some(host.kid())));
1347        let c = claims_part(&token);
1348        assert_eq!(c["scope"], "weather.forecast@* shop.items@MENGER", "space-separated on the wire");
1349        assert_eq!(c["cnf"]["jkt"], peer.thumbprint());
1350        assert_eq!(c["act"], json!({ "sub": host.kid() }));
1351        assert!(minted.exp - minted.iat <= 60);
1352        let v = Verifier::new(peer.kid(), &issuer.jwks()).unwrap();
1353        let got = v.verify(&token, &Expect { call: Some("call-1"), method: Some("far.weather.forecast") }).unwrap();
1354        assert_eq!(got, minted);
1355        assert_eq!(got.scopes_for("shop.items"), ["MENGER"]);
1356    }
1357
1358    #[test]
1359    fn a_token_for_another_audience_is_refused() {
1360        let (host, a, b) = (PeerKey::generate(), PeerKey::generate(), PeerKey::generate());
1361        let issuer = TokenIssuer::new(host);
1362        let (for_a, _) = issuer.mint(req(&a)).unwrap();
1363        let at_b = Verifier::new(b.kid(), &issuer.jwks()).unwrap();
1364        assert!(matches!(at_b.verify(&for_a, &Expect::default()), Err(TokenError::Audience { .. })));
1365    }
1366
1367    #[test]
1368    fn an_expired_or_future_or_long_token_is_refused() {
1369        let (host, peer) = (PeerKey::generate(), PeerKey::generate());
1370        let issuer = TokenIssuer::new(host.clone());
1371        let v = Verifier::new(peer.kid(), &issuer.jwks()).unwrap();
1372        let t0 = now();
1373        let (old, _) = issuer.mint_at(req(&peer), t0 - 200).unwrap();
1374        assert_eq!(v.verify_at(&old, &Expect::default(), t0), Err(TokenError::Expired));
1375        // Within the skew past `exp`, still taken; past it, not.
1376        let (t, c) = issuer.mint_at(req(&peer), t0).unwrap();
1377        assert!(v.verify_at(&t, &Expect::default(), c.exp + 29).is_ok());
1378        let (t, c) = issuer.mint_at(req(&peer), t0).unwrap();
1379        assert_eq!(v.verify_at(&t, &Expect::default(), c.exp + 31), Err(TokenError::Expired));
1380        let (future, _) = issuer.mint_at(req(&peer), t0 + 120).unwrap();
1381        assert_eq!(v.verify_at(&future, &Expect::default(), t0), Err(TokenError::NotYet));
1382        // A token that claims to live past 60 s, even signed by the host.
1383        let mut c = claims_part(&future);
1384        c["iat"] = json!(t0);
1385        c["exp"] = json!(t0 + 3600);
1386        let long = forge(&host, json!({ "alg": "EdDSA", "typ": TOKEN_TYP, "kid": host.kid() }), c);
1387        assert_eq!(v.verify_at(&long, &Expect::default(), t0), Err(TokenError::Lifetime(3600)));
1388    }
1389
1390    #[test]
1391    fn a_replayed_jti_is_refused() {
1392        let (host, peer) = (PeerKey::generate(), PeerKey::generate());
1393        let issuer = TokenIssuer::new(host);
1394        let v = Verifier::new(peer.kid(), &issuer.jwks()).unwrap();
1395        let (t, _) = issuer.mint(req(&peer)).unwrap();
1396        assert!(v.verify(&t, &Expect::default()).is_ok());
1397        assert_eq!(v.verify(&t, &Expect::default()), Err(TokenError::Replayed));
1398        assert_eq!(v.held(), 1);
1399    }
1400
1401    #[test]
1402    fn a_token_presented_for_another_call_or_method_is_refused() {
1403        let (host, peer) = (PeerKey::generate(), PeerKey::generate());
1404        let issuer = TokenIssuer::new(host);
1405        let v = Verifier::new(peer.kid(), &issuer.jwks()).unwrap();
1406        let (t, _) = issuer.mint(req(&peer)).unwrap();
1407        assert!(matches!(v.verify(&t, &Expect { call: Some("call-2"), method: None }), Err(TokenError::Binding(_))));
1408        let (t, _) = issuer.mint(req(&peer)).unwrap();
1409        assert!(matches!(v.verify(&t, &Expect { call: None, method: Some("far.weather.secret") }), Err(TokenError::Binding(_))));
1410    }
1411
1412    #[test]
1413    fn alg_confusion_and_forgeries_are_refused() {
1414        let (host, peer, other) = (PeerKey::generate(), PeerKey::generate(), PeerKey::generate());
1415        let issuer = TokenIssuer::new(host.clone());
1416        let v = Verifier::new(peer.kid(), &issuer.jwks()).unwrap();
1417        let (t, _) = issuer.mint(req(&peer)).unwrap();
1418        let (h, c) = (header_of(&t), claims_part(&t));
1419        let parts: Vec<&str> = t.split('.').collect();
1420        // `alg: none`, no signature.
1421        let mut none = h.clone();
1422        none["alg"] = json!("none");
1423        let unsigned = format!("{}.{}.", b64(none.to_string().as_bytes()), parts[1]);
1424        assert!(matches!(v.verify(&unsigned, &Expect::default()), Err(TokenError::Algorithm(_))), "alg none");
1425        // HS256 "signed" with the public key as an HMAC secret: refused on
1426        // its alg before any key is looked at.
1427        let mut hs = h.clone();
1428        hs["alg"] = json!("HS256");
1429        let hs_token = format!("{}.{}.{}", b64(hs.to_string().as_bytes()), parts[1], parts[2]);
1430        assert!(matches!(v.verify(&hs_token, &Expect::default()), Err(TokenError::Algorithm(_))), "HS256");
1431        // No typ, another typ (a proof passed off as a token).
1432        let mut typ = h.clone();
1433        typ["typ"] = json!(PROOF_TYP);
1434        assert!(matches!(v.verify(&forge(&host, typ, c.clone()), &Expect::default()), Err(TokenError::Type(_))));
1435        // Signed by another key under the host's kid.
1436        assert_eq!(v.verify(&forge(&other, h.clone(), c.clone()), &Expect::default()), Err(TokenError::Signature));
1437        // Signed by another key under its own kid: not trusted.
1438        let mut own = h.clone();
1439        own["kid"] = json!(other.kid());
1440        let mut c2 = c.clone();
1441        c2["iss"] = json!(other.kid());
1442        assert!(matches!(v.verify(&forge(&other, own, c2), &Expect::default()), Err(TokenError::UnknownKey(_))));
1443        // A claim changed after signing.
1444        let mut wider = c.clone();
1445        wider["scope"] = json!("admin@*");
1446        let tampered = format!("{}.{}.{}", parts[0], b64(wider.to_string().as_bytes()), parts[2]);
1447        assert_eq!(v.verify(&tampered, &Expect::default()), Err(TokenError::Signature));
1448        // `crit` and garbage.
1449        let mut crit = h.clone();
1450        crit["crit"] = json!(["exp"]);
1451        assert!(matches!(v.verify(&forge(&host, crit, c), &Expect::default()), Err(TokenError::Malformed(_))));
1452        assert!(matches!(v.verify("a.b", &Expect::default()), Err(TokenError::Malformed(_))));
1453        // A JWKS offering another kind of key is refused outright.
1454        let rsa = Jwks { keys: vec![Jwk { kty: "RSA".into(), crv: String::new(), x: String::new(), kid: None, alg: Some("RS256".into()), use_: None }] };
1455        assert!(matches!(Verifier::new(peer.kid(), &rsa), Err(TokenError::Algorithm(_))));
1456    }
1457
1458    #[test]
1459    fn the_proof_of_possession_is_the_bound_key_s_for_this_call() {
1460        let (host, peer, thief) = (PeerKey::generate(), PeerKey::generate(), PeerKey::generate());
1461        let issuer = TokenIssuer::new(host);
1462        let (t, c) = issuer.mint(req(&peer)).unwrap();
1463        let seen = ProofCache::default();
1464        let n = now();
1465        let p = prove(&peer, &t, "shop.items", "call-1");
1466        assert_eq!(check_proof(&p, &t, &c, "shop.items", "call-1", n, &seen), Ok(()));
1467        assert!(matches!(check_proof(&p, &t, &c, "shop.items", "call-1", n, &seen), Err(TokenError::Proof(w)) if w.contains("replayed")));
1468        // The thief has the token's bytes, not the peer's key.
1469        let stolen = prove(&thief, &t, "shop.items", "call-1");
1470        assert!(matches!(check_proof(&stolen, &t, &c, "shop.items", "call-1", n, &seen), Err(TokenError::Proof(w)) if w.contains("another key")));
1471        // A proof for another method, call or token.
1472        let p = prove(&peer, &t, "shop.items", "call-1");
1473        assert!(check_proof(&p, &t, &c, "shop.secret", "call-1", n, &seen).is_err());
1474        let p = prove(&peer, &t, "shop.items", "call-9");
1475        assert!(check_proof(&p, &t, &c, "shop.items", "call-1", n, &seen).is_err());
1476        let (t2, _) = issuer.mint(req(&peer)).unwrap();
1477        let p = prove(&peer, &t2, "shop.items", "call-1");
1478        assert!(matches!(check_proof(&p, &t, &c, "shop.items", "call-1", n, &seen), Err(TokenError::Proof(w)) if w.contains("another token")));
1479        // Stale.
1480        let p = prove_at(&peer, &t, "shop.items", "call-1", n - 120);
1481        assert!(matches!(check_proof(&p, &t, &c, "shop.items", "call-1", n, &seen), Err(TokenError::Proof(w)) if w.contains("fresh")));
1482        // A pipe's token is bound to no key: no proof can be checked for it.
1483        let pipe = issuer.mint(MintRequest { peer_key: None, ..req(&peer) }).unwrap().1;
1484        assert_eq!(pipe.aud, "pipe:w");
1485        assert!(pipe.cnf.is_none());
1486    }
1487
1488    #[test]
1489    fn a_key_proof_at_info_is_checked() {
1490        let peer = PeerKey::generate();
1491        let (service, mallory) = ("key:5e5e", "key:ma11");
1492        let p = peer.key_proof_for("n0nce", "far", service);
1493        assert!(check_key_proof_for(peer.kid(), &p, "n0nce", "far", service).is_ok());
1494        assert_eq!(check_key_proof_for(peer.kid(), &p, "other", "far", service).map(|_| ()), Err(TokenError::Signature));
1495        assert_eq!(check_key_proof_for(PeerKey::generate().kid(), &p, "n0nce", "far", service).map(|_| ()), Err(TokenError::Signature));
1496        // KEEL-19: made for another asker (a proof Mallory asked for and
1497        // relays to the service as its own): refused.
1498        let relayed = peer.key_proof_for("n0nce", "far", mallory);
1499        assert_eq!(check_key_proof_for(peer.kid(), &relayed, "n0nce", "far", service).map(|_| ()), Err(TokenError::Signature));
1500        // The 0.11.0 forms stay (deprecated) and cannot pass: the old check
1501        // refuses every proof; the old proof (v1) is refused by the new check.
1502        assert!(matches!(check_key_proof(peer.kid(), &p, "n0nce", "far"), Err(TokenError::Refused(w)) if w.contains("check_key_proof_for")));
1503        let v1 = peer.key_proof("n0nce", "far");
1504        assert_eq!(check_key_proof_for(peer.kid(), &v1, "n0nce", "far", service).map(|_| ()), Err(TokenError::Signature));
1505    }
1506
1507    #[test]
1508    fn an_exchange_narrows_and_never_widens() {
1509        let (host, a, b) = (PeerKey::generate(), PeerKey::generate(), PeerKey::generate());
1510        let issuer = TokenIssuer::new(host.clone());
1511        let (t, c) = issuer.mint(req(&a)).unwrap();
1512        let seen = ProofCache::default();
1513        // No proof: refused (the token is bound to a's key).
1514        assert!(matches!(issuer.exchange(&t, None, "b", Some(b.kid().into()), None, "call-2", "far.x", &seen), Err(TokenError::Proof(_))));
1515        // Asking for more than was presented: only the overlap is given.
1516        let ask = vec!["shop.items@*".to_string(), "auth.grant@*".to_string(), "weather.forecast@LISBON".to_string()];
1517        let proof = prove(&a, &t, "exchange", &c.call);
1518        let (t2, c2) = issuer.exchange(&t, Some(&proof), "b", Some(b.kid().into()), Some(&ask), "call-2", "far.x", &seen).unwrap();
1519        assert_eq!(c2.scope, ["shop.items@MENGER", "weather.forecast@LISBON"]);
1520        assert!(is_within(&c2.scope, &c.scope));
1521        assert_eq!(c2.sub, c.sub, "the subject survives every hop");
1522        assert_eq!(c2.actors(), [host.kid().to_string(), a.kid().to_string(), host.kid().to_string()], "act names each hop, nearest first");
1523        assert_eq!(c2.aud, b.kid());
1524        let at_b = Verifier::new(b.kid(), &issuer.jwks()).unwrap();
1525        assert_eq!(at_b.verify(&t2, &Expect::default()).unwrap(), c2);
1526        // A pipe's token (bound to no key) is never exchanged.
1527        let (pipe, _) = issuer.mint(MintRequest { peer_key: None, ..req(&a) }).unwrap();
1528        assert!(matches!(issuer.exchange(&pipe, None, "b", Some(b.kid().into()), None, "c", "m", &seen), Err(TokenError::Proof(w)) if w.contains("pipe")));
1529        // Nothing asked: the presented scope, no wider. (KEEL-19: for
1530        // another method — the subject was exchanged for b and `far.x` once
1531        // already, and is not again.)
1532        let proof = prove(&a, &t, "exchange", &c.call);
1533        let (_, c3) = issuer.exchange(&t, Some(&proof), "b", Some(b.kid().into()), None, "call-3", "far.z", &seen).unwrap();
1534        assert_eq!(c3.scope, c.scope);
1535        let proof = prove(&a, &t, "exchange", &c.call);
1536        assert!(matches!(issuer.exchange(&t, Some(&proof), "b", Some(b.kid().into()), None, "call-4", "far.x", &seen), Err(TokenError::Refused(w)) if w.contains("once")));
1537        // narrow, exhaustively over a small lattice.
1538        let all = ["g@*", "g@A", "g@B", "h@*", "h@A"];
1539        for p in 0..(1 << all.len()) {
1540            let presented: Vec<String> = (0..all.len()).filter(|i| p & (1 << i) != 0).map(|i| all[i].to_string()).collect();
1541            for r in 0..(1 << all.len()) {
1542                let requested: Vec<String> = (0..all.len()).filter(|i| r & (1 << i) != 0).map(|i| all[i].to_string()).collect();
1543                let got = narrow(Some(&requested), &presented);
1544                assert!(is_within(&got, &presented), "{requested:?} from {presented:?} gave {got:?}");
1545            }
1546        }
1547    }
1548
1549    #[test]
1550    fn a_rotated_key_verifies_for_one_lifetime_then_goes() {
1551        let (old, new, peer) = (PeerKey::generate(), PeerKey::generate(), PeerKey::generate());
1552        let issuer = TokenIssuer::new(old.clone());
1553        let (t_old, _) = issuer.mint(req(&peer)).unwrap();
1554        issuer.rotate(new.clone());
1555        let jwks = issuer.jwks();
1556        assert_eq!(jwks.keys.iter().map(|k| k.kid.clone().unwrap()).collect::<Vec<_>>(), [new.kid().to_string(), old.kid().to_string()]);
1557        let v = Verifier::new(peer.kid(), &jwks).unwrap();
1558        assert!(v.verify(&t_old, &Expect::default()).is_ok(), "an old token still verifies while it lives");
1559        let (t_new, c) = issuer.mint(req(&peer)).unwrap();
1560        assert_eq!(c.iss, new.kid());
1561        assert!(v.verify(&t_new, &Expect::default()).is_ok());
1562        // Once the old key leaves the JWKS, a verifier that refreshed refuses it.
1563        issuer.retired.lock().unwrap().clear();
1564        v.trust(&issuer.jwks()).unwrap();
1565        let (t, _) = (t_old, ());
1566        assert!(matches!(v.verify(&t, &Expect::default()), Err(TokenError::UnknownKey(_)) | Err(TokenError::Replayed)));
1567    }
1568
1569    #[test]
1570    fn every_mint_and_exchange_is_audited_without_a_secret() {
1571        #[derive(Default)]
1572        struct Sink(Mutex<Vec<AuditRecord>>);
1573        impl TokenAudit for Sink {
1574            fn record(&self, r: &AuditRecord) {
1575                self.0.lock().unwrap().push(r.clone());
1576            }
1577        }
1578        let sink = Arc::new(Sink::default());
1579        let (host, a, b) = (PeerKey::generate(), PeerKey::generate(), PeerKey::generate());
1580        let issuer = TokenIssuer::new(host).with_audit(sink.clone());
1581        let (t, c) = issuer.mint(req(&a)).unwrap();
1582        let proof = prove(&a, &t, "exchange", &c.call);
1583        let (t2, _) = issuer.exchange(&t, Some(&proof), "b", Some(b.kid().into()), None, "call-2", "far.y", &ProofCache::default()).unwrap();
1584        let records = sink.0.lock().unwrap().clone();
1585        assert_eq!(records.iter().map(|r| r.kind).collect::<Vec<_>>(), [AuditKind::Mint, AuditKind::Exchange]);
1586        assert_eq!(records[1].act.len(), 3);
1587        assert_eq!(records[1].presented_call.as_deref(), Some(c.call.as_str()), "an exchange's record is joined to the hop before it");
1588        assert_eq!(records[0].presented_call, None);
1589        let text = serde_json::to_string(&records).unwrap();
1590        for secret in [&t, &t2, &proof] {
1591            for part in secret.split('.').filter(|p| p.len() > 8) {
1592                assert!(!text.contains(part), "an audit record holds a token's or a proof's bytes");
1593            }
1594        }
1595    }
1596
1597    /// KEEL-19: an exchange is the service's decision; the token it gives is
1598    /// bound to its presenter's key; a refusal is typed and audited, with no
1599    /// secret in the record.
1600    #[test]
1601    fn a_decided_exchange_binds_its_presenter_and_a_refusal_is_audited() {
1602        #[derive(Default)]
1603        struct Sink(Mutex<Vec<ExchangeRefused>>);
1604        impl TokenAudit for Sink {
1605            fn record(&self, _r: &AuditRecord) {}
1606            fn refused(&self, r: &ExchangeRefused) {
1607                self.0.lock().unwrap().push(r.clone());
1608            }
1609        }
1610        let sink = Arc::new(Sink::default());
1611        let (host, a, b) = (PeerKey::generate(), PeerKey::generate(), PeerKey::generate());
1612        let issuer = TokenIssuer::new(host).with_audit(sink.clone());
1613        let (t, c) = issuer.mint(req(&a)).unwrap();
1614        let seen = ProofCache::default();
1615        let proof = prove(&a, &t, EXCHANGE, &c.call);
1616        let no = issuer.exchange_decided(&t, Some(&proof), "b", "call-2", "far.x", &seen, |p| {
1617            assert_eq!(p.aud, a.kid(), "the decision is handed the presenter");
1618            Err((ExchangeRefusal::NotConsented, "a is not consented to reach b".into()))
1619        });
1620        assert!(matches!(&no, Err(TokenError::Refused(w)) if w.contains("not consented")), "{no:?}");
1621        let records = sink.0.lock().unwrap().clone();
1622        assert_eq!(records.len(), 1);
1623        assert_eq!((records[0].reason, records[0].presenter.as_str(), records[0].aud.as_str()), (ExchangeRefusal::NotConsented, a.kid(), "b"));
1624        let text = serde_json::to_string(&records).unwrap();
1625        for part in t.split('.').chain(proof.split('.')).filter(|p| p.len() > 8) {
1626            assert!(!text.contains(part), "a refusal's record holds a token's or a proof's bytes");
1627        }
1628        // No proof: refused before any decision, audited too.
1629        let no_proof = issuer.exchange_decided(&t, None, "b", "call-3", "far.x", &seen, |_| unreachable!("decided without a proof"));
1630        assert!(matches!(no_proof, Err(TokenError::Proof(_))));
1631        assert_eq!(sink.0.lock().unwrap().last().map(|r| r.reason), Some(ExchangeRefusal::Proof));
1632        // Decided: the token is for b, bound to a's key.
1633        let proof = prove(&a, &t, EXCHANGE, &c.call);
1634        let (_, c2) = issuer
1635            .exchange_decided(&t, Some(&proof), "b", "call-4", "far.x", &seen, |_| Ok(Onward { name: "b".into(), peer_key: Some(b.kid().into()), scope: vec!["far.x@*".into()] }))
1636            .unwrap();
1637        assert_eq!((c2.aud.as_str(), c2.cnf.as_ref().map(|c| c.jkt.clone())), (b.kid(), Some(a.thumbprint())));
1638        assert_eq!(c2.scope, ["far.x@*"], "the scope decided");
1639    }
1640
1641    /// DYNAUTH-12's property: `scope ⊆ reach` for every mint — over every
1642    /// reach, forwarded grant and consent drawn from a small lattice.
1643    #[test]
1644    fn every_mint_s_scope_is_within_the_reach() {
1645        let scopes = ["*", "A", "B", "C"];
1646        let subsets = |n: usize| -> Vec<Vec<String>> {
1647            (0..(1usize << n)).map(|m| (0..n).filter(|i| m & (1 << i) != 0).map(|i| scopes[i].to_string()).collect()).collect()
1648        };
1649        let (host, peer) = (PeerKey::generate(), PeerKey::generate());
1650        let issuer = TokenIssuer::new(host);
1651        let mut minted = 0;
1652        for reach in subsets(scopes.len()) {
1653            for consent_a in subsets(scopes.len()) {
1654                for consent_b in subsets(3) {
1655                    for forwarded in [None, Some("far.m")] {
1656                        let needs = vec![("shop.items".to_string(), consent_a.clone()), ("dyn.{peer}".to_string(), consent_b.clone())];
1657                        let scope = mint_scope(forwarded, &reach, &needs);
1658                        let (_, c) = issuer.mint(MintRequest { scope, ..req(&peer) }).unwrap();
1659                        minted += 1;
1660                        for e in &c.scope {
1661                            let (g, s) = e.rsplit_once('@').unwrap();
1662                            assert!(reach.iter().any(|r| r == "*" || r == s), "{e} outside the reach {reach:?}");
1663                            if g != "far.m" {
1664                                let consent = needs.iter().find(|(n, _)| n == g).map(|(_, c)| c).unwrap();
1665                                assert!(consent.iter().any(|c| c == "*" || c == s), "{e} outside its consent {consent:?}");
1666                            }
1667                        }
1668                    }
1669                }
1670            }
1671        }
1672        assert_eq!(minted, 16 * 16 * 8 * 2);
1673    }
1674
1675    /// DYNAUTH-6: an onward token never holds more than the presented one —
1676    /// a need only where it held the same grant, the forwarded grant only
1677    /// where it held the grant the onward call was admitted on.
1678    #[test]
1679    fn an_onward_scope_never_widens() {
1680        let scopes = ["*", "A", "B"];
1681        let subsets = |n: usize| -> Vec<Vec<String>> {
1682            (0..(1usize << n)).map(|m| (0..n).filter(|i| m & (1 << i) != 0).map(|i| scopes[i].to_string()).collect()).collect()
1683        };
1684        let peer = PeerKey::generate();
1685        let issuer = TokenIssuer::new(PeerKey::generate());
1686        for held_slot in subsets(3) {
1687            for held_need in subsets(3) {
1688                let mut presented_scope: Vec<String> = held_slot.iter().map(|s| format!("dyn.{{peer}}@{s}")).collect();
1689                presented_scope.extend(held_need.iter().map(|s| format!("shop.items@{s}")));
1690                let (_, presented) = issuer.mint(MintRequest { scope: presented_scope.clone(), ..req(&peer) }).unwrap();
1691                for reach in subsets(3) {
1692                    for consent in subsets(3) {
1693                        let needs = vec![("shop.items".to_string(), consent.clone()), ("auth.grant".to_string(), vec!["*".to_string()])];
1694                        let got = onward_scope(&presented, Some("dyn.{peer}"), Some("far.forecast"), &reach, &needs);
1695                        for e in &got {
1696                            let (g, s) = e.rsplit_once('@').unwrap();
1697                            let host_grant = if g == "far.forecast" { "dyn.{peer}" } else { g };
1698                            assert!(presented.scopes_for(host_grant).iter().any(|h| h == "*" || h == s), "{e} wider than {presented_scope:?}");
1699                            assert!(reach.iter().any(|r| r == "*" || r == s), "{e} outside the reach {reach:?}");
1700                            assert_ne!(g, "auth.grant", "a need the presented token did not hold");
1701                        }
1702                    }
1703                }
1704            }
1705        }
1706    }
1707
1708    /// KEEL-19 (P5): a key file is never read through a symbolic link, nor
1709    /// one another user owns; a private directory is the user's, 0700.
1710    #[cfg(unix)]
1711    #[test]
1712    fn a_planted_link_or_an_open_directory_is_refused() {
1713        use std::os::unix::fs::PermissionsExt;
1714        let dir = tempfile::tempdir().unwrap();
1715        // A 0600 key of ours, and a link planted where the service's key goes.
1716        let real = dir.path().join("real.key");
1717        let planted = PeerKey::load_or_create(&real).unwrap();
1718        let link = dir.path().join("dial.key");
1719        std::os::unix::fs::symlink(&real, &link).unwrap();
1720        let e = PeerKey::load_or_create(&link).unwrap_err();
1721        assert!(e.contains("symbolic link"), "{e}");
1722        assert!(read_private(&link).is_err());
1723        assert_eq!(PeerKey::load_or_create(&real).unwrap().kid(), planted.kid());
1724        // A dangling link is not "missing": nothing is made through it.
1725        let dangling = dir.path().join("gone.key");
1726        std::os::unix::fs::symlink(dir.path().join("nowhere.key"), &dangling).unwrap();
1727        assert!(PeerKey::load_or_create(&dangling).is_err());
1728        assert!(!dir.path().join("nowhere.key").exists(), "made through a link");
1729        // A private directory: made 0700; a 0755 one or a link refused.
1730        let made = dir.path().join("data");
1731        ensure_private_dir(&made).unwrap();
1732        assert_eq!(std::fs::metadata(&made).unwrap().permissions().mode() & 0o777, 0o700);
1733        let open = dir.path().join("open");
1734        std::fs::create_dir(&open).unwrap();
1735        std::fs::set_permissions(&open, std::fs::Permissions::from_mode(0o755)).unwrap();
1736        assert!(ensure_private_dir(&open).unwrap_err().contains("open to others"));
1737        let linked = dir.path().join("linked");
1738        std::os::unix::fs::symlink(&made, &linked).unwrap();
1739        assert!(ensure_private_dir(&linked).unwrap_err().contains("symbolic link"));
1740    }
1741
1742    #[test]
1743    fn a_key_file_is_made_private_and_read_back() {
1744        let dir = tempfile::tempdir().unwrap();
1745        let path = dir.path().join("k/dyn.key");
1746        let a = PeerKey::load_or_create(&path).unwrap();
1747        let b = PeerKey::load_or_create(&path).unwrap();
1748        assert_eq!(a.kid(), b.kid());
1749        #[cfg(unix)]
1750        {
1751            use std::os::unix::fs::PermissionsExt;
1752            assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
1753            std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();
1754            assert!(PeerKey::load_or_create(&path).is_err());
1755        }
1756        assert!(!format!("{a:?}").contains(&b64(&a.signing.to_bytes())));
1757        // Replaced in place, still private.
1758        #[cfg(unix)]
1759        std::fs::set_permissions(&path, std::os::unix::fs::PermissionsExt::from_mode(0o600)).unwrap();
1760        let c = PeerKey::generate();
1761        c.save(&path).unwrap();
1762        assert_eq!(PeerKey::load_or_create(&path).unwrap().kid(), c.kid());
1763    }
1764}