proof-crypto 1.0.0

Hash abstraction, COSE_Sign1 sign/verify, key types, and algorithm registry for Proof Engine
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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
// Copyright 2026 Proof Engine Contributors
// SPDX-License-Identifier: MIT OR Apache-2.0
//! Phase 2 builders: create and verify signed artifacts.
//! Every builder round-trips through canonical CBOR + schema so malformed
//! domain objects can never reach signing or id assignment.

use proof_core::{
    model::{
        AttestationContent, Claim, EventContent, Evidence, EvidenceKind, MetaValue, Relationship,
    },
    ErrorCode, HashRef, Limits, ProofError,
};
use proof_format::{
    attestation_to_cbor, cbor_to_attestation, cbor_to_event, cbor_to_evidence,
    cbor_to_relationship, decode_and_check_canonical, encode_canonical, event_to_cbor,
    evidence_to_cbor, relationship_to_cbor,
};

use crate::alg::AllowedAlgs;
use crate::claim::{claim_kind, CLAIM_REVOKE, CLAIM_SUPERSEDE};
use crate::cose::{sign_ed25519, verify_sign1};
use crate::id::{attestation_id, event_id, evidence_id, relationship_id, verify_id};
use crate::keys::Ed25519Key;

/// Fixed test seed. NEVER use in production. All fixtures derive from it.
pub const TEST_SEED: [u8; 32] = [9u8; 32];

/// A created event: validated content, canonical bytes, deterministic id.
#[derive(Debug, Clone)]
pub struct CreatedEvent {
    pub content: EventContent,
    pub canonical: Vec<u8>,
    pub id: String,
}

/// Validate `content` (schema + canonical round-trip) and assign its id.
pub fn create_event(content: EventContent, limits: &Limits) -> Result<CreatedEvent, ProofError> {
    if content.v != 1 {
        return Err(ErrorCode::UnsupportedVersion.err("only event v=1 supported"));
    }
    let value = event_to_cbor(&content)?;
    let canonical = encode_canonical(&value);
    // Round-trip: what we verify later must equal what we built now.
    let back = cbor_to_event(&decode_and_check_canonical(&canonical, limits)?, limits)?;
    if back != content {
        return Err(ErrorCode::SchemaViolation.err("event did not survive canonical round-trip"));
    }
    let id = event_id(&canonical);
    Ok(CreatedEvent {
        content,
        canonical,
        id,
    })
}

/// Verify event bytes: canonical form + schema + id binding.
/// If `expected_id` is given, the recomputed id must match it (tamper check).
pub fn verify_event(
    canonical: &[u8],
    expected_id: Option<&str>,
    limits: &Limits,
) -> Result<(EventContent, String), ProofError> {
    let value = decode_and_check_canonical(canonical, limits)?;
    let content = cbor_to_event(&value, limits)?;
    let id = event_id(canonical);
    if let Some(expect) = expected_id {
        verify_id(proof_core::model::id_prefix::EVENT, expect, canonical)?;
    }
    Ok((content, id))
}

/// A created attestation: validated content, canonical bytes, id, COSE_Sign1.
#[derive(Debug, Clone)]
pub struct CreatedAttestation {
    pub content: AttestationContent,
    pub canonical: Vec<u8>,
    pub id: String,
    pub sign1: Vec<u8>,
}

/// Validate `content`, bind it to `key` (issuer MUST equal the key's KeyRef),
/// assign its id, and sign. Fail closed on any mismatch — never sign bytes
/// the issuer field disowns.
// PE-CRYPTO-005 · PE-TRUST-002 (issuer bound to key, never from attacker bytes).
pub fn attest(
    content: AttestationContent,
    key: &Ed25519Key,
    limits: &Limits,
) -> Result<CreatedAttestation, ProofError> {
    if content.v != 1 {
        return Err(ErrorCode::UnsupportedVersion.err("only attestation v=1 supported"));
    }
    if content.issuer != key.key_ref() {
        return Err(ErrorCode::SchemaViolation.err("issuer does not match signing key"));
    }
    let value = attestation_to_cbor(&content);
    let canonical = encode_canonical(&value);
    let back = cbor_to_attestation(&decode_and_check_canonical(&canonical, limits)?, limits)?;
    if back != content {
        return Err(
            ErrorCode::SchemaViolation.err("attestation did not survive canonical round-trip")
        );
    }
    let id = attestation_id(&canonical);
    let sign1 = sign_ed25519(&canonical, key);
    Ok(CreatedAttestation {
        content,
        canonical,
        id,
        sign1,
    })
}

/// Verify a signed attestation artifact: shape + alg policy + key binding +
/// crypto, then schema + id. Returns the authenticated content and its id.
pub fn verify_attestation(
    sign1: &[u8],
    expected_issuer: &str,
    allowed: &AllowedAlgs,
    limits: &Limits,
) -> Result<(AttestationContent, String), ProofError> {
    let parsed = verify_sign1(sign1, expected_issuer, allowed, limits)?;
    let value = decode_and_check_canonical(&parsed.payload, limits)?;
    let content = cbor_to_attestation(&value, limits)?;
    // The payload is authenticated; the id binds it. Recompute, don't trust.
    let id = attestation_id(&parsed.payload);
    if content.issuer != expected_issuer {
        return Err(ErrorCode::SignatureInvalid.err("payload issuer differs from expected issuer"));
    }
    Ok((content, id))
}

/// Signed lifecycle status object: a full COSE_Sign1 attestation whose claim
/// is `revoke` or `supersede` (FORMAT §4.7). A caller-supplied revocation set
/// is a list of these — never plain id lists.
#[derive(Debug, Clone)]
pub struct SignedStatus {
    pub content: AttestationContent,
    pub sign1: Vec<u8>,
}

/// Build a signed `revoke` status object: `claim.type="revoke"`,
/// `target=<id>`, optional `reason`. `subject` mirrors `target`.
pub fn revoke_attestation(
    target: &str,
    reason: Option<&str>,
    by: &Ed25519Key,
    issued_at: u64,
    limits: &Limits,
) -> Result<CreatedAttestation, ProofError> {
    if target.is_empty() {
        return Err(ErrorCode::SchemaViolation.err("revoke target must not be empty"));
    }
    // CBOR map keys sort bytewise; keep `fields` in sorted order so the
    // canonical round-trip in `attest` is order-stable ("reason" < "target").
    let mut fields = vec![];
    if let Some(r) = reason {
        if r.is_empty() {
            return Err(ErrorCode::SchemaViolation.err("revoke reason must not be empty"));
        }
        fields.push(("reason".into(), MetaValue::Text(r.into())));
    }
    fields.push(("target".into(), MetaValue::Text(target.into())));
    attest(
        AttestationContent {
            v: 1,
            issuer: by.key_ref(),
            subject: target.into(),
            claim: Claim {
                claim_type: CLAIM_REVOKE.into(),
                fields,
            },
            issued_at,
            expires_at: None,
            evidence_ref: None,
        },
        by,
        limits,
    )
}

/// Build a signed `supersede` status object: `claim.type="supersede"`,
/// `old=<id>`, `new=<id>`. `subject` mirrors `old`.
pub fn supersede_attestation(
    old: &str,
    new: &str,
    by: &Ed25519Key,
    issued_at: u64,
    limits: &Limits,
) -> Result<CreatedAttestation, ProofError> {
    if old.is_empty() || new.is_empty() {
        return Err(ErrorCode::SchemaViolation.err("supersede old/new must not be empty"));
    }
    if old == new {
        return Err(ErrorCode::SchemaViolation.err("supersede old == new"));
    }
    // Sorted-by-key order keeps the canonical round-trip stable ("new" < "old").
    attest(
        AttestationContent {
            v: 1,
            issuer: by.key_ref(),
            subject: old.into(),
            claim: Claim {
                claim_type: CLAIM_SUPERSEDE.into(),
                fields: vec![
                    ("new".into(), MetaValue::Text(new.into())),
                    ("old".into(), MetaValue::Text(old.into())),
                ],
            },
            issued_at,
            expires_at: None,
            evidence_ref: None,
        },
        by,
        limits,
    )
}

/// Verify a caller-supplied signed status object: signature + alg policy +
/// issuer binding + claim shape. Returns the authenticated content.
/// The caller states who must have signed it (`expected_issuer`); trust is
/// never derived from the attacker-controlled COSE kid (audit P2). Authority
/// over the target is decided later by the pipeline, never here.
/// Structurally bad or non-status claims are errors — a status object MUST be
/// a revoke or supersede, never a statement smuggled through this path.
pub fn verify_status_object(
    sign1: &[u8],
    expected_issuer: &str,
    allowed: &AllowedAlgs,
    limits: &Limits,
) -> Result<AttestationContent, ProofError> {
    let (content, id) = verify_attestation(sign1, expected_issuer, allowed, limits)?;
    if !claim_kind(&content).is_status() {
        return Err(ErrorCode::SchemaViolation.err(format!(
            "status object {id} has claim.type neither revoke nor supersede"
        )));
    }
    Ok(content)
}

/// Convert a created status object into the verification-facing wrapper.
pub fn to_signed_status(created: &CreatedAttestation) -> Result<SignedStatus, ProofError> {
    claim_kind(&created.content)
        .is_status()
        .then_some(())
        .ok_or_else(|| ErrorCode::SchemaViolation.err("not a status object"))?;
    Ok(SignedStatus {
        content: created.content.clone(),
        sign1: created.sign1.clone(),
    })
}

/// A created evidence object: validated content, canonical bytes, id.
#[derive(Debug, Clone)]
pub struct CreatedEvidence {
    pub content: Evidence,
    pub canonical: Vec<u8>,
    pub id: String,
}

/// Validate evidence fields and assign its id. Evidence carries no signature
/// itself; tamper-evidence comes from the id binding (and from the referenced
/// attestation, when present).
// PE-EVID-001 (schema before id).
pub fn make_evidence(
    kind: EvidenceKind,
    digest: HashRef,
    attestation_ref: Option<String>,
    hint: Option<String>,
    limits: &Limits,
) -> Result<CreatedEvidence, ProofError> {
    if let Some(r) = &attestation_ref {
        if r.is_empty() || r.len() > 1024 {
            return Err(ErrorCode::SchemaViolation.err("bad attestation_ref"));
        }
    }
    let content = Evidence {
        v: 1,
        kind,
        digest,
        attestation_ref,
        hint,
    };
    let value = evidence_to_cbor(&content);
    let canonical = encode_canonical(&value);
    let back = cbor_to_evidence(&decode_and_check_canonical(&canonical, limits)?, limits)?;
    if back != content {
        return Err(ErrorCode::SchemaViolation.err("evidence did not survive canonical round-trip"));
    }
    let id = evidence_id(&canonical);
    Ok(CreatedEvidence {
        content,
        canonical,
        id,
    })
}

/// Verify evidence bytes: canonical form + schema + id binding.
pub fn verify_evidence(
    canonical: &[u8],
    expected_id: Option<&str>,
    limits: &Limits,
) -> Result<(Evidence, String), ProofError> {
    let value = decode_and_check_canonical(canonical, limits)?;
    let content = cbor_to_evidence(&value, limits)?;
    let id = evidence_id(canonical);
    if let Some(expect) = expected_id {
        verify_id(proof_core::model::id_prefix::EVIDENCE, expect, canonical)?;
    }
    Ok((content, id))
}

/// A created relationship: validated content, canonical bytes, id.
/// Grounding (backing evidence for trust-relevant types) is NOT checked here —
/// that is topology validation in `proof-graph`. This function only binds bytes to id.
#[derive(Debug, Clone)]
pub struct CreatedRelationship {
    pub content: Relationship,
    pub canonical: Vec<u8>,
    pub id: String,
}

pub fn make_relationship(
    content: Relationship,
    limits: &Limits,
) -> Result<CreatedRelationship, ProofError> {
    if content.v != 1 {
        return Err(ErrorCode::UnsupportedVersion.err("only relationship v=1 supported"));
    }
    let value = relationship_to_cbor(&content);
    let canonical = encode_canonical(&value);
    let back = cbor_to_relationship(&decode_and_check_canonical(&canonical, limits)?, limits)?;
    if back != content {
        return Err(
            ErrorCode::SchemaViolation.err("relationship did not survive canonical round-trip")
        );
    }
    let id = relationship_id(&canonical);
    Ok(CreatedRelationship {
        content,
        canonical,
        id,
    })
}

/// Verify relationship bytes: canonical form + schema + id binding.
pub fn verify_relationship(
    canonical: &[u8],
    expected_id: Option<&str>,
    limits: &Limits,
) -> Result<(Relationship, String), ProofError> {
    let value = decode_and_check_canonical(canonical, limits)?;
    let content = cbor_to_relationship(&value, limits)?;
    let id = relationship_id(canonical);
    if let Some(expect) = expected_id {
        verify_id(proof_core::model::id_prefix::REL, expect, canonical)?;
    }
    Ok((content, id))
}

/// Shared fixed fixtures (deterministic; also used by golden vectors 06–08).
pub mod fixtures {
    use super::*;
    use proof_core::model::{Claim, EventType, MetaValue};
    use proof_core::{HashAlgorithm, HashRef};

    pub fn test_key() -> Ed25519Key {
        Ed25519Key::from_seed(&TEST_SEED)
    }

    pub fn fixed_event_content() -> EventContent {
        EventContent {
            v: 1,
            event_type: EventType::new(EventType::PAYMENT_CREATED),
            subject: "acct:merchant-01".into(),
            effective_at: 1_700_000_000,
            payload_ref: HashRef::new(HashAlgorithm::Sha256, vec![0xABu8; 32]).unwrap(),
            metadata: vec![("order".into(), MetaValue::Text("ord-1".into()))],
        }
    }

    pub fn fixed_attestation_content(issuer: &str, subject: &str) -> AttestationContent {
        AttestationContent {
            v: 1,
            issuer: issuer.into(),
            subject: subject.into(),
            claim: Claim {
                claim_type: "payment.created-observed".into(),
                fields: vec![("order".into(), MetaValue::Text("ord-1".into()))],
            },
            issued_at: 1_700_000_100,
            expires_at: Some(1_800_000_000),
            evidence_ref: None,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::fixtures::*;
    use super::*;
    use proof_core::model::{Claim, MetaValue};

    fn lim() -> Limits {
        Limits::default()
    }

    #[test]
    fn event_create_verify_ok() {
        let ev = create_event(fixed_event_content(), &lim()).unwrap();
        assert!(ev.id.starts_with("evt:v1:"));
        let (content, id) = verify_event(&ev.canonical, Some(&ev.id), &lim()).unwrap();
        assert_eq!(content, ev.content);
        assert_eq!(id, ev.id);
        // No expected id also works (self-consistent recompute).
        let (_, id2) = verify_event(&ev.canonical, None, &lim()).unwrap();
        assert_eq!(id2, ev.id);
    }

    #[test]
    fn event_mutation_breaks_id() {
        let ev = create_event(fixed_event_content(), &lim()).unwrap();
        let mut mutated = ev.content.clone();
        mutated.metadata = vec![("order".into(), MetaValue::Text("ord-2".into()))];
        let bad = create_event(mutated, &lim()).unwrap();
        assert_ne!(bad.id, ev.id);
        // Old id against new bytes must fail.
        let e = verify_event(&bad.canonical, Some(&ev.id), &lim()).unwrap_err();
        assert_eq!(e.code, ErrorCode::IdMismatch);
    }

    #[test]
    fn attestation_sign_verify_ok() {
        let key = test_key();
        let ev = create_event(fixed_event_content(), &lim()).unwrap();
        let at = attest(
            fixed_attestation_content(&key.key_ref(), &ev.id),
            &key,
            &lim(),
        )
        .unwrap();
        assert!(at.id.starts_with("att:v1:"));
        let (content, id) =
            verify_attestation(&at.sign1, &key.key_ref(), &AllowedAlgs::strict(), &lim()).unwrap();
        assert_eq!(content, at.content);
        assert_eq!(id, at.id);
    }

    #[test]
    fn attestation_one_byte_tamper_fails() {
        let key = test_key();
        let ev = create_event(fixed_event_content(), &lim()).unwrap();
        let at = attest(
            fixed_attestation_content(&key.key_ref(), &ev.id),
            &key,
            &lim(),
        )
        .unwrap();
        let mut bad = at.sign1.clone();
        let n = bad.len();
        bad[n - 1] ^= 0x01; // inside signature bytes: structure stays valid.
        let e =
            verify_attestation(&bad, &key.key_ref(), &AllowedAlgs::strict(), &lim()).unwrap_err();
        assert_eq!(e.code, ErrorCode::SignatureInvalid);
    }

    #[test]
    fn attestation_wrong_key_fails() {
        let key = test_key();
        let other = Ed25519Key::from_seed(&[7u8; 32]);
        let ev = create_event(fixed_event_content(), &lim()).unwrap();
        let at = attest(
            fixed_attestation_content(&key.key_ref(), &ev.id),
            &key,
            &lim(),
        )
        .unwrap();
        let e = verify_attestation(&at.sign1, &other.key_ref(), &AllowedAlgs::strict(), &lim())
            .unwrap_err();
        assert_eq!(e.code, ErrorCode::SignatureInvalid);
    }

    #[test]
    fn attest_refuses_foreign_issuer() {
        let key = test_key();
        let other = Ed25519Key::from_seed(&[7u8; 32]);
        // Content names `other` but is signed with `key`: must refuse to sign.
        let content = fixed_attestation_content(&other.key_ref(), "evt:v1:x");
        let e = attest(content, &key, &lim()).unwrap_err();
        assert_eq!(e.code, ErrorCode::SchemaViolation);
    }

    #[test]
    fn attest_refuses_bad_time_order() {
        let key = test_key();
        let mut content = fixed_attestation_content(&key.key_ref(), "evt:v1:x");
        content.issued_at = 200;
        content.expires_at = Some(100);
        let e = attest(content, &key, &lim()).unwrap_err();
        assert_eq!(e.code, ErrorCode::SchemaViolation);
    }

    #[test]
    fn attest_refuses_empty_claim_type() {
        let key = test_key();
        let mut content = fixed_attestation_content(&key.key_ref(), "evt:v1:x");
        content.claim = Claim {
            claim_type: "".into(),
            fields: vec![],
        };
        let e = attest(content, &key, &lim()).unwrap_err();
        assert_eq!(e.code, ErrorCode::SchemaViolation);
    }

    #[test]
    fn evidence_create_verify_ok_and_tamper_fails() {
        use proof_core::{HashAlgorithm, HashRef};
        let digest = HashRef::new(HashAlgorithm::Sha256, vec![0xEEu8; 32]).unwrap();
        let ev = make_evidence(
            EvidenceKind::new(EvidenceKind::TRANSACTION_RECORD),
            digest,
            Some("att:v1:ref".into()),
            None,
            &lim(),
        )
        .unwrap();
        assert!(ev.id.starts_with("evd:v1:"));
        let (content, id) = verify_evidence(&ev.canonical, Some(&ev.id), &lim()).unwrap();
        assert_eq!(content, ev.content);
        assert_eq!(id, ev.id);
        // Flip a digest byte: structure stays valid CBOR, id must mismatch.
        let mut tampered = ev.content.clone();
        tampered.digest = HashRef::new(HashAlgorithm::Sha256, vec![0xEFu8; 32]).unwrap();
        let bad = make_evidence(
            tampered.kind,
            tampered.digest,
            tampered.attestation_ref,
            tampered.hint,
            &lim(),
        )
        .unwrap();
        let e = verify_evidence(&bad.canonical, Some(&ev.id), &lim()).unwrap_err();
        assert_eq!(e.code, ErrorCode::IdMismatch);
    }

    #[test]
    fn revoke_attestation_signs_status_object() {
        let key = test_key();
        let ev = create_event(fixed_event_content(), &lim()).unwrap();
        let at = attest(
            fixed_attestation_content(&key.key_ref(), &ev.id),
            &key,
            &lim(),
        )
        .unwrap();
        let rev = revoke_attestation(&at.id, Some("fraud"), &key, 1_700_000_300, &lim()).unwrap();
        assert!(rev.content.claim.claim_type == "revoke");
        assert_eq!(rev.content.subject, at.id);
        // Round-trip: the pipeline-facing verifier accepts it as a status object.
        let content =
            verify_status_object(&rev.sign1, &key.key_ref(), &AllowedAlgs::strict(), &lim())
                .unwrap();
        assert_eq!(content, rev.content);
        assert_eq!(crate::claim::revocation_target(&content).unwrap(), at.id);
    }

    #[test]
    fn supersede_attestation_signs_status_object() {
        let key = test_key();
        let ev = create_event(fixed_event_content(), &lim()).unwrap();
        let a = attest(
            fixed_attestation_content(&key.key_ref(), &ev.id),
            &key,
            &lim(),
        )
        .unwrap();
        let b = attest(
            proof_core::model::AttestationContent {
                issued_at: 1_700_000_101,
                ..fixed_attestation_content(&key.key_ref(), &ev.id)
            },
            &key,
            &lim(),
        )
        .unwrap();
        let sup = supersede_attestation(&a.id, &b.id, &key, 1_700_000_300, &lim()).unwrap();
        let content =
            verify_status_object(&sup.sign1, &key.key_ref(), &AllowedAlgs::strict(), &lim())
                .unwrap();
        let (old, new) = crate::claim::supersession_pair(&content).unwrap();
        assert_eq!((old, new), (a.id.as_str(), b.id.as_str()));
    }

    #[test]
    fn status_builders_refuse_garbage() {
        let key = test_key();
        let e = revoke_attestation("", None, &key, 1, &lim()).unwrap_err();
        assert_eq!(e.code, ErrorCode::SchemaViolation);
        let e = supersede_attestation("same", "same", &key, 1, &lim()).unwrap_err();
        assert_eq!(e.code, ErrorCode::SchemaViolation);
        // A statement attestation must never pass the status-object verifier.
        let ev = create_event(fixed_event_content(), &lim()).unwrap();
        let s = attest(
            fixed_attestation_content(&key.key_ref(), &ev.id),
            &key,
            &lim(),
        )
        .unwrap();
        let e = verify_status_object(&s.sign1, &key.key_ref(), &AllowedAlgs::strict(), &lim())
            .unwrap_err();
        assert_eq!(e.code, ErrorCode::SchemaViolation);
    }

    #[test]
    fn status_object_tamper_detected() {
        let key = test_key();
        let ev = create_event(fixed_event_content(), &lim()).unwrap();
        let at = attest(
            fixed_attestation_content(&key.key_ref(), &ev.id),
            &key,
            &lim(),
        )
        .unwrap();
        let rev = revoke_attestation(&at.id, None, &key, 1_700_000_300, &lim()).unwrap();
        // Re-sign the SAME canonical payload with a different key: the kid-bound
        // issuer (other) differs from the payload issuer (key) → MUST fail.
        let other = Ed25519Key::from_seed(&[7u8; 32]);
        let forged_sign1 = sign_ed25519(&rev.canonical, &other);
        // Expected signer is the payload issuer (key); the forgery was signed by
        // other, so kid binding fails — trust never follows the attacker kid.
        let e = verify_status_object(
            &forged_sign1,
            &key.key_ref(),
            &AllowedAlgs::strict(),
            &lim(),
        )
        .unwrap_err();
        assert_eq!(e.code, ErrorCode::SignatureInvalid);
        // A valid status object stated under the WRONG expected signer also
        // fails: the caller names who must have signed, full stop.
        let e = verify_status_object(&rev.sign1, &other.key_ref(), &AllowedAlgs::strict(), &lim())
            .unwrap_err();
        assert_eq!(e.code, ErrorCode::SignatureInvalid);
    }
}