Skip to main content

lean_ctx_cloud/events/
sign.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Signing of C0 2.0 events (SPEC-ENGINE §3.3.1, §3.3.5;
3//! `vectors/signing.vectors.json`, `vectors/body_commit.vectors.json`).
4//!
5//! The signature covers `"leanctx.cloud.event.v2\n" ‖ canonical_json(event)`
6//! where the event is taken without its body (bound through
7//! `body_commit`), `ck_wrapped`, `signature` and every server-set field.
8
9use ed25519_dalek::{Signature, Signer as _, SigningKey, Verifier as _, VerifyingKey};
10use serde_json::{Map, Value};
11
12use lean_ctx_protocol::cloud::{canonical_json, signing_input};
13
14/// Signature domain of an event.
15pub const EVENT_DOMAIN: &str = "leanctx.cloud.event.v2\n";
16
17/// Fields that are not part of the signed envelope.
18const UNSIGNED: [&str; 14] = [
19    "body",
20    "ck_wrapped",
21    "signature",
22    "seq",
23    "received_at",
24    "provenance",
25    "review_state",
26    "reviewed_by",
27    "review_id",
28    "batch_id",
29    "purged",
30    "key_lost",
31    "revoked_signer",
32    "legacy",
33];
34
35/// `hex(blake3(public_key))[..16]`.
36pub fn key_id(public_key: &[u8; 32]) -> String {
37    blake3::hash(public_key).to_hex()[..16].to_string()
38}
39
40/// The signed envelope: the event without body, `ck_wrapped`, signature
41/// and server fields.
42pub fn envelope(event: &Value) -> Result<Map<String, Value>, String> {
43    let Value::Object(fields) = event else {
44        return Err("an event is a JSON object".into());
45    };
46    let mut fields = fields.clone();
47    for name in UNSIGNED {
48        fields.remove(name);
49    }
50    Ok(fields)
51}
52
53/// The exact bytes an event signature is made over.
54pub fn event_signing_input(event: &Value) -> Result<Vec<u8>, String> {
55    signing_input(EVENT_DOMAIN, &Value::Object(envelope(event)?)).map_err(|e| e.to_string())
56}
57
58/// Sign `event` in place with `key` (sets `key_id` and `signature`).
59pub fn sign(event: &mut Value, key: &SigningKey) -> Result<(), String> {
60    let kid = key_id(key.verifying_key().as_bytes());
61    let Value::Object(fields) = event else {
62        return Err("an event is a JSON object".into());
63    };
64    fields.insert("key_id".into(), Value::String(kid));
65    let signature = key.sign(&event_signing_input(event)?);
66    if let Value::Object(fields) = event {
67        fields.insert(
68            "signature".into(),
69            Value::String(hex::encode(signature.to_bytes())),
70        );
71    }
72    Ok(())
73}
74
75/// Whether `event` carries a valid signature of `public_key` whose key id
76/// it names.
77pub fn verify(event: &Value, public_key: &[u8; 32]) -> bool {
78    let Some(sig_hex) = event.get("signature").and_then(Value::as_str) else {
79        return false;
80    };
81    if event.get("key_id").and_then(Value::as_str) != Some(key_id(public_key).as_str()) {
82        return false;
83    }
84    let (Ok(sig), Ok(key)) = (
85        hex::decode(sig_hex)
86            .ok()
87            .and_then(|b| <[u8; 64]>::try_from(b).ok())
88            .ok_or(()),
89        VerifyingKey::from_bytes(public_key),
90    ) else {
91        return false;
92    };
93    event_signing_input(event)
94        .is_ok_and(|input| key.verify(&input, &Signature::from_bytes(&sig)).is_ok())
95}
96
97/// `hex(blake3(canonical_json(envelope + signature)))`: the leaf digest of
98/// a signed envelope.
99pub fn envelope_digest(event: &Value) -> Result<String, String> {
100    let mut fields = envelope(event)?;
101    if let Some(sig) = event.get("signature") {
102        fields.insert("signature".into(), sig.clone());
103    }
104    Ok(
105        blake3::hash(&canonical_json(&Value::Object(fields)).map_err(|e| e.to_string())?)
106            .to_hex()
107            .to_string(),
108    )
109}
110
111/// `hex(blake3_keyed(key, canonical_json(body)))`; `key` is the place's
112/// `id_salt`.
113pub fn body_commit(key: &[u8; 32], body: &Value) -> Result<String, String> {
114    Ok(
115        blake3::keyed_hash(key, &canonical_json(body).map_err(|e| e.to_string())?)
116            .to_hex()
117            .to_string(),
118    )
119}
120
121/// A fresh `body_nonce`: 16 random bytes, hex.
122pub fn new_body_nonce() -> Result<String, crate::CloudError> {
123    let mut bytes = [0u8; 16];
124    getrandom::fill(&mut bytes).map_err(|e| crate::CloudError::Local(format!("random: {e}")))?;
125    Ok(hex::encode(bytes))
126}