OXYGENHUB

Coverage / crates/spectra-core/src/proof.rs 95.9%

70 of 73 lines run, 21 of 29 functions · run #31 on main · run missed

1
//! Signed requests and the proofs events carry (spec §8.5, §9.5).
2
//!
3
//! A principal signs `"spectra1 request " || method || 0x00 || BLAKE3(body)
4
//! || time (8 bytes) || nonce (16 bytes)` with its key, through `oxy-core`'s
5
//! challenge signing. The signature, with what it covered, is the proof
6
//! kept on every event the request causes, so a verifier can check later,
7
//! from the ledger alone, which key asked for it.
8
//!
9
//! The CLI, writing to the ledger itself, signs with `method = "cli"` and
10
//! `body` = the event's canonical payload, so its proof also binds the
11
//! event's content.
12
13
use crate::cbor::{self, Value};
14
use crate::identity::{Identity, Signature};
15
use crate::keys::KeyPair;
16
use rand::RngCore;
17
18
/// How far a request's time may be from the server's clock (spec §8.5).
19
pub const WINDOW_MS: u64 = 5 * 60 * 1000;
20
21
/// A signature with everything it covered except the body itself.
22
#[derive(Clone, Debug, PartialEq, Eq)]
23
pub struct Proof {
24
    pub sig: Signature,
25
    pub method: String,
26
    pub body_hash: [u8; 32],
27
    pub time_ms: u64,
28
    pub nonce: [u8; 16],
29
}
30
31
impl Proof {
32
    /// Sign `method` and `body` now with `pair`.
33384×
    pub fn sign(pair: &KeyPair, method: &str, body: &[u8]) -> Proof {
34384×
        let mut nonce = [0u8; 16];
35384×
        rand::rngs::OsRng.fill_bytes(&mut nonce);
36384×
        Proof::sign_at(pair, method, body, crate::ids::now_ms(), nonce)
37384×
    }
38
39385×
    pub fn sign_at(pair: &KeyPair, method: &str, body: &[u8], time_ms: u64, nonce: [u8; 16]) -> Proof {
40385×
        let body_hash = *blake3::hash(body).as_bytes();
41385×
        let sig = pair.sign(&message(method, &body_hash, time_ms, &nonce));
42385×
        Proof { sig, method: method.into(), body_hash, time_ms, nonce }
43385×
    }
44
45
    /// The signing key's KeyId.
461289×
    pub fn key(&self) -> [u8; 32] {
471289×
        self.sig.key.0
481289×
    }
49
50
    /// Check the signature against `identity` and, when given, the body.
511157×
    pub fn verify(&self, identity: &Identity, body: Option<&[u8]>) -> Result<(), String> {
521157×
        if let Some(b) = body {
531092×
            if *blake3::hash(b).as_bytes() != self.body_hash {
543×
                return Err("the signature covers a different body".into());
551089×
            }
5665×
        }
571154×
        let msg = message(&self.method, &self.body_hash, self.time_ms, &self.nonce);
581154×
        crate::identity::verify(identity, &self.sig, &msg).map_err(|e| format!("signature does not verify: {e}"))
591157×
    }
60
61391×
    pub fn encode(&self) -> Vec<u8> {
62391×
        cbor::encode(&Value::map([
63391×
            (0, self.sig.to_value()),
64391×
            (1, Value::Text(self.method.clone())),
65391×
            (2, Value::Bytes(self.body_hash.to_vec())),
66391×
            (3, Value::Uint(self.time_ms)),
67391×
            (4, Value::Bytes(self.nonce.to_vec())),
68391×
        ]))
69391×
    }
70
711013×
    pub fn decode(b: &[u8]) -> Result<Proof, String> {
721013×
        let v = cbor::decode(b).map_err(|e| format!("malformed proof: {e}"))?;
731013×
        let m = v.as_map().ok_or("malformed proof")?;
745065×
        let get = |k: u64| m.get(&k).ok_or_else(|| format!("proof lacks field {k}"));
75
        Ok(Proof {
761013×
            sig: Signature::from_value(get(0)?).map_err(|e| format!("malformed signature: {e}"))?,
771013×
            method: get(1)?.as_text().ok_or("proof method")?.to_string(),
781013×
            body_hash: get(2)?.as_bytes().and_then(|b| b.try_into().ok()).ok_or("proof body hash")?,
791013×
            time_ms: get(3)?.as_uint().ok_or("proof time")?,
801013×
            nonce: get(4)?.as_bytes().and_then(|b| b.try_into().ok()).ok_or("proof nonce")?,
81
        })
821013×
    }
83
}
84
85
/// `"spectra1 request " || method || 0 || body_hash || time || nonce`.
861539×
pub fn message(method: &str, body_hash: &[u8; 32], time_ms: u64, nonce: &[u8; 16]) -> Vec<u8> {
871539×
    let mut m = b"spectra1 request ".to_vec();
881539×
    m.extend_from_slice(method.as_bytes());
891539×
    m.push(0);
901539×
    m.extend_from_slice(body_hash);
911539×
    m.extend_from_slice(&time_ms.to_be_bytes());
921539×
    m.extend_from_slice(nonce);
931539×
    m
941539×
}
95
96
#[cfg(test)]
97
mod tests {
98
    use super::*;
99
100
    #[test]
1011×
    fn a_proof_round_trips_and_binds_key_method_body_and_time() {
1021×
        let a = KeyPair::generate("a", "");
1031×
        let b = KeyPair::generate("b", "");
1041×
        let p = Proof::sign(&a, "POST /mcp", b"{\"x\":1}");
1051×
        let q = Proof::decode(&p.encode()).unwrap();
1061×
        assert_eq!(p, q);
1071×
        q.verify(&a.identity, Some(b"{\"x\":1}")).unwrap();
1081×
        assert!(q.verify(&a.identity, Some(b"{\"x\":2}")).is_err(), "another body");
1091×
        assert!(q.verify(&b.identity, None).is_err(), "another key");
1101×
        let mut r = q.clone();
1111×
        r.method = "POST /api".into();
1121×
        assert!(r.verify(&a.identity, None).is_err(), "another method");
1131×
        let mut t = q.clone();
1141×
        t.time_ms += 1;
1151×
        assert!(t.verify(&a.identity, None).is_err(), "another time");
1161×
    }
117
}