plexus_core/plexus/remote_child/
proven.rs1use std::collections::HashMap;
22use std::sync::Mutex;
23
24use base64::Engine;
25use ed25519_dalek::Signer;
26
27#[derive(Debug, PartialEq, Eq)]
42pub struct Proven {
43 principal: String,
44}
45
46impl Proven {
47 pub fn principal(&self) -> &str {
49 &self.principal
50 }
51}
52
53pub(super) const KEY_PROOF_CONTEXT: &str = "plexus-key-login/v1";
57
58pub const UPGRADE_LEDGER_MAX: usize = 4096;
62
63pub 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
76pub 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
93pub struct KeyedUpgrade {
102 audiences: Vec<String>,
103 seen: Mutex<HashMap<(String, String), i64>>,
104 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 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 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 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}