vouch-core 4.0.0

Vouch Protocol canonical core: JCS canonicalization, Ed25519 + ML-DSA proofs, did:key/multikey, Data Integrity (eddsa-jcs-2022), credentials, delegation, revocation. One byte-exact implementation shared by every language SDK via WASM and UniFFI/C-FFI.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
//! Heartbeat session lineage: the equivocation proof (Specification §11.10).
//!
//! An agent's heartbeat sessions form a chain. The first heartbeat of a
//! session (its opening) names the session it follows in its signed body:
//! `"predecessor": {"session": "<previous session id>"}`, or
//! `"predecessor": "genesis"` for the agent's first session.
//!
//! Two openings with the same subject, signed by the same key, that name the
//! same predecessor but carry different session ids prove the key is held
//! twice. A validator keeps both as an equivocation proof that anyone can
//! check with [`verify_equivocation_proof`]. Two heartbeats of one session
//! never are one: a resend, a re-dated resend, a resend without its audience,
//! or the next interval.
//!
//! This mirrors `vouch/lineage.py` (the reference) and shares the vector in
//! `test-vectors/heartbeat-equivocation/`. The validator's lineage registry
//! and the agent's lineage store live in the reference only.

use serde_json::{Map, Value};

use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};

use crate::data_integrity;

pub const GENESIS: &str = "genesis";
pub const EQUIVOCATION_TYPE: &str = "VouchHeartbeatEquivocation";
pub const HEARTBEAT_PROTOCOL_VERSION: &str = "1.0";
pub const HEARTBEAT_REQUEST_TYPE: &str = "heartbeat_request";
/// The fields that ride beside a heartbeat's signed body.
pub const SIDECAR_FIELDS: [&str; 2] = ["authorityState", "lineage"];
pub const MAX_DID_LENGTH: usize = 1024;
pub const MAX_SESSION_ID_LENGTH: usize = 256;
pub const MAX_AUDIENCE: usize = 16;
pub const MAX_EARLIER_REVEALS: usize = 16;
pub const MAX_MERKLE_ROOT_LENGTH: usize = 128;
/// How many proofs [`proof_applies_to`] looks at.
pub const MAX_PROOFS_CHECKED: usize = 16;
const MAX_SAFE_INTEGER: u64 = (1 << 53) - 1;

pub const EQUIVOCATION_PROVEN: &str = "equivocation_proven";

/// The verdict of [`verify_equivocation_proof`]: `valid` and the reason
/// (`equivocation_proven`, or why not), the same text in every binding.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EquivocationVerdict {
    pub valid: bool,
    pub reason: String,
}

fn no(reason: &str) -> EquivocationVerdict {
    EquivocationVerdict {
        valid: false,
        reason: reason.to_string(),
    }
}

/// Why a `predecessor` value is not well formed, or None.
pub fn predecessor_problem(value: &Value) -> Option<String> {
    if value.as_str() == Some(GENESIS) {
        return None;
    }
    let Some(obj) = value
        .as_object()
        .filter(|o| o.len() == 1 && o.contains_key("session"))
    else {
        return Some(r#"predecessor must be "genesis" or {"session": "<session id>"}"#.into());
    };
    match obj["session"].as_str() {
        Some(s) if !s.is_empty() && s.chars().count() <= MAX_SESSION_ID_LENGTH => None,
        _ => Some(format!(
            "predecessor.session must be a session id of 1 to {MAX_SESSION_ID_LENGTH} characters"
        )),
    }
}

/// A stable text for a well-formed predecessor.
pub fn predecessor_key(value: &Value) -> String {
    match value.as_str() {
        Some(GENESIS) => GENESIS.to_string(),
        _ => format!(
            "session:{}",
            value
                .get("session")
                .and_then(Value::as_str)
                .unwrap_or_default()
        ),
    }
}

/// The heartbeat without the fields that ride outside its signed body.
pub fn strip_sidecars(heartbeat: &Map<String, Value>) -> Map<String, Value> {
    heartbeat
        .iter()
        .filter(|(k, _)| !SIDECAR_FIELDS.contains(&k.as_str()))
        .map(|(k, v)| (k.clone(), v.clone()))
        .collect()
}

/// A JSON whole number from 0 to 2^53 - 1 (`-0` reads as 0, as a JSON integer
/// does in the reference).
fn is_safe_uint(v: &Value) -> bool {
    let Value::Number(n) = v else {
        return false;
    };
    if let Some(u) = n.as_u64() {
        return u <= MAX_SAFE_INTEGER;
    }
    if n.as_i64().is_some() {
        return false;
    }
    matches!(n.as_f64(), Some(f) if f == 0.0 && f.is_sign_negative())
}

fn is_id_char(c: u8) -> bool {
    c.is_ascii_alphanumeric() || matches!(c, b'.' | b'-' | b'_')
}

/// DID syntax: "did:", a lowercase method name, ":", and a method-specific id
/// of letters, digits, ".", "-", "_", "%XX" and ":" (not ending in ":").
pub fn is_did_syntax(s: &str) -> bool {
    let Some(rest) = s.strip_prefix("did:") else {
        return false;
    };
    let Some((method, id)) = rest.split_once(':') else {
        return false;
    };
    if method.is_empty()
        || !method
            .bytes()
            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit())
    {
        return false;
    }
    let b = id.as_bytes();
    if b.is_empty() || b[b.len() - 1] == b':' {
        return false;
    }
    let mut i = 0;
    while i < b.len() {
        match b[i] {
            b':' => i += 1,
            b'%' => {
                if i + 2 >= b.len()
                    || !b[i + 1].is_ascii_hexdigit()
                    || !b[i + 2].is_ascii_hexdigit()
                {
                    return false;
                }
                i += 3;
            }
            c if is_id_char(c) => i += 1,
            _ => return false,
        }
    }
    true
}

/// A canary commitment or reveal: "u" and 43 base64url characters in their
/// one canonical spelling (32 bytes).
pub fn is_canary_value(v: &Value) -> bool {
    let Some(s) = v.as_str() else {
        return false;
    };
    let Some(body) = s.strip_prefix('u') else {
        return false;
    };
    if body.len() != 43
        || !body
            .bytes()
            .all(|c| c.is_ascii_alphanumeric() || c == b'-' || c == b'_')
    {
        return false;
    }
    match URL_SAFE_NO_PAD.decode(body) {
        Ok(raw) => raw.len() == 32 && URL_SAFE_NO_PAD.encode(&raw) == body,
        Err(_) => false,
    }
}

fn audience_ok(v: &Value) -> bool {
    let items: Vec<&Value> = match v {
        Value::String(_) => vec![v],
        Value::Array(a) => a.iter().collect(),
        _ => return false,
    };
    (1..=MAX_AUDIENCE).contains(&items.len())
        && items.iter().all(|i| {
            i.as_str()
                .is_some_and(|s| !s.is_empty() && s.chars().count() <= MAX_DID_LENGTH)
        })
}

fn is_authority_digest(s: &str) -> bool {
    s.len() == 47
        && s.starts_with("uEi")
        && s.bytes()
            .skip(3)
            .all(|c| c.is_ascii_alphanumeric() || c == b'-' || c == b'_')
}

/// Why a heartbeat request (its signed body, sidecars left out) is not well
/// formed, or None: the reference's wire-format rules (§11.3), in its order.
pub fn heartbeat_request_problem(d: &Value) -> Option<String> {
    let Some(d) = d.as_object() else {
        return Some("heartbeat request must be a dict".into());
    };
    if d.get("version").and_then(Value::as_str) != Some(HEARTBEAT_PROTOCOL_VERSION) {
        return Some(format!("version must be '{HEARTBEAT_PROTOCOL_VERSION}'"));
    }
    if d.get("type").and_then(Value::as_str) != Some(HEARTBEAT_REQUEST_TYPE) {
        return Some(format!("type must be '{HEARTBEAT_REQUEST_TYPE}'"));
    }
    for required in [
        "subject_did",
        "session_id",
        "interval_index",
        "issued_at",
        "actionMerkleRoot",
        "canaryCommitment",
        "behavioralDigest",
    ] {
        if !d.contains_key(required) {
            return Some(format!("{required} is required"));
        }
    }
    for (name, limit) in [
        ("subject_did", MAX_DID_LENGTH),
        ("session_id", MAX_SESSION_ID_LENGTH),
    ] {
        match d[name].as_str() {
            Some(s) if !s.is_empty() => {
                if s.chars().count() > limit {
                    return Some(format!("{name} is longer than {limit} characters"));
                }
            }
            _ => return Some(format!("{name} must be a non-empty string")),
        }
    }
    if !is_did_syntax(d["subject_did"].as_str().unwrap_or_default()) {
        return Some("subject_did must be a DID".into());
    }
    if !is_safe_uint(&d["interval_index"]) {
        return Some("interval_index must be a whole number from 0 to 2^53 - 1".into());
    }
    if d.get("authorityEpoch").is_some_and(|e| !is_safe_uint(e)) {
        return Some("authorityEpoch must be a whole number from 0 to 2^53 - 1".into());
    }
    if d["actionMerkleRoot"]
        .as_str()
        .is_none_or(|s| s.chars().count() > MAX_MERKLE_ROOT_LENGTH)
    {
        return Some("actionMerkleRoot must be a multibase string".into());
    }
    if !is_canary_value(&d["canaryCommitment"]) {
        return Some("canaryCommitment must be a canary value".into());
    }
    if d.get("canaryReveal").is_some_and(|v| !is_canary_value(v)) {
        return Some("canaryReveal must be a canary value".into());
    }
    if let Some(earlier) = d.get("canaryEarlierReveals") {
        match earlier.as_array() {
            Some(list) if (1..=MAX_EARLIER_REVEALS).contains(&list.len()) => {
                if !list.iter().all(is_canary_value) {
                    return Some("canaryEarlierReveals item must be a canary value".into());
                }
            }
            _ => {
                return Some(format!(
                "canaryEarlierReveals must be a list of 1 to {MAX_EARLIER_REVEALS} canary values"
            ))
            }
        }
    }
    let Some(digest) = d["behavioralDigest"].as_object() else {
        return Some("behavioralDigest must be an object".into());
    };
    for counter in ["apiCalls", "tokensConsumed"] {
        if digest.get(counter).is_some_and(|v| !is_safe_uint(v)) {
            return Some(format!(
                "behavioralDigest.{counter} must be a whole number from 0 to 2^53 - 1"
            ));
        }
    }
    if digest
        .get("intentDriftScore")
        .is_some_and(Value::is_boolean)
    {
        return Some("behavioralDigest.intentDriftScore must be a number".into());
    }
    if d.get("audience").is_some_and(|a| !audience_ok(a)) {
        return Some(format!(
            "audience must be a validator DID or a list of 1 to {MAX_AUDIENCE} of them"
        ));
    }
    if let Some(hashes) = d.get("actionLeafHashes") {
        if !hashes
            .as_array()
            .is_some_and(|l| l.iter().all(Value::is_string))
        {
            return Some("actionLeafHashes must be a list of multibase strings".into());
        }
    }
    if d.get("proof").is_some_and(|p| !p.is_object()) {
        return Some("proof must be an object".into());
    }
    if let Some(v) = d.get("authorityStateDigest") {
        if !v.as_str().is_some_and(is_authority_digest) {
            return Some("authorityStateDigest must be a multibase SHA-256 digest".into());
        }
    }
    if let Some(p) = d.get("predecessor") {
        if let Some(problem) = predecessor_problem(p) {
            return Some(problem);
        }
    }
    let issued = d["issued_at"].as_str().unwrap_or_default();
    if crate::time::parse_protocol_time_ns(issued).is_err() {
        return Some("issued_at must be an ISO-8601 UTC timestamp".into());
    }
    None
}

/// Check an equivocation proof against the agent's raw Ed25519 public key.
///
/// It holds when both heartbeats are well-formed heartbeats of `agent`, both
/// are signed by `public_key` for assertionMethod (a verification method of
/// the agent's DID), both are openings naming the same predecessor, and their
/// session ids differ. Two heartbeats of one session never prove anything.
///
/// Reasons, in the order they are checked: `proof_malformed:type`,
/// `proof_malformed:agent`, `proof_malformed:two heartbeats are needed`,
/// `proof_key_unusable`, then for each heartbeat `proof_malformed:heartbeat`,
/// `proof_subject_mismatch`, `proof_signature_invalid`,
/// `proof_not_an_opening`, then `proof_predecessors_differ`,
/// `proof_same_session`, `proof_genesis_openings` (two openings that both
/// name "genesis" are what an honest agent sends when it starts again
/// without its lineage file); `equivocation_proven` when it holds.
pub fn verify_equivocation_proof(proof: &Value, public_key: &[u8]) -> EquivocationVerdict {
    let Some(p) = proof
        .as_object()
        .filter(|p| p.get("type").and_then(Value::as_str) == Some(EQUIVOCATION_TYPE))
    else {
        return no("proof_malformed:type");
    };
    let Some(agent) = p
        .get("agent")
        .and_then(Value::as_str)
        .filter(|a| !a.is_empty())
    else {
        return no("proof_malformed:agent");
    };
    let Some(beats) = p
        .get("heartbeats")
        .and_then(Value::as_array)
        .filter(|b| b.len() == 2)
    else {
        return no("proof_malformed:two heartbeats are needed");
    };
    if public_key.len() != 32 || crate::keys::strict_verifying_key(public_key).is_err() {
        return no("proof_key_unusable");
    }
    let mut openings: Vec<(String, String)> = Vec::with_capacity(2);
    for beat in beats {
        let Some(beat) = beat.as_object() else {
            return no("proof_malformed:heartbeat");
        };
        let signed = Value::Object(strip_sidecars(beat));
        if heartbeat_request_problem(&signed).is_some() {
            return no("proof_malformed:heartbeat");
        }
        if signed["subject_did"].as_str() != Some(agent) {
            return no("proof_subject_mismatch");
        }
        let Some(sig) = signed.get("proof").and_then(Value::as_object) else {
            return no("proof_signature_invalid");
        };
        let method_ok = sig
            .get("verificationMethod")
            .and_then(Value::as_str)
            .is_some_and(|m| m.split('#').next() == Some(agent));
        if !method_ok || sig.get("proofPurpose").and_then(Value::as_str) != Some("assertionMethod")
        {
            return no("proof_signature_invalid");
        }
        if !matches!(data_integrity::verify_proof(&signed, public_key), Ok(true)) {
            return no("proof_signature_invalid");
        }
        let Some(pred) = signed.get("predecessor") else {
            return no("proof_not_an_opening");
        };
        openings.push((
            predecessor_key(pred),
            signed["session_id"]
                .as_str()
                .unwrap_or_default()
                .to_string(),
        ));
    }
    if openings[0].0 != openings[1].0 {
        return no("proof_predecessors_differ");
    }
    if openings[0].1 == openings[1].1 {
        return no("proof_same_session");
    }
    if openings[0].0 == GENESIS {
        // Two "genesis" openings are what an honest agent sends when it
        // starts again without its lineage file: no proof of a second key.
        return no("proof_genesis_openings");
    }
    EquivocationVerdict {
        valid: true,
        reason: EQUIVOCATION_PROVEN.to_string(),
    }
}

/// An agent key given as text, for the bindings: a `did:key` DID (its key is
/// read from it) or the raw 32-byte Ed25519 key in base64. None when it is
/// neither.
pub fn public_key_from_text(key: &str) -> Option<Vec<u8>> {
    if key.starts_with("did:key:") {
        return crate::authority_state::did_key_ed25519(key);
    }
    use base64::engine::general_purpose::STANDARD;
    STANDARD.decode(key).ok().filter(|k| k.len() == 32)
}

/// [`verify_equivocation_proof`] with the key as text
/// ([`public_key_from_text`]): a key that is neither is `proof_key_unusable`,
/// after the proof's own shape is checked, as the reference orders it.
pub fn verify_equivocation_proof_text_key(proof: &Value, public_key: &str) -> EquivocationVerdict {
    let key = public_key_from_text(public_key).unwrap_or_default();
    verify_equivocation_proof(proof, &key)
}

/// The verdict as JSON: {valid, reason}.
impl EquivocationVerdict {
    pub fn to_json(&self) -> Value {
        serde_json::json!({"valid": self.valid, "reason": self.reason})
    }
}

/// The first of `proofs` that holds for `did` under `public_key`, or None.
/// Proofs for other DIDs are skipped first; at most
/// [`MAX_PROOFS_CHECKED`] proofs that name `did` are checked, wherever they
/// sit in the list. A verifier that holds such a proof for a caller, or for
/// a DID in the caller's delegation chain, refuses the call
/// (`agent_equivocated`).
pub fn proof_applies_to<'a>(
    proofs: &'a [Value],
    did: &str,
    public_key: &[u8],
) -> Option<&'a Value> {
    proofs
        .iter()
        .filter(|proof| proof.get("agent").and_then(Value::as_str) == Some(did))
        .take(MAX_PROOFS_CHECKED)
        .find(|proof| verify_equivocation_proof(proof, public_key).valid)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn did_syntax_follows_the_reference() {
        for ok in [
            "did:key:z6Mk",
            "did:web:example.com",
            "did:web:example.com%3A8443:a:b",
            "did:a1:x",
            "did:web::x",
        ] {
            assert!(is_did_syntax(ok), "{ok}");
        }
        for bad in [
            "did:Web:x",
            "did:web:",
            "did:web:x:",
            "did::x",
            "did:web",
            "dad:web:x",
            "did:web:a%2",
            "did:web:a%zz",
            "did:web:a b",
            "did:web:é",
        ] {
            assert!(!is_did_syntax(bad), "{bad}");
        }
    }

    #[test]
    fn canary_values_are_canonical() {
        let ok = format!("u{}", "A".repeat(43));
        assert!(is_canary_value(&Value::String(ok)));
        // The last character carries two unused bits: they must be zero.
        assert!(!is_canary_value(&Value::String(format!(
            "u{}B",
            "A".repeat(42)
        ))));
        assert!(!is_canary_value(&Value::String(format!(
            "u{}",
            "A".repeat(42)
        ))));
        assert!(!is_canary_value(&Value::String(format!(
            "z{}",
            "A".repeat(43)
        ))));
        assert!(!is_canary_value(&serde_json::json!(5)));
    }

    #[test]
    fn predecessor_shapes() {
        use serde_json::json;
        assert!(predecessor_problem(&json!("genesis")).is_none());
        assert!(predecessor_problem(&json!({"session": "s"})).is_none());
        assert!(predecessor_problem(&json!({"session": ""})).is_some());
        assert!(predecessor_problem(&json!({"session": "s", "x": 1})).is_some());
        assert!(predecessor_problem(&json!(null)).is_some());
        assert!(predecessor_problem(&json!({"session": "s".repeat(257)})).is_some());
        assert_eq!(predecessor_key(&json!("genesis")), "genesis");
        assert_eq!(predecessor_key(&json!({"session": "s"})), "session:s");
    }
}