1use proof_core::{
8 model::{
9 AttestationContent, Claim, EventContent, Evidence, EvidenceKind, MetaValue, Relationship,
10 },
11 ErrorCode, HashRef, Limits, ProofError,
12};
13use proof_format::{
14 attestation_to_cbor, cbor_to_attestation, cbor_to_event, cbor_to_evidence,
15 cbor_to_relationship, decode_and_check_canonical, encode_canonical, event_to_cbor,
16 evidence_to_cbor, relationship_to_cbor,
17};
18
19use crate::alg::AllowedAlgs;
20use crate::claim::{claim_kind, CLAIM_REVOKE, CLAIM_SUPERSEDE};
21use crate::cose::{sign_ed25519, verify_sign1};
22use crate::id::{attestation_id, event_id, evidence_id, relationship_id, verify_id};
23use crate::keys::Ed25519Key;
24
25pub const TEST_SEED: [u8; 32] = [9u8; 32];
27
28#[derive(Debug, Clone)]
30pub struct CreatedEvent {
31 pub content: EventContent,
32 pub canonical: Vec<u8>,
33 pub id: String,
34}
35
36pub fn create_event(content: EventContent, limits: &Limits) -> Result<CreatedEvent, ProofError> {
38 if content.v != 1 {
39 return Err(ErrorCode::UnsupportedVersion.err("only event v=1 supported"));
40 }
41 let value = event_to_cbor(&content)?;
42 let canonical = encode_canonical(&value);
43 let back = cbor_to_event(&decode_and_check_canonical(&canonical, limits)?, limits)?;
45 if back != content {
46 return Err(ErrorCode::SchemaViolation.err("event did not survive canonical round-trip"));
47 }
48 let id = event_id(&canonical);
49 Ok(CreatedEvent {
50 content,
51 canonical,
52 id,
53 })
54}
55
56pub fn verify_event(
59 canonical: &[u8],
60 expected_id: Option<&str>,
61 limits: &Limits,
62) -> Result<(EventContent, String), ProofError> {
63 let value = decode_and_check_canonical(canonical, limits)?;
64 let content = cbor_to_event(&value, limits)?;
65 let id = event_id(canonical);
66 if let Some(expect) = expected_id {
67 verify_id(proof_core::model::id_prefix::EVENT, expect, canonical)?;
68 }
69 Ok((content, id))
70}
71
72#[derive(Debug, Clone)]
74pub struct CreatedAttestation {
75 pub content: AttestationContent,
76 pub canonical: Vec<u8>,
77 pub id: String,
78 pub sign1: Vec<u8>,
79}
80
81pub fn attest(
86 content: AttestationContent,
87 key: &Ed25519Key,
88 limits: &Limits,
89) -> Result<CreatedAttestation, ProofError> {
90 if content.v != 1 {
91 return Err(ErrorCode::UnsupportedVersion.err("only attestation v=1 supported"));
92 }
93 if content.issuer != key.key_ref() {
94 return Err(ErrorCode::SchemaViolation.err("issuer does not match signing key"));
95 }
96 let value = attestation_to_cbor(&content);
97 let canonical = encode_canonical(&value);
98 let back = cbor_to_attestation(&decode_and_check_canonical(&canonical, limits)?, limits)?;
99 if back != content {
100 return Err(
101 ErrorCode::SchemaViolation.err("attestation did not survive canonical round-trip")
102 );
103 }
104 let id = attestation_id(&canonical);
105 let sign1 = sign_ed25519(&canonical, key);
106 Ok(CreatedAttestation {
107 content,
108 canonical,
109 id,
110 sign1,
111 })
112}
113
114pub fn verify_attestation(
117 sign1: &[u8],
118 expected_issuer: &str,
119 allowed: &AllowedAlgs,
120 limits: &Limits,
121) -> Result<(AttestationContent, String), ProofError> {
122 let parsed = verify_sign1(sign1, expected_issuer, allowed, limits)?;
123 let value = decode_and_check_canonical(&parsed.payload, limits)?;
124 let content = cbor_to_attestation(&value, limits)?;
125 let id = attestation_id(&parsed.payload);
127 if content.issuer != expected_issuer {
128 return Err(ErrorCode::SignatureInvalid.err("payload issuer differs from expected issuer"));
129 }
130 Ok((content, id))
131}
132
133#[derive(Debug, Clone)]
137pub struct SignedStatus {
138 pub content: AttestationContent,
139 pub sign1: Vec<u8>,
140}
141
142pub fn revoke_attestation(
145 target: &str,
146 reason: Option<&str>,
147 by: &Ed25519Key,
148 issued_at: u64,
149 limits: &Limits,
150) -> Result<CreatedAttestation, ProofError> {
151 if target.is_empty() {
152 return Err(ErrorCode::SchemaViolation.err("revoke target must not be empty"));
153 }
154 let mut fields = vec![];
157 if let Some(r) = reason {
158 if r.is_empty() {
159 return Err(ErrorCode::SchemaViolation.err("revoke reason must not be empty"));
160 }
161 fields.push(("reason".into(), MetaValue::Text(r.into())));
162 }
163 fields.push(("target".into(), MetaValue::Text(target.into())));
164 attest(
165 AttestationContent {
166 v: 1,
167 issuer: by.key_ref(),
168 subject: target.into(),
169 claim: Claim {
170 claim_type: CLAIM_REVOKE.into(),
171 fields,
172 },
173 issued_at,
174 expires_at: None,
175 evidence_ref: None,
176 },
177 by,
178 limits,
179 )
180}
181
182pub fn supersede_attestation(
185 old: &str,
186 new: &str,
187 by: &Ed25519Key,
188 issued_at: u64,
189 limits: &Limits,
190) -> Result<CreatedAttestation, ProofError> {
191 if old.is_empty() || new.is_empty() {
192 return Err(ErrorCode::SchemaViolation.err("supersede old/new must not be empty"));
193 }
194 if old == new {
195 return Err(ErrorCode::SchemaViolation.err("supersede old == new"));
196 }
197 attest(
199 AttestationContent {
200 v: 1,
201 issuer: by.key_ref(),
202 subject: old.into(),
203 claim: Claim {
204 claim_type: CLAIM_SUPERSEDE.into(),
205 fields: vec![
206 ("new".into(), MetaValue::Text(new.into())),
207 ("old".into(), MetaValue::Text(old.into())),
208 ],
209 },
210 issued_at,
211 expires_at: None,
212 evidence_ref: None,
213 },
214 by,
215 limits,
216 )
217}
218
219pub fn verify_status_object(
227 sign1: &[u8],
228 expected_issuer: &str,
229 allowed: &AllowedAlgs,
230 limits: &Limits,
231) -> Result<AttestationContent, ProofError> {
232 let (content, id) = verify_attestation(sign1, expected_issuer, allowed, limits)?;
233 if !claim_kind(&content).is_status() {
234 return Err(ErrorCode::SchemaViolation.err(format!(
235 "status object {id} has claim.type neither revoke nor supersede"
236 )));
237 }
238 Ok(content)
239}
240
241pub fn to_signed_status(created: &CreatedAttestation) -> Result<SignedStatus, ProofError> {
243 claim_kind(&created.content)
244 .is_status()
245 .then_some(())
246 .ok_or_else(|| ErrorCode::SchemaViolation.err("not a status object"))?;
247 Ok(SignedStatus {
248 content: created.content.clone(),
249 sign1: created.sign1.clone(),
250 })
251}
252
253#[derive(Debug, Clone)]
255pub struct CreatedEvidence {
256 pub content: Evidence,
257 pub canonical: Vec<u8>,
258 pub id: String,
259}
260
261pub fn make_evidence(
266 kind: EvidenceKind,
267 digest: HashRef,
268 attestation_ref: Option<String>,
269 hint: Option<String>,
270 limits: &Limits,
271) -> Result<CreatedEvidence, ProofError> {
272 if let Some(r) = &attestation_ref {
273 if r.is_empty() || r.len() > 1024 {
274 return Err(ErrorCode::SchemaViolation.err("bad attestation_ref"));
275 }
276 }
277 let content = Evidence {
278 v: 1,
279 kind,
280 digest,
281 attestation_ref,
282 hint,
283 };
284 let value = evidence_to_cbor(&content);
285 let canonical = encode_canonical(&value);
286 let back = cbor_to_evidence(&decode_and_check_canonical(&canonical, limits)?, limits)?;
287 if back != content {
288 return Err(ErrorCode::SchemaViolation.err("evidence did not survive canonical round-trip"));
289 }
290 let id = evidence_id(&canonical);
291 Ok(CreatedEvidence {
292 content,
293 canonical,
294 id,
295 })
296}
297
298pub fn verify_evidence(
300 canonical: &[u8],
301 expected_id: Option<&str>,
302 limits: &Limits,
303) -> Result<(Evidence, String), ProofError> {
304 let value = decode_and_check_canonical(canonical, limits)?;
305 let content = cbor_to_evidence(&value, limits)?;
306 let id = evidence_id(canonical);
307 if let Some(expect) = expected_id {
308 verify_id(proof_core::model::id_prefix::EVIDENCE, expect, canonical)?;
309 }
310 Ok((content, id))
311}
312
313#[derive(Debug, Clone)]
317pub struct CreatedRelationship {
318 pub content: Relationship,
319 pub canonical: Vec<u8>,
320 pub id: String,
321}
322
323pub fn make_relationship(
324 content: Relationship,
325 limits: &Limits,
326) -> Result<CreatedRelationship, ProofError> {
327 if content.v != 1 {
328 return Err(ErrorCode::UnsupportedVersion.err("only relationship v=1 supported"));
329 }
330 let value = relationship_to_cbor(&content);
331 let canonical = encode_canonical(&value);
332 let back = cbor_to_relationship(&decode_and_check_canonical(&canonical, limits)?, limits)?;
333 if back != content {
334 return Err(
335 ErrorCode::SchemaViolation.err("relationship did not survive canonical round-trip")
336 );
337 }
338 let id = relationship_id(&canonical);
339 Ok(CreatedRelationship {
340 content,
341 canonical,
342 id,
343 })
344}
345
346pub fn verify_relationship(
348 canonical: &[u8],
349 expected_id: Option<&str>,
350 limits: &Limits,
351) -> Result<(Relationship, String), ProofError> {
352 let value = decode_and_check_canonical(canonical, limits)?;
353 let content = cbor_to_relationship(&value, limits)?;
354 let id = relationship_id(canonical);
355 if let Some(expect) = expected_id {
356 verify_id(proof_core::model::id_prefix::REL, expect, canonical)?;
357 }
358 Ok((content, id))
359}
360
361pub mod fixtures {
363 use super::*;
364 use proof_core::model::{Claim, EventType, MetaValue};
365 use proof_core::{HashAlgorithm, HashRef};
366
367 pub fn test_key() -> Ed25519Key {
368 Ed25519Key::from_seed(&TEST_SEED)
369 }
370
371 pub fn fixed_event_content() -> EventContent {
372 EventContent {
373 v: 1,
374 event_type: EventType::new(EventType::PAYMENT_CREATED),
375 subject: "acct:merchant-01".into(),
376 effective_at: 1_700_000_000,
377 payload_ref: HashRef::new(HashAlgorithm::Sha256, vec![0xABu8; 32]).unwrap(),
378 metadata: vec![("order".into(), MetaValue::Text("ord-1".into()))],
379 }
380 }
381
382 pub fn fixed_attestation_content(issuer: &str, subject: &str) -> AttestationContent {
383 AttestationContent {
384 v: 1,
385 issuer: issuer.into(),
386 subject: subject.into(),
387 claim: Claim {
388 claim_type: "payment.created-observed".into(),
389 fields: vec![("order".into(), MetaValue::Text("ord-1".into()))],
390 },
391 issued_at: 1_700_000_100,
392 expires_at: Some(1_800_000_000),
393 evidence_ref: None,
394 }
395 }
396}
397
398#[cfg(test)]
399mod tests {
400 use super::fixtures::*;
401 use super::*;
402 use proof_core::model::{Claim, MetaValue};
403
404 fn lim() -> Limits {
405 Limits::default()
406 }
407
408 #[test]
409 fn event_create_verify_ok() {
410 let ev = create_event(fixed_event_content(), &lim()).unwrap();
411 assert!(ev.id.starts_with("evt:v1:"));
412 let (content, id) = verify_event(&ev.canonical, Some(&ev.id), &lim()).unwrap();
413 assert_eq!(content, ev.content);
414 assert_eq!(id, ev.id);
415 let (_, id2) = verify_event(&ev.canonical, None, &lim()).unwrap();
417 assert_eq!(id2, ev.id);
418 }
419
420 #[test]
421 fn event_mutation_breaks_id() {
422 let ev = create_event(fixed_event_content(), &lim()).unwrap();
423 let mut mutated = ev.content.clone();
424 mutated.metadata = vec![("order".into(), MetaValue::Text("ord-2".into()))];
425 let bad = create_event(mutated, &lim()).unwrap();
426 assert_ne!(bad.id, ev.id);
427 let e = verify_event(&bad.canonical, Some(&ev.id), &lim()).unwrap_err();
429 assert_eq!(e.code, ErrorCode::IdMismatch);
430 }
431
432 #[test]
433 fn attestation_sign_verify_ok() {
434 let key = test_key();
435 let ev = create_event(fixed_event_content(), &lim()).unwrap();
436 let at = attest(
437 fixed_attestation_content(&key.key_ref(), &ev.id),
438 &key,
439 &lim(),
440 )
441 .unwrap();
442 assert!(at.id.starts_with("att:v1:"));
443 let (content, id) =
444 verify_attestation(&at.sign1, &key.key_ref(), &AllowedAlgs::strict(), &lim()).unwrap();
445 assert_eq!(content, at.content);
446 assert_eq!(id, at.id);
447 }
448
449 #[test]
450 fn attestation_one_byte_tamper_fails() {
451 let key = test_key();
452 let ev = create_event(fixed_event_content(), &lim()).unwrap();
453 let at = attest(
454 fixed_attestation_content(&key.key_ref(), &ev.id),
455 &key,
456 &lim(),
457 )
458 .unwrap();
459 let mut bad = at.sign1.clone();
460 let n = bad.len();
461 bad[n - 1] ^= 0x01; let e =
463 verify_attestation(&bad, &key.key_ref(), &AllowedAlgs::strict(), &lim()).unwrap_err();
464 assert_eq!(e.code, ErrorCode::SignatureInvalid);
465 }
466
467 #[test]
468 fn attestation_wrong_key_fails() {
469 let key = test_key();
470 let other = Ed25519Key::from_seed(&[7u8; 32]);
471 let ev = create_event(fixed_event_content(), &lim()).unwrap();
472 let at = attest(
473 fixed_attestation_content(&key.key_ref(), &ev.id),
474 &key,
475 &lim(),
476 )
477 .unwrap();
478 let e = verify_attestation(&at.sign1, &other.key_ref(), &AllowedAlgs::strict(), &lim())
479 .unwrap_err();
480 assert_eq!(e.code, ErrorCode::SignatureInvalid);
481 }
482
483 #[test]
484 fn attest_refuses_foreign_issuer() {
485 let key = test_key();
486 let other = Ed25519Key::from_seed(&[7u8; 32]);
487 let content = fixed_attestation_content(&other.key_ref(), "evt:v1:x");
489 let e = attest(content, &key, &lim()).unwrap_err();
490 assert_eq!(e.code, ErrorCode::SchemaViolation);
491 }
492
493 #[test]
494 fn attest_refuses_bad_time_order() {
495 let key = test_key();
496 let mut content = fixed_attestation_content(&key.key_ref(), "evt:v1:x");
497 content.issued_at = 200;
498 content.expires_at = Some(100);
499 let e = attest(content, &key, &lim()).unwrap_err();
500 assert_eq!(e.code, ErrorCode::SchemaViolation);
501 }
502
503 #[test]
504 fn attest_refuses_empty_claim_type() {
505 let key = test_key();
506 let mut content = fixed_attestation_content(&key.key_ref(), "evt:v1:x");
507 content.claim = Claim {
508 claim_type: "".into(),
509 fields: vec![],
510 };
511 let e = attest(content, &key, &lim()).unwrap_err();
512 assert_eq!(e.code, ErrorCode::SchemaViolation);
513 }
514
515 #[test]
516 fn evidence_create_verify_ok_and_tamper_fails() {
517 use proof_core::{HashAlgorithm, HashRef};
518 let digest = HashRef::new(HashAlgorithm::Sha256, vec![0xEEu8; 32]).unwrap();
519 let ev = make_evidence(
520 EvidenceKind::new(EvidenceKind::TRANSACTION_RECORD),
521 digest,
522 Some("att:v1:ref".into()),
523 None,
524 &lim(),
525 )
526 .unwrap();
527 assert!(ev.id.starts_with("evd:v1:"));
528 let (content, id) = verify_evidence(&ev.canonical, Some(&ev.id), &lim()).unwrap();
529 assert_eq!(content, ev.content);
530 assert_eq!(id, ev.id);
531 let mut tampered = ev.content.clone();
533 tampered.digest = HashRef::new(HashAlgorithm::Sha256, vec![0xEFu8; 32]).unwrap();
534 let bad = make_evidence(
535 tampered.kind,
536 tampered.digest,
537 tampered.attestation_ref,
538 tampered.hint,
539 &lim(),
540 )
541 .unwrap();
542 let e = verify_evidence(&bad.canonical, Some(&ev.id), &lim()).unwrap_err();
543 assert_eq!(e.code, ErrorCode::IdMismatch);
544 }
545
546 #[test]
547 fn revoke_attestation_signs_status_object() {
548 let key = test_key();
549 let ev = create_event(fixed_event_content(), &lim()).unwrap();
550 let at = attest(
551 fixed_attestation_content(&key.key_ref(), &ev.id),
552 &key,
553 &lim(),
554 )
555 .unwrap();
556 let rev = revoke_attestation(&at.id, Some("fraud"), &key, 1_700_000_300, &lim()).unwrap();
557 assert!(rev.content.claim.claim_type == "revoke");
558 assert_eq!(rev.content.subject, at.id);
559 let content =
561 verify_status_object(&rev.sign1, &key.key_ref(), &AllowedAlgs::strict(), &lim())
562 .unwrap();
563 assert_eq!(content, rev.content);
564 assert_eq!(crate::claim::revocation_target(&content).unwrap(), at.id);
565 }
566
567 #[test]
568 fn supersede_attestation_signs_status_object() {
569 let key = test_key();
570 let ev = create_event(fixed_event_content(), &lim()).unwrap();
571 let a = attest(
572 fixed_attestation_content(&key.key_ref(), &ev.id),
573 &key,
574 &lim(),
575 )
576 .unwrap();
577 let b = attest(
578 proof_core::model::AttestationContent {
579 issued_at: 1_700_000_101,
580 ..fixed_attestation_content(&key.key_ref(), &ev.id)
581 },
582 &key,
583 &lim(),
584 )
585 .unwrap();
586 let sup = supersede_attestation(&a.id, &b.id, &key, 1_700_000_300, &lim()).unwrap();
587 let content =
588 verify_status_object(&sup.sign1, &key.key_ref(), &AllowedAlgs::strict(), &lim())
589 .unwrap();
590 let (old, new) = crate::claim::supersession_pair(&content).unwrap();
591 assert_eq!((old, new), (a.id.as_str(), b.id.as_str()));
592 }
593
594 #[test]
595 fn status_builders_refuse_garbage() {
596 let key = test_key();
597 let e = revoke_attestation("", None, &key, 1, &lim()).unwrap_err();
598 assert_eq!(e.code, ErrorCode::SchemaViolation);
599 let e = supersede_attestation("same", "same", &key, 1, &lim()).unwrap_err();
600 assert_eq!(e.code, ErrorCode::SchemaViolation);
601 let ev = create_event(fixed_event_content(), &lim()).unwrap();
603 let s = attest(
604 fixed_attestation_content(&key.key_ref(), &ev.id),
605 &key,
606 &lim(),
607 )
608 .unwrap();
609 let e = verify_status_object(&s.sign1, &key.key_ref(), &AllowedAlgs::strict(), &lim())
610 .unwrap_err();
611 assert_eq!(e.code, ErrorCode::SchemaViolation);
612 }
613
614 #[test]
615 fn status_object_tamper_detected() {
616 let key = test_key();
617 let ev = create_event(fixed_event_content(), &lim()).unwrap();
618 let at = attest(
619 fixed_attestation_content(&key.key_ref(), &ev.id),
620 &key,
621 &lim(),
622 )
623 .unwrap();
624 let rev = revoke_attestation(&at.id, None, &key, 1_700_000_300, &lim()).unwrap();
625 let other = Ed25519Key::from_seed(&[7u8; 32]);
628 let forged_sign1 = sign_ed25519(&rev.canonical, &other);
629 let e = verify_status_object(
632 &forged_sign1,
633 &key.key_ref(),
634 &AllowedAlgs::strict(),
635 &lim(),
636 )
637 .unwrap_err();
638 assert_eq!(e.code, ErrorCode::SignatureInvalid);
639 let e = verify_status_object(&rev.sign1, &other.key_ref(), &AllowedAlgs::strict(), &lim())
642 .unwrap_err();
643 assert_eq!(e.code, ErrorCode::SignatureInvalid);
644 }
645}