acdp-types 0.16.1

Wire types (Body, PublishRequest, DataRef, receipts, search) for the Agent Context Distribution Protocol (ACDP)
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
//! Lifecycle event receipts (ACDP 0.5.0, RFC-ACDP-0017 §10, amending
//! RFC-ACDP-0013).
//!
//! An event receipt is a registry-signed acceptance time for one
//! lifecycle event. It gives the event a provable evidence time
//! (`accepted_at`), where the event's own `occurred_at` is only the
//! actor's claim. Registries serve the receipts in
//! `registry_state.event_receipts`, an array parallel to
//! `lifecycle_events`.
//!
//! The signing construction is RFC-ACDP-0010 §5 verbatim: JCS of the
//! object minus `signature`, SHA-256, and a signature over the ASCII
//! bytes of the full `"sha256:<hex>"` string. `receipt_type` is the
//! in-preimage domain separator.

use crate::body::Signature;
use crate::receipt::{
    is_canonical_ms_utc, preimage_hash_of_object, verify_signature_over_hash_with, ReceiptSigner,
};
use acdp_primitives::error::AcdpError;
use acdp_primitives::primitives::{ContentHash, CtxId};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};

/// The `receipt_type` literal of an event receipt.
pub const EVENT_RECEIPT_TYPE: &str = "acdp-event-receipt/1";

/// A registry-signed lifecycle event receipt (RFC-ACDP-0017 §10.1).
///
/// CLOSED schema (`acdp-event-receipt.schema.json`,
/// `additionalProperties: false`): every member is signed, so an unknown
/// member would change the preimage and is rejected at parse time.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct EventReceipt {
    /// Always [`EVENT_RECEIPT_TYPE`].
    pub receipt_type: String,
    /// The registry's identity, `did:web:<origin_registry>`.
    pub registry_did: String,
    /// The context the event belongs to.
    pub ctx_id: CtxId,
    /// The event's `event_id` (canonical lowercase UUID).
    pub event_id: String,
    /// `sha256:` + hex(SHA-256(JCS(event, *including* its signature))).
    pub event_hash: String,
    /// The event's zero-based position in `lifecycle_events`.
    pub index: u64,
    /// The registry's clock when it accepted the event (canonical
    /// millisecond RFC 3339 UTC).
    #[serde(with = "crate::receipt::ms_rfc3339")]
    pub accepted_at: DateTime<Utc>,
    /// Registry signature over the receipt preimage.
    pub signature: Signature,
}

impl EventReceipt {
    /// Parse an event receipt from raw wire JSON, enforcing the closed
    /// schema: exact `receipt_type`, canonical-UUID `event_id`,
    /// `sha256:<64 hex>` `event_hash`, the canonical millisecond byte
    /// form of the RAW `accepted_at`, and a `signature.key_id` under
    /// `registry_did`. Failures are [`AcdpError::InvalidReceipt`].
    pub fn from_value(value: &serde_json::Value) -> Result<Self, AcdpError> {
        let raw_accepted_at = value.get("accepted_at").and_then(|v| v.as_str());
        if !raw_accepted_at.is_some_and(is_canonical_ms_utc) {
            return Err(AcdpError::InvalidReceipt(
                "event receipt accepted_at is missing or not canonical millisecond-precision \
                 RFC 3339 UTC (RFC-ACDP-0017 §10.1)"
                    .into(),
            ));
        }
        let receipt = Self::deserialize(value)
            .map_err(|e| AcdpError::InvalidReceipt(format!("event receipt does not parse: {e}")))?;
        receipt.validate()?;
        Ok(receipt)
    }

    /// The schema invariants serde does not enforce.
    pub fn validate(&self) -> Result<(), AcdpError> {
        if self.receipt_type != EVENT_RECEIPT_TYPE {
            return Err(AcdpError::InvalidReceipt(format!(
                "event receipt receipt_type '{}' ≠ '{EVENT_RECEIPT_TYPE}'",
                self.receipt_type
            )));
        }
        CtxId::parse(self.ctx_id.as_str().to_string())
            .map_err(|e| AcdpError::InvalidReceipt(format!("event receipt ctx_id: {e}")))?;
        if !is_canonical_uuid(&self.event_id) {
            return Err(AcdpError::InvalidReceipt(format!(
                "event receipt event_id '{}' is not a canonical lowercase UUID",
                self.event_id
            )));
        }
        if !is_sha256_digest(&self.event_hash) {
            return Err(AcdpError::InvalidReceipt(format!(
                "event receipt event_hash '{}' is not sha256:<64 lowercase hex>",
                self.event_hash
            )));
        }
        match self.signature.key_id.split_once('#') {
            Some((did, frag)) if did == self.registry_did && !frag.is_empty() => Ok(()),
            _ => Err(AcdpError::InvalidReceipt(format!(
                "event receipt signature.key_id '{}' is not a DID URL under registry_did '{}'",
                self.signature.key_id, self.registry_did
            ))),
        }
    }

    /// `event_hash` for a raw lifecycle event: `sha256:` +
    /// hex(SHA-256(JCS(event))), over the event exactly as stored,
    /// *including* its `signature` member (RFC-ACDP-0017 §10.1).
    pub fn event_hash_of_value(raw_event: &serde_json::Value) -> Result<String, AcdpError> {
        let canonical = acdp_jcs::try_canonicalize_value(raw_event)?;
        Ok(format!(
            "sha256:{}",
            hex::encode(Sha256::digest(&canonical))
        ))
    }

    /// RFC-ACDP-0017 §10.3 steps 2–6 and 9: the receipt binds the
    /// lifecycle event at `index` of the context `ctx_id`, served from
    /// `origin_registry` and created at `created_at`. The signature
    /// (step 7) and the cross-receipt `accepted_at` ordering (step 8) are
    /// separate: see [`Self::verify_signature_against_hash`]. A receipt
    /// failing any step is treated as absent (§10.3).
    pub fn check_binding(
        &self,
        origin_registry: &str,
        ctx_id: &CtxId,
        raw_event: &serde_json::Value,
        index: u64,
        created_at: DateTime<Utc>,
    ) -> Result<(), AcdpError> {
        let fail = |m: String| Err(AcdpError::InvalidReceipt(m));
        let expected_did = acdp_did::web::authority_to_did_web(origin_registry);
        if self.registry_did != expected_did {
            return fail(format!(
                "event receipt registry_did '{}' ≠ '{expected_did}' (§10.3 step 2)",
                self.registry_did
            ));
        }
        if &self.ctx_id != ctx_id {
            return fail("event receipt ctx_id ≠ the context's (§10.3 step 3)".into());
        }
        if raw_event.get("event_id").and_then(|v| v.as_str()) != Some(self.event_id.as_str()) {
            return fail("event receipt event_id ≠ the event's (§10.3 step 4)".into());
        }
        if self.index != index {
            return fail(format!(
                "event receipt index {} ≠ position {index} (§10.3 step 5)",
                self.index
            ));
        }
        if Self::event_hash_of_value(raw_event)? != self.event_hash {
            return fail("event receipt event_hash does not recompute (§10.3 step 6)".into());
        }
        if self.accepted_at < created_at {
            return fail(
                "event receipt accepted_at precedes the context's created_at (§10.3 step 9)".into(),
            );
        }
        Ok(())
    }

    /// Preimage hash from the RAW wire JSON (the value minus
    /// `signature`). Verifiers MUST hash the receipt as received.
    pub fn preimage_hash_of_value(value: &serde_json::Value) -> Result<ContentHash, AcdpError> {
        preimage_hash_of_object(value, "event receipt")
    }

    /// Struct-based preimage hash, used at mint time.
    pub fn preimage_hash(&self) -> Result<ContentHash, AcdpError> {
        Self::preimage_hash_of_value(&serde_json::to_value(self)?)
    }

    /// Verify the signature over an already-computed preimage hash
    /// against a known registry public key (pure; no DID resolution).
    pub fn verify_signature_against_hash(
        &self,
        hash: &ContentHash,
        registry_pub_ed25519: Option<&[u8; 32]>,
        registry_pub_p256_sec1: Option<&[u8]>,
    ) -> Result<(), AcdpError> {
        verify_signature_over_hash_with(
            &self.signature,
            hash,
            registry_pub_ed25519,
            registry_pub_p256_sec1,
            "event receipt",
            AcdpError::InvalidReceipt,
        )
    }
}

impl ReceiptSigner {
    /// Mint an event receipt for the lifecycle event at `index`
    /// (RFC-ACDP-0017 §10.1), signed with the receipt signing key.
    ///
    /// `raw_event` is the event exactly as stored, including its
    /// `signature`; `event_hash` is computed from it here. The caller
    /// owns the §10.1 clock rules: `accepted_at` MUST NOT be backdated
    /// and MUST be ≥ the previous event's `accepted_at` and the
    /// context's `created_at`.
    pub fn mint_event_receipt(
        &self,
        ctx_id: &CtxId,
        raw_event: &serde_json::Value,
        index: u64,
        accepted_at: DateTime<Utc>,
    ) -> Result<EventReceipt, AcdpError> {
        let event_id = raw_event
            .get("event_id")
            .and_then(|v| v.as_str())
            .ok_or_else(|| {
                AcdpError::SchemaViolation("lifecycle event has no string event_id".into())
            })?
            .to_string();
        let mut receipt = EventReceipt {
            receipt_type: EVENT_RECEIPT_TYPE.to_string(),
            registry_did: self.registry_did().to_string(),
            ctx_id: ctx_id.clone(),
            event_id,
            event_hash: EventReceipt::event_hash_of_value(raw_event)?,
            index,
            accepted_at: acdp_primitives::time::trunc_ms(accepted_at),
            signature: Signature {
                algorithm: self.signing_key().algorithm().into(),
                key_id: self.key_id().to_string(),
                value: String::new(),
            },
        };
        receipt.validate()?;
        let hash = receipt.preimage_hash()?;
        let (algorithm, value) = self.signing_key().sign_content_hash(&hash);
        receipt.signature.algorithm = algorithm.into();
        receipt.signature.value = value;
        Ok(receipt)
    }
}

fn is_canonical_uuid(s: &str) -> bool {
    let b = s.as_bytes();
    b.len() == 36
        && b.iter().enumerate().all(|(i, &c)| match i {
            8 | 13 | 18 | 23 => c == b'-',
            _ => c.is_ascii_digit() || (b'a'..=b'f').contains(&c),
        })
}

fn is_sha256_digest(s: &str) -> bool {
    s.strip_prefix("sha256:").is_some_and(|hex| {
        hex.len() == 64
            && hex
                .bytes()
                .all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c))
    })
}

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

    const CTX: &str = "acdp://registry.example.com/aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa";

    fn signer() -> ReceiptSigner {
        ReceiptSigner::new(
            SigningKey::from_bytes(&[0x11; 32]),
            "did:web:registry.example.com",
            "did:web:registry.example.com#receipt-key-1",
        )
        .unwrap()
    }

    fn event() -> serde_json::Value {
        serde_json::json!({
            "event_id": "018f6d0a-7b2e-4c4d-9e1f-3a5b7c9d1e2f",
            "ctx_id": CTX,
            "event_type": "retracted",
            "occurred_at": "2026-10-03T00:00:00.000Z",
            "actor": "did:web:registry.example.com"
        })
    }

    fn accepted() -> DateTime<Utc> {
        DateTime::parse_from_rfc3339("2026-10-03T00:00:01.000Z")
            .unwrap()
            .with_timezone(&Utc)
    }

    #[test]
    fn mint_round_trips_and_verifies() {
        let receipt = signer()
            .mint_event_receipt(&CtxId::parse(CTX).unwrap(), &event(), 0, accepted())
            .unwrap();
        let wire = serde_json::to_value(&receipt).unwrap();
        assert_eq!(wire["accepted_at"], "2026-10-03T00:00:01.000Z");
        let parsed = EventReceipt::from_value(&wire).unwrap();
        assert_eq!(parsed, receipt);
        let hash = EventReceipt::preimage_hash_of_value(&wire).unwrap();
        let key = SigningKey::from_bytes(&[0x11; 32]).verifying_key_bytes();
        parsed
            .verify_signature_against_hash(&hash, Some(&key), None)
            .unwrap();
        assert_eq!(
            parsed.event_hash,
            EventReceipt::event_hash_of_value(&event()).unwrap()
        );
    }

    #[test]
    fn check_binding_covers_steps_2_to_6_and_9() {
        let ctx = CtxId::parse(CTX).unwrap();
        let created = DateTime::parse_from_rfc3339("2026-09-01T00:00:00.000Z")
            .unwrap()
            .with_timezone(&Utc);
        let r = signer()
            .mint_event_receipt(&ctx, &event(), 0, accepted())
            .unwrap();
        r.check_binding("registry.example.com", &ctx, &event(), 0, created)
            .unwrap();
        // Step 2: another registry.
        assert!(r
            .check_binding("other.example.com", &ctx, &event(), 0, created)
            .is_err());
        // Step 3: another context.
        let other =
            CtxId::parse("acdp://registry.example.com/bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb")
                .unwrap();
        assert!(r
            .check_binding("registry.example.com", &other, &event(), 0, created)
            .is_err());
        // Step 5: another position.
        assert!(r
            .check_binding("registry.example.com", &ctx, &event(), 1, created)
            .is_err());
        // Steps 4 and 6: another event.
        let mut changed = event();
        changed["occurred_at"] = "2026-10-03T00:00:00.001Z".into();
        assert!(r
            .check_binding("registry.example.com", &ctx, &changed, 0, created)
            .is_err());
        changed = event();
        changed["event_id"] = "018f6d0a-7b2e-4c4d-9e1f-3a5b7c9d1e30".into();
        assert!(r
            .check_binding("registry.example.com", &ctx, &changed, 0, created)
            .is_err());
        // Step 9: accepted before the context was created.
        let later = accepted() + chrono::Duration::days(1);
        assert!(r
            .check_binding("registry.example.com", &ctx, &event(), 0, later)
            .is_err());
    }

    #[test]
    fn registry_state_event_receipts_round_trip() {
        use crate::body::RegistryState;
        let r = signer()
            .mint_event_receipt(&CtxId::parse(CTX).unwrap(), &event(), 0, accepted())
            .unwrap();
        let mut state: RegistryState =
            serde_json::from_value(serde_json::json!({"status": "active"})).unwrap();
        assert!(state.event_receipts().is_none());
        state.set_event_receipts(vec![r.clone()]).unwrap();
        let wire = serde_json::to_value(&state).unwrap();
        assert_eq!(
            wire["event_receipts"][0]["receipt_type"],
            EVENT_RECEIPT_TYPE
        );
        let back: RegistryState = serde_json::from_value(wire).unwrap();
        assert_eq!(back.event_receipts().unwrap().unwrap(), vec![r]);
        // Omitted, never `[]`.
        state.set_event_receipts(vec![]).unwrap();
        assert!(serde_json::to_value(&state)
            .unwrap()
            .get("event_receipts")
            .is_none());
        // A malformed element surfaces as InvalidReceipt.
        let bad: RegistryState = serde_json::from_value(
            serde_json::json!({"status": "active", "event_receipts": [{"x": 1}]}),
        )
        .unwrap();
        assert!(matches!(
            bad.event_receipts(),
            Some(Err(AcdpError::InvalidReceipt(_)))
        ));
    }

    /// Regression: a fresh context from a lifecycle registry carries no
    /// `lifecycle_events` (RFC-ACDP-0013 §4.1 omits the empty array), and
    /// that means not retracted, not unknown.
    #[test]
    fn retraction_absent_events_from_lifecycle_registry_is_not_retracted() {
        use crate::body::RegistryState;
        let fresh: RegistryState =
            serde_json::from_value(serde_json::json!({"status": "active"})).unwrap();
        assert_eq!(fresh.retraction(true), Some(false));
        assert_eq!(fresh.retraction(false), None);

        let retracted_event = {
            let mut e = event();
            e["signature"] = serde_json::json!({
                "algorithm": "ed25519",
                "key_id": "did:web:registry.example.com#receipt-key-1",
                "value": "AA=="
            });
            e
        };
        let state: RegistryState = serde_json::from_value(serde_json::json!({
            "status": "active",
            "lifecycle_events": [retracted_event]
        }))
        .unwrap();
        assert_eq!(state.retraction(true), Some(true));
        assert_eq!(state.retraction(false), Some(true));

        let by_status: RegistryState =
            serde_json::from_value(serde_json::json!({"status": "retracted"})).unwrap();
        assert_eq!(by_status.retraction(false), Some(true));
    }

    #[test]
    fn closed_schema_rejects_unknown_member_and_bad_forms() {
        let receipt = signer()
            .mint_event_receipt(&CtxId::parse(CTX).unwrap(), &event(), 0, accepted())
            .unwrap();
        let wire = serde_json::to_value(&receipt).unwrap();

        let mut extra = wire.clone();
        extra["note"] = "x".into();
        assert!(EventReceipt::from_value(&extra).is_err());

        let mut short_ts = wire.clone();
        short_ts["accepted_at"] = "2026-10-03T00:00:01Z".into();
        assert!(EventReceipt::from_value(&short_ts).is_err());

        let mut wrong_type = wire.clone();
        wrong_type["receipt_type"] = "acdp-event-receipt/2".into();
        assert!(EventReceipt::from_value(&wrong_type).is_err());

        let mut foreign_key = wire;
        foreign_key["signature"]["key_id"] = "did:web:evil.example.com#k".into();
        assert!(EventReceipt::from_value(&foreign_key).is_err());
    }
}