Skip to main content

plexus_core/plexus/remote_child/
proven.rs

1//! KEEL-19 · a principal a verifier proved, as a type.
2//!
3//! A keyed child — one that proves a key at `_info`, or verifies tokens
4//! addressed to a key — believes a forwarded hop from the service acting for
5//! others only over a connection whose sender was *proven*. A principal
6//! written as a string proves nothing: anyone can write the service's key.
7//! [`Proven`] is that proof as a type: it has no constructor from a string,
8//! and is made only where a signature was checked —
9//!
10//! - [`KeyedUpgrade::verify`]: the key proof a mount dials its child with
11//!   (`Authorization: Bearer plexus-key.…`, plexus-wire spec/00), which
12//!   `serve_child_ws` asks at the upgrade, or an embedder's own transport
13//!   hands it.
14//!
15//! (A dial-out's relay proof, `relay_proved`, is checked too, but the
16//! dial-out serves a keyless host and needs no `Proven`.) A keyed child is
17//! served only through `serve_child_proven` (or `serve_child_ws`, which
18//! calls it); `serve_child_with` refuses one, whatever `ChildPeer` it is
19//! given.
20
21use std::collections::HashMap;
22use std::sync::Mutex;
23
24use base64::Engine;
25use ed25519_dalek::Signer;
26
27/// A principal (`key:<hex>`) whose key signed a proof a verifier checked.
28/// No constructor from a string: [`KeyedUpgrade::verify`] makes it.
29///
30/// ```compile_fail
31/// // A string is not a proof: there is no way to write one.
32/// let p = plexus_core::plexus::remote_child::Proven { principal: "key:00".into() };
33/// ```
34///
35/// ```compile_fail
36/// let p: plexus_core::plexus::remote_child::Proven = "key:00".to_string().into();
37/// ```
38///
39/// Not `Clone`: it is the proof of one socket's upgrade, consumed by serving
40/// that socket ([`super::serve_child_proven`]).
41#[derive(Debug, PartialEq, Eq)]
42pub struct Proven {
43    principal: String,
44}
45
46impl Proven {
47    /// The principal proven (`key:<hex>`).
48    pub fn principal(&self) -> &str {
49        &self.principal
50    }
51}
52
53/// spec/00's key-proof context, the one a child is dialed with. (KEEL-19's
54/// P2 — a context of its own for a child dial — is a plexus-wire spec/00
55/// change, not made here: a sign-in proof and a child dial are one form.)
56pub(super) const KEY_PROOF_CONTEXT: &str = "plexus-key-login/v1";
57
58/// The most (key, nonce) pairs a [`KeyedUpgrade`] holds at once. Full, it
59/// refuses new upgrades until entries leave their 60 s window — it never
60/// forgets one early (KEEL-19, P3a: an evicted proof could be replayed).
61pub const UPGRADE_LEDGER_MAX: usize = 4096;
62
63/// KEEL-19 (P2): the agent id a child dial's key proof is signed as. spec/00
64/// has one key-proof form for a dial and a sign-in; `agent` is in the signed
65/// bytes, so a child takes only a proof made as this agent: a sign-in proof
66/// replayed to a child at the same URL is refused. A server's sign-in
67/// (plexus-auth-core's `KeyProofAdapter`) takes a dial proof as the dialing
68/// key's sign-in for its own URL, by design: that is how a service mounts a
69/// service behind key sign-in.
70pub const CHILD_DIAL_AGENT: &str = "plexus.child-dial";
71
72fn b64(b: &[u8]) -> String {
73    base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(b)
74}
75
76/// A spec/00 key proof by `key`, for the child at `aud` (its URL), as the
77/// reserved agent [`CHILD_DIAL_AGENT`] — what a mount sends at the upgrade
78/// (`ws::dial` does), and what an embedder's client of a keyed child sends.
79pub fn dial_proof(key: &crate::plexus::peer_token::PeerKey, aud: &str) -> String {
80    let agent = CHILD_DIAL_AGENT;
81    let mut n = [0u8; 32];
82    n[..16].copy_from_slice(uuid::Uuid::new_v4().as_bytes());
83    n[16..].copy_from_slice(uuid::Uuid::new_v4().as_bytes());
84    let ts = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs() as i64);
85    let aud = aud.trim_end_matches('/');
86    let nonce = b64(&n);
87    let sig = key.signing().sign(format!("{KEY_PROOF_CONTEXT}\n{aud}\n{agent}\n{nonce}\n{ts}").as_bytes());
88    let hex: String = key.public().as_bytes().iter().map(|b| format!("{b:02x}")).collect();
89    let body = serde_json::json!({ "v": 1, "key": hex, "aud": aud, "agent": agent, "nonce": nonce, "ts": ts, "sig": b64(&sig.to_bytes()) });
90    format!("plexus-key.{}", b64(body.to_string().as_bytes()))
91}
92
93/// KEEL-19 · the accepting side of a child's dial: what verifies the key
94/// proof a service dials its child with (`Authorization: Bearer
95/// plexus-key.…`, spec/00) and so makes the [`Proven`] a keyed child is
96/// served on. `aud`
97/// must be one of the URLs this child is dialed at, `ts` within 60 s past
98/// and 30 s ahead, each (key, nonce) once — remembered for its window, at
99/// most [`UPGRADE_LEDGER_MAX`]; a restarted child forgets, so a proof
100/// captured in its last 60 s can be replayed once to it after a restart.
101pub struct KeyedUpgrade {
102    audiences: Vec<String>,
103    seen: Mutex<HashMap<(String, String), i64>>,
104    /// When the last "ledger full" warning was written, and how many
105    /// refusals since were not (at most one line per 10 s).
106    full_said: Mutex<(Option<std::time::Instant>, u64)>,
107}
108
109impl std::fmt::Debug for KeyedUpgrade {
110    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
111        f.debug_struct("KeyedUpgrade").field("audiences", &self.audiences).finish()
112    }
113}
114
115impl KeyedUpgrade {
116    /// Proofs addressed to one of `audiences` (`ws://127.0.0.1:<port>`, …).
117    pub fn new<I: IntoIterator<Item = S>, S: AsRef<str>>(audiences: I) -> Self {
118        Self { audiences: audiences.into_iter().map(|a| a.as_ref().trim().trim_end_matches('/').to_string()).collect(), seen: Default::default(), full_said: Default::default() }
119    }
120
121    /// The principal the bearer value `bearer` proves, or why not.
122    pub fn verify(&self, bearer: &str) -> Result<Proven, String> {
123        use ed25519_dalek::Signature;
124        let b64 = &base64::engine::general_purpose::URL_SAFE_NO_PAD;
125        let body = bearer.trim().strip_prefix("plexus-key.").ok_or("not a key proof (`plexus-key.…`)")?;
126        let p: serde_json::Value = b64.decode(body).ok().and_then(|j| serde_json::from_slice(&j).ok()).ok_or("a key proof that does not read")?;
127        let s = |k: &str| p.get(k).and_then(serde_json::Value::as_str).unwrap_or_default().to_string();
128        let (key, aud, agent, nonce, sig) = (s("key"), s("aud"), s("agent"), s("nonce"), s("sig"));
129        let ts = p.get("ts").and_then(serde_json::Value::as_i64).ok_or("a key proof with no `ts`")?;
130        if p.get("v").and_then(serde_json::Value::as_u64) != Some(1) {
131            return Err("a key proof whose `v` is not 1".into());
132        }
133        if agent != CHILD_DIAL_AGENT {
134            return Err(format!("a key proof as agent `{agent}`, not a child dial (`{CHILD_DIAL_AGENT}`): a sign-in proof is not taken here"));
135        }
136        if !self.audiences.iter().any(|a| a == aud.trim_end_matches('/')) {
137            return Err(format!("a key proof for `{aud}`, not for this child"));
138        }
139        let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs() as i64);
140        if ts + 60 < now || ts > now + 30 {
141            return Err("a key proof out of its time window".into());
142        }
143        let vk = crate::plexus::peer_token::key_of(&format!("key:{key}")).ok_or("a key proof whose `key` is not an Ed25519 key")?;
144        let sig: [u8; 64] = b64.decode(&sig).ok().and_then(|b| b.try_into().ok()).ok_or("a key proof whose `sig` does not read")?;
145        vk.verify_strict(format!("{KEY_PROOF_CONTEXT}\n{aud}\n{agent}\n{nonce}\n{ts}").as_bytes(), &Signature::from_bytes(&sig))
146            .map_err(|_| "a key proof whose signature does not verify")?;
147        let mut seen = self.seen.lock().unwrap();
148        seen.retain(|_, until| *until >= now);
149        if seen.contains_key(&(key.clone(), nonce.clone())) {
150            return Err("a key proof used before".into());
151        }
152        // P3a: bounded, and full it refuses — never forgets a proof early.
153        if seen.len() >= UPGRADE_LEDGER_MAX {
154            let mut said = self.full_said.lock().unwrap();
155            said.1 += 1;
156            if said.0.is_none_or(|t| t.elapsed() >= std::time::Duration::from_secs(10)) {
157                tracing::warn!(target: "plexus::audit", held = seen.len(), refused = said.1, audiences = ?self.audiences, "child upgrade ledger full: new upgrades refused until proofs leave their 60 s window");
158                *said = (Some(std::time::Instant::now()), 0);
159            }
160            return Err(format!("this child holds {UPGRADE_LEDGER_MAX} key proofs in their 60 s window: a new upgrade is refused until some expire"));
161        }
162        seen.insert((key.clone(), nonce), ts + 60);
163        Ok(Proven { principal: format!("key:{key}") })
164    }
165}