use std::collections::HashMap;
use std::sync::Mutex;
use base64::Engine;
use ed25519_dalek::Signer;
#[derive(Debug, PartialEq, Eq)]
pub struct Proven {
principal: String,
}
impl Proven {
pub fn principal(&self) -> &str {
&self.principal
}
}
pub(super) const KEY_PROOF_CONTEXT: &str = "plexus-key-login/v1";
pub const UPGRADE_LEDGER_MAX: usize = 4096;
pub const CHILD_DIAL_AGENT: &str = "plexus.child-dial";
fn b64(b: &[u8]) -> String {
base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(b)
}
pub fn dial_proof(key: &crate::plexus::peer_token::PeerKey, aud: &str) -> String {
let agent = CHILD_DIAL_AGENT;
let mut n = [0u8; 32];
n[..16].copy_from_slice(uuid::Uuid::new_v4().as_bytes());
n[16..].copy_from_slice(uuid::Uuid::new_v4().as_bytes());
let ts = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs() as i64);
let aud = aud.trim_end_matches('/');
let nonce = b64(&n);
let sig = key.signing().sign(format!("{KEY_PROOF_CONTEXT}\n{aud}\n{agent}\n{nonce}\n{ts}").as_bytes());
let hex: String = key.public().as_bytes().iter().map(|b| format!("{b:02x}")).collect();
let body = serde_json::json!({ "v": 1, "key": hex, "aud": aud, "agent": agent, "nonce": nonce, "ts": ts, "sig": b64(&sig.to_bytes()) });
format!("plexus-key.{}", b64(body.to_string().as_bytes()))
}
pub struct KeyedUpgrade {
audiences: Vec<String>,
seen: Mutex<HashMap<(String, String), i64>>,
full_said: Mutex<(Option<std::time::Instant>, u64)>,
}
impl std::fmt::Debug for KeyedUpgrade {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("KeyedUpgrade").field("audiences", &self.audiences).finish()
}
}
impl KeyedUpgrade {
pub fn new<I: IntoIterator<Item = S>, S: AsRef<str>>(audiences: I) -> Self {
Self { audiences: audiences.into_iter().map(|a| a.as_ref().trim().trim_end_matches('/').to_string()).collect(), seen: Default::default(), full_said: Default::default() }
}
pub fn verify(&self, bearer: &str) -> Result<Proven, String> {
use ed25519_dalek::Signature;
let b64 = &base64::engine::general_purpose::URL_SAFE_NO_PAD;
let body = bearer.trim().strip_prefix("plexus-key.").ok_or("not a key proof (`plexus-key.…`)")?;
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")?;
let s = |k: &str| p.get(k).and_then(serde_json::Value::as_str).unwrap_or_default().to_string();
let (key, aud, agent, nonce, sig) = (s("key"), s("aud"), s("agent"), s("nonce"), s("sig"));
let ts = p.get("ts").and_then(serde_json::Value::as_i64).ok_or("a key proof with no `ts`")?;
if p.get("v").and_then(serde_json::Value::as_u64) != Some(1) {
return Err("a key proof whose `v` is not 1".into());
}
if agent != CHILD_DIAL_AGENT {
return Err(format!("a key proof as agent `{agent}`, not a child dial (`{CHILD_DIAL_AGENT}`): a sign-in proof is not taken here"));
}
if !self.audiences.iter().any(|a| a == aud.trim_end_matches('/')) {
return Err(format!("a key proof for `{aud}`, not for this child"));
}
let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs() as i64);
if ts + 60 < now || ts > now + 30 {
return Err("a key proof out of its time window".into());
}
let vk = crate::plexus::peer_token::key_of(&format!("key:{key}")).ok_or("a key proof whose `key` is not an Ed25519 key")?;
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")?;
vk.verify_strict(format!("{KEY_PROOF_CONTEXT}\n{aud}\n{agent}\n{nonce}\n{ts}").as_bytes(), &Signature::from_bytes(&sig))
.map_err(|_| "a key proof whose signature does not verify")?;
let mut seen = self.seen.lock().unwrap();
seen.retain(|_, until| *until >= now);
if seen.contains_key(&(key.clone(), nonce.clone())) {
return Err("a key proof used before".into());
}
if seen.len() >= UPGRADE_LEDGER_MAX {
let mut said = self.full_said.lock().unwrap();
said.1 += 1;
if said.0.is_none_or(|t| t.elapsed() >= std::time::Duration::from_secs(10)) {
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");
*said = (Some(std::time::Instant::now()), 0);
}
return Err(format!("this child holds {UPGRADE_LEDGER_MAX} key proofs in their 60 s window: a new upgrade is refused until some expire"));
}
seen.insert((key.clone(), nonce), ts + 60);
Ok(Proven { principal: format!("key:{key}") })
}
}