Skip to main content

hyprstream_pds/
at9p.rs

1//! `did:at9p` capsule, update-record, and shard-manifest schema.
2//!
3//! The structures in this module are deliberately just the durable record
4//! grammar for #882. They encode through the existing [`crate::dag_cbor`]
5//! deterministic codec and every byte-oriented decoder enforces the at9p R3
6//! gate: `decode(bytes).encode() == bytes`, otherwise the input is rejected.
7//! Signature verification, rotation-chain validation, witness checks, and MAC
8//! label interpretation are later gates (#883/#884), not schema work.
9//!
10//! Codec placement decision: the schema lives in `hyprstream-pds`, beside the
11//! single DAG-CBOR implementation it reuses. The resolver/discovery crates
12//! already depend on `hyprstream-pds`, so this avoids moving the codec or
13//! creating a second CBOR layer while keeping the schema available to both PDS
14//! and resolver code.
15
16use std::collections::BTreeSet;
17
18use anyhow::{bail, ensure, Context, Result};
19use hyprstream_rpc::cid::{encode_cid, Codec, HashAlgo};
20
21use crate::dag_cbor::DagCbor;
22
23pub const CAPSULE_VERSION: &str = "at9p-capsule/1";
24pub const CAPSULE_SIGNATURE_CONTEXT: &str = "at9p-capsule/1";
25pub const UPDATE_SIGNATURE_CONTEXT: &str = "at9p-update/1";
26pub const MANIFEST_SIGNATURE_CONTEXT: &str = "at9p-manifest/1";
27
28pub const ED25519_PUBLIC_KEY_LEN: usize = 32;
29pub const ED25519_SIGNATURE_LEN: usize = 64;
30pub const ML_DSA65_PUBLIC_KEY_LEN: usize = 1952;
31pub const ML_DSA65_SIGNATURE_LEN: usize = 3309;
32pub const H512_LEN: usize = 64;
33
34#[derive(Clone, Debug, Eq, PartialEq)]
35pub struct HybridKeyPair {
36    pub ed25519_pub: Vec<u8>,
37    pub mldsa65_pub: Vec<u8>,
38}
39
40impl HybridKeyPair {
41    pub fn new(ed25519_pub: impl Into<Vec<u8>>, mldsa65_pub: impl Into<Vec<u8>>) -> Result<Self> {
42        let key = Self {
43            ed25519_pub: ed25519_pub.into(),
44            mldsa65_pub: mldsa65_pub.into(),
45        };
46        key.validate()?;
47        Ok(key)
48    }
49
50    pub fn validate(&self) -> Result<()> {
51        ensure!(
52            self.ed25519_pub.len() == ED25519_PUBLIC_KEY_LEN,
53            "ed25519 public key must be {ED25519_PUBLIC_KEY_LEN} bytes"
54        );
55        ensure!(
56            self.mldsa65_pub.len() == ML_DSA65_PUBLIC_KEY_LEN,
57            "ML-DSA-65 public key must be {ML_DSA65_PUBLIC_KEY_LEN} bytes"
58        );
59        Ok(())
60    }
61
62    fn to_value(&self) -> DagCbor {
63        DagCbor::str_map([
64            ("ed25519Pub", DagCbor::Bytes(self.ed25519_pub.clone())),
65            ("mldsa65Pub", DagCbor::Bytes(self.mldsa65_pub.clone())),
66        ])
67    }
68
69    /// KERI pre-rotation commitment digest for this keypair: `BLAKE3-512` over
70    /// the canonical DAG-CBOR of the hybrid keypair (both the Ed25519 and
71    /// ML-DSA-65 public keys). This is the value a capsule author places in
72    /// `next_key_commitments` to pre-commit the *next* key set, and the value
73    /// the B1 successor-check ([`crate::at9p_chain`]) recomputes from an
74    /// update-record's revealed signing key to prove it was pre-committed.
75    ///
76    /// Hashing both components together binds them: an attacker cannot swap one
77    /// half of the hybrid pair without changing the commitment.
78    pub fn commitment_digest(&self) -> [u8; H512_LEN] {
79        h512(&self.to_value().encode())
80    }
81
82    fn from_value(value: &DagCbor) -> Result<Self> {
83        reject_unknown(value, &["ed25519Pub", "mldsa65Pub"], "at9p hybrid keypair")?;
84        Self::new(
85            required_bytes(value, "ed25519Pub", "at9p hybrid keypair")?.to_vec(),
86            required_bytes(value, "mldsa65Pub", "at9p hybrid keypair")?.to_vec(),
87        )
88    }
89}
90
91#[derive(Clone, Debug, Eq, PartialEq)]
92pub enum ServiceType {
93    NinePExport,
94    AtprotoPds,
95}
96
97impl ServiceType {
98    fn as_str(&self) -> &'static str {
99        match self {
100            Self::NinePExport => "NinePExport",
101            Self::AtprotoPds => "AtprotoPDS",
102        }
103    }
104
105    fn parse(s: &str) -> Result<Self> {
106        match s {
107            "NinePExport" => Ok(Self::NinePExport),
108            "AtprotoPDS" => Ok(Self::AtprotoPds),
109            other => bail!("unknown at9p service type {other:?}"),
110        }
111    }
112}
113
114#[derive(Clone, Debug, Eq, PartialEq)]
115pub enum Transport {
116    Iroh,
117    Quic,
118    Moq,
119    Https,
120}
121
122impl Transport {
123    fn as_str(&self) -> &'static str {
124        match self {
125            Self::Iroh => "iroh",
126            Self::Quic => "quic",
127            Self::Moq => "moq",
128            Self::Https => "https",
129        }
130    }
131
132    fn parse(s: &str) -> Result<Self> {
133        match s {
134            "iroh" => Ok(Self::Iroh),
135            "quic" => Ok(Self::Quic),
136            "moq" => Ok(Self::Moq),
137            "https" => Ok(Self::Https),
138            other => bail!("unknown at9p endpoint transport {other:?}"),
139        }
140    }
141}
142
143#[derive(Clone, Debug, Eq, PartialEq)]
144pub struct ServiceEndpoint {
145    pub transport: Transport,
146    pub address: String,
147    pub node_id: Option<String>,
148    pub relay: Option<String>,
149    pub export: Option<String>,
150    /// Hybrid request-encryption public material bound by the signed capsule.
151    /// Absent on older identities; encrypted offline bootstrap requires it.
152    pub request_kem: Option<Vec<u8>>,
153}
154
155impl ServiceEndpoint {
156    pub fn new(transport: Transport, address: impl Into<String>) -> Result<Self> {
157        let endpoint = Self {
158            transport,
159            address: address.into(),
160            node_id: None,
161            relay: None,
162            export: None,
163            request_kem: None,
164        };
165        endpoint.validate()?;
166        Ok(endpoint)
167    }
168
169    pub fn validate(&self) -> Result<()> {
170        validate_nonempty_no_ws(&self.address, "service endpoint address")?;
171        validate_optional_no_ws(self.node_id.as_deref(), "service endpoint nodeId")?;
172        validate_optional_no_ws(self.relay.as_deref(), "service endpoint relay")?;
173        validate_optional_no_ws(self.export.as_deref(), "service endpoint export")?;
174        if let Some(key) = &self.request_kem {
175            ensure!(
176                !key.is_empty() && key.len() <= 4096,
177                "invalid endpoint request KEM length"
178            );
179        }
180        Ok(())
181    }
182
183    fn to_value(&self) -> DagCbor {
184        let mut fields = vec![
185            ("address", DagCbor::Text(self.address.clone())),
186            (
187                "transport",
188                DagCbor::Text(self.transport.as_str().to_owned()),
189            ),
190        ];
191        if let Some(node_id) = &self.node_id {
192            fields.push(("nodeId", DagCbor::Text(node_id.clone())));
193        }
194        if let Some(relay) = &self.relay {
195            fields.push(("relay", DagCbor::Text(relay.clone())));
196        }
197        if let Some(export) = &self.export {
198            fields.push(("export", DagCbor::Text(export.clone())));
199        }
200        if let Some(key) = &self.request_kem {
201            fields.push(("requestKem", DagCbor::Bytes(key.clone())));
202        }
203        DagCbor::str_map(fields)
204    }
205
206    fn from_value(value: &DagCbor) -> Result<Self> {
207        reject_unknown(
208            value,
209            &[
210                "address",
211                "transport",
212                "nodeId",
213                "relay",
214                "export",
215                "requestKem",
216            ],
217            "at9p service endpoint",
218        )?;
219        let endpoint = Self {
220            transport: Transport::parse(required_str(
221                value,
222                "transport",
223                "at9p service endpoint",
224            )?)?,
225            address: required_str(value, "address", "at9p service endpoint")?.to_owned(),
226            node_id: optional_str(value, "nodeId")?.map(str::to_owned),
227            relay: optional_str(value, "relay")?.map(str::to_owned),
228            export: optional_str(value, "export")?.map(str::to_owned),
229            request_kem: match value.get("requestKem") {
230                Some(DagCbor::Bytes(key)) => Some(key.clone()),
231                Some(_) => bail!("endpoint requestKem must be bytes"),
232                None => None,
233            },
234        };
235        endpoint.validate()?;
236        Ok(endpoint)
237    }
238}
239
240#[derive(Clone, Debug, Eq, PartialEq)]
241pub struct ServiceEntry {
242    pub id: String,
243    pub service_type: ServiceType,
244    pub endpoint: ServiceEndpoint,
245}
246
247impl ServiceEntry {
248    pub fn new(
249        id: impl Into<String>,
250        service_type: ServiceType,
251        endpoint: ServiceEndpoint,
252    ) -> Result<Self> {
253        let entry = Self {
254            id: id.into(),
255            service_type,
256            endpoint,
257        };
258        entry.validate()?;
259        Ok(entry)
260    }
261
262    pub fn validate(&self) -> Result<()> {
263        validate_service_id(&self.id)?;
264        self.endpoint.validate()
265    }
266
267    fn to_value(&self) -> DagCbor {
268        DagCbor::str_map([
269            ("endpoint", self.endpoint.to_value()),
270            ("id", DagCbor::Text(self.id.clone())),
271            ("type", DagCbor::Text(self.service_type.as_str().to_owned())),
272        ])
273    }
274
275    fn from_value(value: &DagCbor) -> Result<Self> {
276        reject_unknown(value, &["endpoint", "id", "type"], "at9p service entry")?;
277        Self::new(
278            required_str(value, "id", "at9p service entry")?.to_owned(),
279            ServiceType::parse(required_str(value, "type", "at9p service entry")?)?,
280            ServiceEndpoint::from_value(required(value, "endpoint", "at9p service entry")?)?,
281        )
282    }
283}
284
285#[derive(Clone, Debug, Eq, PartialEq)]
286pub struct Delegation {
287    pub id: String,
288    pub target: String,
289    pub capabilities: Vec<String>,
290}
291
292impl Delegation {
293    pub fn new(
294        id: impl Into<String>,
295        target: impl Into<String>,
296        capabilities: Vec<String>,
297    ) -> Result<Self> {
298        let delegation = Self {
299            id: id.into(),
300            target: target.into(),
301            capabilities,
302        };
303        delegation.validate()?;
304        Ok(delegation)
305    }
306
307    pub fn validate(&self) -> Result<()> {
308        validate_nonempty_no_ws(&self.id, "delegation id")?;
309        validate_did_or_endpoint(&self.target, "delegation target")?;
310        ensure!(
311            !self.capabilities.is_empty(),
312            "delegation capabilities must not be empty"
313        );
314        validate_unique_texts(&self.capabilities, "delegation capabilities")?;
315        Ok(())
316    }
317
318    fn to_value(&self) -> DagCbor {
319        DagCbor::str_map([
320            (
321                "capabilities",
322                DagCbor::list(self.capabilities.iter().cloned().map(DagCbor::Text)),
323            ),
324            ("id", DagCbor::Text(self.id.clone())),
325            ("target", DagCbor::Text(self.target.clone())),
326        ])
327    }
328
329    fn from_value(value: &DagCbor) -> Result<Self> {
330        reject_unknown(value, &["capabilities", "id", "target"], "at9p delegation")?;
331        let capabilities = required(value, "capabilities", "at9p delegation")?
332            .as_list()?
333            .iter()
334            .map(|item| Ok(item.as_str()?.to_owned()))
335            .collect::<Result<Vec<_>>>()?;
336        Self::new(
337            required_str(value, "id", "at9p delegation")?.to_owned(),
338            required_str(value, "target", "at9p delegation")?.to_owned(),
339            capabilities,
340        )
341    }
342}
343
344#[derive(Clone, Debug, Eq, PartialEq)]
345pub struct CoseCompositeSignature {
346    pub context: String,
347    pub protected: Vec<u8>,
348    pub ed25519_signature: Vec<u8>,
349    pub mldsa65_signature: Vec<u8>,
350}
351
352impl CoseCompositeSignature {
353    pub fn new(
354        context: impl Into<String>,
355        protected: impl Into<Vec<u8>>,
356        ed25519_signature: impl Into<Vec<u8>>,
357        mldsa65_signature: impl Into<Vec<u8>>,
358    ) -> Result<Self> {
359        let sig = Self {
360            context: context.into(),
361            protected: protected.into(),
362            ed25519_signature: ed25519_signature.into(),
363            mldsa65_signature: mldsa65_signature.into(),
364        };
365        sig.validate()?;
366        Ok(sig)
367    }
368
369    pub fn validate(&self) -> Result<()> {
370        ensure!(
371            matches!(
372                self.context.as_str(),
373                CAPSULE_SIGNATURE_CONTEXT | UPDATE_SIGNATURE_CONTEXT | MANIFEST_SIGNATURE_CONTEXT
374            ),
375            "unsupported at9p COSE context {:?}",
376            self.context
377        );
378        ensure!(
379            !self.protected.is_empty(),
380            "COSE protected header is required"
381        );
382        ensure!(
383            self.ed25519_signature.len() == ED25519_SIGNATURE_LEN,
384            "Ed25519 signature must be {ED25519_SIGNATURE_LEN} bytes"
385        );
386        ensure!(
387            self.mldsa65_signature.len() == ML_DSA65_SIGNATURE_LEN,
388            "ML-DSA-65 signature must be {ML_DSA65_SIGNATURE_LEN} bytes"
389        );
390        Ok(())
391    }
392
393    fn ensure_context(&self, expected: &str) -> Result<()> {
394        ensure!(
395            self.context == expected,
396            "at9p signature context mismatch: expected {expected:?}, got {:?}",
397            self.context
398        );
399        Ok(())
400    }
401
402    fn to_value(&self) -> DagCbor {
403        DagCbor::str_map([
404            ("context", DagCbor::Text(self.context.clone())),
405            ("ed25519", DagCbor::Bytes(self.ed25519_signature.clone())),
406            ("mldsa65", DagCbor::Bytes(self.mldsa65_signature.clone())),
407            ("protected", DagCbor::Bytes(self.protected.clone())),
408        ])
409    }
410
411    fn from_value(value: &DagCbor) -> Result<Self> {
412        reject_unknown(
413            value,
414            &["context", "protected", "ed25519", "mldsa65"],
415            "at9p composite signature",
416        )?;
417        Self::new(
418            required_str(value, "context", "at9p composite signature")?.to_owned(),
419            required_bytes(value, "protected", "at9p composite signature")?.to_vec(),
420            required_bytes(value, "ed25519", "at9p composite signature")?.to_vec(),
421            required_bytes(value, "mldsa65", "at9p composite signature")?.to_vec(),
422        )
423    }
424}
425
426#[derive(Clone, Debug, Eq, PartialEq)]
427pub struct CapsuleBody {
428    pub version: String,
429    pub subject_keys: Vec<HybridKeyPair>,
430    pub next_key_commitments: Vec<[u8; H512_LEN]>,
431    pub services: Vec<ServiceEntry>,
432    pub label_hints: Option<Vec<String>>,
433    /// Classical DID aliases this `did:at9p` identity attests to — the
434    /// **hybrid-signed** leg of the `alsoKnownAs` aliasing bridge (#896 / D4,
435    /// design #879 Q4 / #905 §2/§6). Each entry is a `did:web` / `did:key` /
436    /// `did:plc` identifier the capsule claims to *also* be. Because the list
437    /// lives inside the GATE-verified capsule body, it is content-bound to the
438    /// at9p identity and signed under pinned Hybrid — the strongest of the two
439    /// aliasing legs. The reciprocal (classical→at9p) vouch is classical-only
440    /// (a DID document's best), so the authoritative-direction rule
441    /// (`at9p_alias::resolve_authoritative_alias`) requires **both** legs to
442    /// name each other before the at9p identity is trusted.
443    pub also_known_as: Option<Vec<String>>,
444    pub delegations: Option<Vec<Delegation>>,
445    pub witnesses: Option<Vec<String>>,
446}
447
448impl CapsuleBody {
449    pub fn new(subject_keys: Vec<HybridKeyPair>, services: Vec<ServiceEntry>) -> Result<Self> {
450        let body = Self {
451            version: CAPSULE_VERSION.to_owned(),
452            subject_keys,
453            next_key_commitments: Vec::new(),
454            services,
455            label_hints: None,
456            also_known_as: None,
457            delegations: None,
458            witnesses: None,
459        };
460        body.validate()?;
461        Ok(body)
462    }
463
464    /// Select the published subject key whose Ed25519 half equals `ed25519_pub`,
465    /// if any — the **set-semantics** accessor (#1188 / #1183).
466    ///
467    /// `subjectKeys` is a set of currently-usable identity keys, not an ordered
468    /// list with a positional "primary". A consumer that holds an Ed25519
469    /// application-signer key (admission #894, native announcements #1004) finds
470    /// *its* hybrid pair by identity, and takes the atomically-bound ML-DSA-65
471    /// half from the same entry. The schema guarantees at most one match
472    /// ([`validate_unique_subject_keys`] forbids a repeated Ed25519 half), so
473    /// this is unambiguous. Returns `None` when no published key matches — the
474    /// caller then rejects fail-closed, never falling back to a positional key.
475    pub fn subject_key_for_ed25519(&self, ed25519_pub: &[u8]) -> Option<&HybridKeyPair> {
476        self.subject_keys
477            .iter()
478            .find(|key| key.ed25519_pub.as_slice() == ed25519_pub)
479    }
480
481    /// Whether `ed25519_pub` is one of the published subject keys.
482    pub fn publishes_ed25519(&self, ed25519_pub: &[u8]) -> bool {
483        self.subject_key_for_ed25519(ed25519_pub).is_some()
484    }
485
486    /// Canonical DAG-CBOR bytes of the capsule body.
487    ///
488    /// This is the signed payload for an at9p capsule: the composite signature
489    /// (see [`crate::at9p_sign`]) covers exactly these bytes, never the
490    /// enclosing `signatures` field. Validates the body first so a record whose
491    /// pub fields were mutated after construction cannot emit (or get signed
492    /// over) bytes the decode side would reject.
493    pub fn to_dag_cbor(&self) -> Result<Vec<u8>> {
494        self.validate()?;
495        Ok(self.to_value().encode())
496    }
497
498    pub fn validate(&self) -> Result<()> {
499        ensure!(
500            self.version == CAPSULE_VERSION,
501            "unsupported at9p capsule version {:?}",
502            self.version
503        );
504        ensure!(
505            !self.subject_keys.is_empty(),
506            "capsule subjectKeys must not be empty"
507        );
508        for key in &self.subject_keys {
509            key.validate()?;
510        }
511        // subjectKeys is a *set*, not an ordered list with a positional
512        // "primary" (#1188 / #1183): consumers select a member by its atomic
513        // hybrid identity (Ed25519↔ML-DSA-65 pairing), never by index. Two
514        // identical pairs would be a meaningless repeat, and — worse — an
515        // ambiguous key-selection input. Reject duplicates by their
516        // commitment digest (the same BLAKE3-512 binding both halves that
517        // `next_key_commitments` uses), so overlap/rotation publishes *distinct*
518        // usable keys. A member sharing one half with another but differing on
519        // the other half is a distinct pair and is allowed (each is atomically
520        // bound), but an Ed25519 half MUST NOT repeat across pairs: selection by
521        // application signer key (admission, native announcements) keys on the
522        // Ed25519 half, so a repeated Ed25519 would reintroduce ambiguity.
523        validate_unique_subject_keys(&self.subject_keys)?;
524        // next_key_commitments MAY be empty (#879 §5.3: a declared-immutable
525        // identity with rotation frozen forever), but two identical commitments
526        // are meaningless (the same next key pre-committed twice) and would
527        // only waste bytes / invite ambiguity in key selection. Reject
528        // duplicates; each 64B entry is already length-checked on decode.
529        validate_unique_digests(&self.next_key_commitments, "nextKeyCommitments")?;
530        ensure!(
531            !self.services.is_empty(),
532            "capsule services must not be empty"
533        );
534        validate_unique_services(&self.services)?;
535        for service in &self.services {
536            service.validate()?;
537        }
538        if let Some(label_hints) = &self.label_hints {
539            ensure!(
540                !label_hints.is_empty(),
541                "labelHints must not be empty when present"
542            );
543            validate_unique_texts(label_hints, "labelHints")?;
544        }
545        if let Some(aliases) = &self.also_known_as {
546            ensure!(
547                !aliases.is_empty(),
548                "alsoKnownAs must not be empty when present"
549            );
550            validate_classical_did_list(aliases, "alsoKnownAs")?;
551        }
552        if let Some(delegations) = &self.delegations {
553            ensure!(
554                !delegations.is_empty(),
555                "delegations must not be empty when present"
556            );
557            for delegation in delegations {
558                delegation.validate()?;
559            }
560        }
561        if let Some(witnesses) = &self.witnesses {
562            ensure!(
563                !witnesses.is_empty(),
564                "witnesses must not be empty when present"
565            );
566            validate_unique_texts(witnesses, "witnesses")?;
567            for witness in witnesses {
568                validate_did_or_endpoint(witness, "witness")?;
569            }
570        }
571        Ok(())
572    }
573
574    fn to_value(&self) -> DagCbor {
575        let service_map = DagCbor::str_map(
576            self.services
577                .iter()
578                .map(|service| (service.id.clone(), service.to_value())),
579        );
580        let mut fields = vec![
581            (
582                "nextKeyCommitments",
583                DagCbor::list(
584                    self.next_key_commitments
585                        .iter()
586                        .map(|digest| DagCbor::Bytes(digest.to_vec())),
587                ),
588            ),
589            ("services", service_map),
590            (
591                "subjectKeys",
592                DagCbor::list(self.subject_keys.iter().map(HybridKeyPair::to_value)),
593            ),
594            ("version", DagCbor::Text(self.version.clone())),
595        ];
596        if let Some(label_hints) = &self.label_hints {
597            fields.push((
598                "labelHints",
599                DagCbor::list(label_hints.iter().cloned().map(DagCbor::Text)),
600            ));
601        }
602        if let Some(aliases) = &self.also_known_as {
603            fields.push((
604                "alsoKnownAs",
605                DagCbor::list(aliases.iter().cloned().map(DagCbor::Text)),
606            ));
607        }
608        if let Some(delegations) = &self.delegations {
609            fields.push((
610                "delegations",
611                DagCbor::list(delegations.iter().map(Delegation::to_value)),
612            ));
613        }
614        if let Some(witnesses) = &self.witnesses {
615            fields.push((
616                "witnesses",
617                DagCbor::list(witnesses.iter().cloned().map(DagCbor::Text)),
618            ));
619        }
620        DagCbor::str_map(fields)
621    }
622
623    fn from_value(value: &DagCbor) -> Result<Self> {
624        reject_unknown(
625            value,
626            &[
627                "version",
628                "subjectKeys",
629                "nextKeyCommitments",
630                "services",
631                "labelHints",
632                "alsoKnownAs",
633                "delegations",
634                "witnesses",
635            ],
636            "at9p capsule body",
637        )?;
638        let subject_keys = required(value, "subjectKeys", "at9p capsule body")?
639            .as_list()?
640            .iter()
641            .map(HybridKeyPair::from_value)
642            .collect::<Result<Vec<_>>>()?;
643        let next_key_commitments = required(value, "nextKeyCommitments", "at9p capsule body")?
644            .as_list()?
645            .iter()
646            .map(|digest| h512_from_slice(digest.as_bytes()?))
647            .collect::<Result<Vec<_>>>()?;
648        let services = parse_services(required(value, "services", "at9p capsule body")?)?;
649        let label_hints = optional_text_list(value, "labelHints")?;
650        let also_known_as = optional_text_list(value, "alsoKnownAs")?;
651        let delegations = match value.get("delegations") {
652            Some(v) => Some(
653                v.as_list()?
654                    .iter()
655                    .map(Delegation::from_value)
656                    .collect::<Result<Vec<_>>>()?,
657            ),
658            None => None,
659        };
660        let witnesses = optional_text_list(value, "witnesses")?;
661        let body = Self {
662            version: required_str(value, "version", "at9p capsule body")?.to_owned(),
663            subject_keys,
664            next_key_commitments,
665            services,
666            label_hints,
667            also_known_as,
668            delegations,
669            witnesses,
670        };
671        body.validate()?;
672        Ok(body)
673    }
674}
675
676#[derive(Clone, Debug, Eq, PartialEq)]
677pub struct Capsule {
678    pub body: CapsuleBody,
679    pub signatures: CoseCompositeSignature,
680}
681
682impl Capsule {
683    pub fn new(body: CapsuleBody, signatures: CoseCompositeSignature) -> Result<Self> {
684        signatures.ensure_context(CAPSULE_SIGNATURE_CONTEXT)?;
685        body.validate()?;
686        Ok(Self { body, signatures })
687    }
688
689    /// Validate the capsule (body + signature context binding) — the encode/
690    /// decode trust boundary. Public so holders of a `Capsule` built via struct
691    /// literal can check it before emitting bytes.
692    pub fn validate(&self) -> Result<()> {
693        self.body.validate()?;
694        self.signatures.ensure_context(CAPSULE_SIGNATURE_CONTEXT)?;
695        Ok(())
696    }
697
698    pub fn to_dag_cbor(&self) -> Result<Vec<u8>> {
699        self.validate()?;
700        Ok(self.encode_value())
701    }
702
703    pub fn from_dag_cbor(bytes: &[u8]) -> Result<Self> {
704        Self::from_value(&decode_canonical(bytes, "at9p capsule")?)
705    }
706
707    pub fn cid512(&self) -> Result<String> {
708        at9p_capsule_cid512(&self.to_dag_cbor()?)
709    }
710
711    /// Serialize without re-validating. For crate-internal digest/state
712    /// projection over capsules already known to be valid — they reached here
713    /// via [`Self::from_dag_cbor`] (validated) or the signing path. External
714    /// callers must use [`Self::to_dag_cbor`].
715    pub(crate) fn encode_value(&self) -> Vec<u8> {
716        self.to_value().encode()
717    }
718
719    fn to_value(&self) -> DagCbor {
720        DagCbor::str_map([
721            ("body", self.body.to_value()),
722            ("signatures", self.signatures.to_value()),
723        ])
724    }
725
726    fn from_value(value: &DagCbor) -> Result<Self> {
727        reject_unknown(value, &["body", "signatures"], "at9p capsule")?;
728        Self::new(
729            CapsuleBody::from_value(required(value, "body", "at9p capsule")?)?,
730            CoseCompositeSignature::from_value(required(value, "signatures", "at9p capsule")?)?,
731        )
732    }
733}
734
735#[derive(Clone, Debug, Eq, PartialEq)]
736pub struct UpdateRecord {
737    pub subject_cid512: String,
738    pub epoch: u64,
739    pub prev_record_digest: [u8; H512_LEN],
740    pub new_capsule_body: CapsuleBody,
741    pub expires_at: String,
742    pub signatures: CoseCompositeSignature,
743}
744
745impl UpdateRecord {
746    /// Validating constructor — the encode/decode trust boundary. Prefer this
747    /// over struct-literal construction so an invalid record is caught at the
748    /// call site rather than at [`Self::to_dag_cbor`] / [`Self::signable_bytes`].
749    pub fn new(
750        subject_cid512: String,
751        epoch: u64,
752        prev_record_digest: [u8; H512_LEN],
753        new_capsule_body: CapsuleBody,
754        expires_at: String,
755        signatures: CoseCompositeSignature,
756    ) -> Result<Self> {
757        let record = Self {
758            subject_cid512,
759            epoch,
760            prev_record_digest,
761            new_capsule_body,
762            expires_at,
763            signatures,
764        };
765        record.validate()?;
766        Ok(record)
767    }
768
769    pub fn to_dag_cbor(&self) -> Result<Vec<u8>> {
770        self.validate()?;
771        Ok(self.encode_value())
772    }
773
774    /// Serialize without re-validating. For crate-internal digest/state
775    /// projection (chain watermark, duplicity digest) over records already known
776    /// to be valid — they reached here via [`Self::from_dag_cbor`] (validated)
777    /// or the signing path. External callers must use [`Self::to_dag_cbor`].
778    pub(crate) fn encode_value(&self) -> Vec<u8> {
779        self.to_value().encode()
780    }
781
782    pub fn from_dag_cbor(bytes: &[u8]) -> Result<Self> {
783        Self::from_value(&decode_canonical(bytes, "at9p update record")?)
784    }
785
786    /// Canonical DAG-CBOR bytes of the update record *without* its `signatures`
787    /// field — the payload the composite signature covers (see
788    /// [`crate::at9p_sign`]). Validates the signed content (cid, datetime,
789    /// capsule body); the signature itself is excluded by definition.
790    pub fn signable_bytes(&self) -> Result<Vec<u8>> {
791        self.validate_content()?;
792        Ok(self.signable_value().encode())
793    }
794
795    fn signable_value(&self) -> DagCbor {
796        DagCbor::str_map([
797            ("epoch", DagCbor::Unsigned(self.epoch)),
798            ("expiresAt", DagCbor::Text(self.expires_at.clone())),
799            ("newCapsuleBody", self.new_capsule_body.to_value()),
800            (
801                "prevRecordDigest",
802                DagCbor::Bytes(self.prev_record_digest.to_vec()),
803            ),
804            ("subjectCid512", DagCbor::Text(self.subject_cid512.clone())),
805        ])
806    }
807
808    /// Validate the signed content (everything the signature covers) — cid,
809    /// datetime, and the new capsule body. Excludes the signature itself.
810    fn validate_content(&self) -> Result<()> {
811        validate_cid512(&self.subject_cid512)?;
812        validate_datetime(&self.expires_at)?;
813        self.new_capsule_body.validate()?;
814        Ok(())
815    }
816
817    /// Full validation: content plus the signature-context binding. The
818    /// encode/decode trust boundary.
819    pub fn validate(&self) -> Result<()> {
820        self.validate_content()?;
821        self.signatures.ensure_context(UPDATE_SIGNATURE_CONTEXT)?;
822        Ok(())
823    }
824
825    fn to_value(&self) -> DagCbor {
826        DagCbor::str_map([
827            ("epoch", DagCbor::Unsigned(self.epoch)),
828            ("expiresAt", DagCbor::Text(self.expires_at.clone())),
829            ("newCapsuleBody", self.new_capsule_body.to_value()),
830            (
831                "prevRecordDigest",
832                DagCbor::Bytes(self.prev_record_digest.to_vec()),
833            ),
834            ("signatures", self.signatures.to_value()),
835            ("subjectCid512", DagCbor::Text(self.subject_cid512.clone())),
836        ])
837    }
838
839    fn from_value(value: &DagCbor) -> Result<Self> {
840        reject_unknown(
841            value,
842            &[
843                "subjectCid512",
844                "epoch",
845                "prevRecordDigest",
846                "newCapsuleBody",
847                "expiresAt",
848                "signatures",
849            ],
850            "at9p update record",
851        )?;
852        let record = Self {
853            subject_cid512: required_str(value, "subjectCid512", "at9p update record")?.to_owned(),
854            epoch: required(value, "epoch", "at9p update record")?.as_unsigned()?,
855            prev_record_digest: h512_from_slice(required_bytes(
856                value,
857                "prevRecordDigest",
858                "at9p update record",
859            )?)?,
860            new_capsule_body: CapsuleBody::from_value(required(
861                value,
862                "newCapsuleBody",
863                "at9p update record",
864            )?)?,
865            expires_at: required_str(value, "expiresAt", "at9p update record")?.to_owned(),
866            signatures: CoseCompositeSignature::from_value(required(
867                value,
868                "signatures",
869                "at9p update record",
870            )?)?,
871        };
872        record.validate()?;
873        Ok(record)
874    }
875}
876
877#[derive(Clone, Debug, Eq, PartialEq)]
878pub struct ShardEntry {
879    pub index: u64,
880    pub shard_len: u64,
881    pub shard_digest: [u8; H512_LEN],
882}
883
884impl ShardEntry {
885    fn to_value(&self) -> DagCbor {
886        DagCbor::str_map([
887            ("index", DagCbor::Unsigned(self.index)),
888            ("shardDigest", DagCbor::Bytes(self.shard_digest.to_vec())),
889            ("shardLen", DagCbor::Unsigned(self.shard_len)),
890        ])
891    }
892
893    fn from_value(value: &DagCbor) -> Result<Self> {
894        reject_unknown(
895            value,
896            &["index", "shardLen", "shardDigest"],
897            "at9p shard entry",
898        )?;
899        Ok(Self {
900            index: required(value, "index", "at9p shard entry")?.as_unsigned()?,
901            shard_len: required(value, "shardLen", "at9p shard entry")?.as_unsigned()?,
902            shard_digest: h512_from_slice(required_bytes(
903                value,
904                "shardDigest",
905                "at9p shard entry",
906            )?)?,
907        })
908    }
909}
910
911#[derive(Clone, Debug, Eq, PartialEq)]
912pub struct Manifest {
913    pub subject_cid512: String,
914    pub codec: String,
915    pub total_len: u64,
916    pub shards: Vec<ShardEntry>,
917    pub signatures: CoseCompositeSignature,
918}
919
920impl Manifest {
921    /// Validating constructor — the encode/decode trust boundary. Prefer this
922    /// over struct-literal construction so an invalid manifest (e.g. mismatched
923    /// `totalLen`, non-contiguous shards, wrong signature context) is caught at
924    /// the call site rather than at [`Self::to_dag_cbor`].
925    pub fn new(
926        subject_cid512: String,
927        codec: String,
928        total_len: u64,
929        shards: Vec<ShardEntry>,
930        signatures: CoseCompositeSignature,
931    ) -> Result<Self> {
932        let manifest = Self {
933            subject_cid512,
934            codec,
935            total_len,
936            shards,
937            signatures,
938        };
939        manifest.validate()?;
940        Ok(manifest)
941    }
942
943    pub fn to_dag_cbor(&self) -> Result<Vec<u8>> {
944        self.validate()?;
945        Ok(self.to_value().encode())
946    }
947
948    pub fn from_dag_cbor(bytes: &[u8]) -> Result<Self> {
949        Self::from_value(&decode_canonical(bytes, "at9p manifest")?)
950    }
951
952    pub fn validate(&self) -> Result<()> {
953        validate_cid512(&self.subject_cid512)?;
954        validate_nonempty_no_ws(&self.codec, "manifest codec")?;
955        ensure!(!self.shards.is_empty(), "manifest shards must not be empty");
956        let mut expected = 0u64;
957        let mut summed_len = 0u64;
958        for shard in &self.shards {
959            ensure!(
960                shard.index == expected,
961                "manifest shard index must be contiguous: expected {expected}, got {}",
962                shard.index
963            );
964            ensure!(shard.shard_len > 0, "manifest shardLen must be nonzero");
965            summed_len = summed_len
966                .checked_add(shard.shard_len)
967                .context("manifest shard lengths overflow")?;
968            expected = expected
969                .checked_add(1)
970                .context("manifest shard index overflow")?;
971        }
972        ensure!(
973            summed_len == self.total_len,
974            "manifest totalLen {total_len} does not equal shard sum {summed_len}",
975            total_len = self.total_len
976        );
977        self.signatures.ensure_context(MANIFEST_SIGNATURE_CONTEXT)?;
978        Ok(())
979    }
980
981    fn to_value(&self) -> DagCbor {
982        DagCbor::str_map([
983            ("codec", DagCbor::Text(self.codec.clone())),
984            (
985                "shards",
986                DagCbor::list(self.shards.iter().map(ShardEntry::to_value)),
987            ),
988            ("signatures", self.signatures.to_value()),
989            ("subjectCid512", DagCbor::Text(self.subject_cid512.clone())),
990            ("totalLen", DagCbor::Unsigned(self.total_len)),
991        ])
992    }
993
994    fn from_value(value: &DagCbor) -> Result<Self> {
995        reject_unknown(
996            value,
997            &["subjectCid512", "codec", "totalLen", "shards", "signatures"],
998            "at9p manifest",
999        )?;
1000        let manifest = Self {
1001            subject_cid512: required_str(value, "subjectCid512", "at9p manifest")?.to_owned(),
1002            codec: required_str(value, "codec", "at9p manifest")?.to_owned(),
1003            total_len: required(value, "totalLen", "at9p manifest")?.as_unsigned()?,
1004            shards: required(value, "shards", "at9p manifest")?
1005                .as_list()?
1006                .iter()
1007                .map(ShardEntry::from_value)
1008                .collect::<Result<Vec<_>>>()?,
1009            signatures: CoseCompositeSignature::from_value(required(
1010                value,
1011                "signatures",
1012                "at9p manifest",
1013            )?)?,
1014        };
1015        manifest.validate()?;
1016        Ok(manifest)
1017    }
1018}
1019
1020#[derive(Clone, Debug, Eq, PartialEq)]
1021pub struct Shard {
1022    pub subject_cid512: String,
1023    pub index: u64,
1024    pub shard_bytes: Vec<u8>,
1025}
1026
1027impl Shard {
1028    /// Validating constructor — the encode/decode trust boundary.
1029    pub fn new(subject_cid512: String, index: u64, shard_bytes: Vec<u8>) -> Result<Self> {
1030        let shard = Self {
1031            subject_cid512,
1032            index,
1033            shard_bytes,
1034        };
1035        shard.validate()?;
1036        Ok(shard)
1037    }
1038
1039    /// Validate the shard's `subjectCid512` (the only field-level invariant).
1040    pub fn validate(&self) -> Result<()> {
1041        validate_cid512(&self.subject_cid512)
1042    }
1043
1044    pub fn to_dag_cbor(&self) -> Result<Vec<u8>> {
1045        self.validate()?;
1046        Ok(DagCbor::str_map([
1047            ("index", DagCbor::Unsigned(self.index)),
1048            ("shardBytes", DagCbor::Bytes(self.shard_bytes.clone())),
1049            ("subjectCid512", DagCbor::Text(self.subject_cid512.clone())),
1050        ])
1051        .encode())
1052    }
1053
1054    pub fn from_dag_cbor(bytes: &[u8]) -> Result<Self> {
1055        let value = decode_canonical(bytes, "at9p shard")?;
1056        reject_unknown(
1057            &value,
1058            &["subjectCid512", "index", "shardBytes"],
1059            "at9p shard",
1060        )?;
1061        let shard = Self {
1062            subject_cid512: required_str(&value, "subjectCid512", "at9p shard")?.to_owned(),
1063            index: required(&value, "index", "at9p shard")?.as_unsigned()?,
1064            shard_bytes: required_bytes(&value, "shardBytes", "at9p shard")?.to_vec(),
1065        };
1066        validate_cid512(&shard.subject_cid512)?;
1067        Ok(shard)
1068    }
1069}
1070
1071/// BLAKE3 extended to a 512-bit (`H512_LEN`-byte) output — the at9p digest
1072/// primitive (`H512` in design #879 §5). Used for capsule CIDs, update-record
1073/// linkage digests (`prev-record-digest`), and key commitments.
1074pub fn h512(bytes: &[u8]) -> [u8; H512_LEN] {
1075    let mut digest = [0u8; H512_LEN];
1076    let mut hasher = blake3::Hasher::new();
1077    hasher.update(bytes);
1078    hasher.finalize_xof().fill(&mut digest);
1079    digest
1080}
1081
1082pub fn at9p_capsule_cid512(canonical_capsule_bytes: &[u8]) -> Result<String> {
1083    let digest = h512(canonical_capsule_bytes);
1084    encode_cid(Codec::At9pCapsule, HashAlgo::Blake3, &digest)
1085}
1086
1087fn decode_canonical(bytes: &[u8], record_type: &str) -> Result<DagCbor> {
1088    let value = DagCbor::decode(bytes).with_context(|| format!("{record_type}: decode failed"))?;
1089    ensure!(
1090        value.encode() == bytes,
1091        "{record_type}: non-canonical DAG-CBOR encoding"
1092    );
1093    Ok(value)
1094}
1095
1096fn required<'a>(value: &'a DagCbor, key: &str, nsid: &str) -> Result<&'a DagCbor> {
1097    value
1098        .get(key)
1099        .ok_or_else(|| anyhow::anyhow!("{nsid}: missing required field {key:?}"))
1100}
1101
1102fn required_str<'a>(value: &'a DagCbor, key: &str, nsid: &str) -> Result<&'a str> {
1103    required(value, key, nsid)?.as_str()
1104}
1105
1106fn required_bytes<'a>(value: &'a DagCbor, key: &str, nsid: &str) -> Result<&'a [u8]> {
1107    required(value, key, nsid)?.as_bytes()
1108}
1109
1110fn optional_str<'a>(value: &'a DagCbor, key: &str) -> Result<Option<&'a str>> {
1111    match value.get(key) {
1112        Some(v) => Ok(Some(v.as_str()?)),
1113        None => Ok(None),
1114    }
1115}
1116
1117fn optional_text_list(value: &DagCbor, key: &str) -> Result<Option<Vec<String>>> {
1118    value
1119        .get(key)
1120        .map(|v| {
1121            v.as_list()?
1122                .iter()
1123                .map(|item| Ok(item.as_str()?.to_owned()))
1124                .collect::<Result<Vec<_>>>()
1125        })
1126        .transpose()
1127}
1128
1129fn reject_unknown(value: &DagCbor, allowed: &[&str], nsid: &str) -> Result<()> {
1130    for (k, _) in value.as_map()? {
1131        let key = k.as_str()?;
1132        ensure!(allowed.contains(&key), "{nsid}: unknown field {key:?}");
1133    }
1134    Ok(())
1135}
1136
1137fn parse_services(value: &DagCbor) -> Result<Vec<ServiceEntry>> {
1138    let mut services = Vec::new();
1139    for (key, entry) in value.as_map()? {
1140        let id = key.as_str()?;
1141        validate_service_id(id)?;
1142        let service = ServiceEntry::from_value(entry)?;
1143        ensure!(
1144            service.id == id,
1145            "service map key {id:?} does not match entry id {:?}",
1146            service.id
1147        );
1148        services.push(service);
1149    }
1150    Ok(services)
1151}
1152
1153fn h512_from_slice(bytes: &[u8]) -> Result<[u8; H512_LEN]> {
1154    ensure!(
1155        bytes.len() == H512_LEN,
1156        "H512 digest must be {H512_LEN} bytes, got {}",
1157        bytes.len()
1158    );
1159    let mut digest = [0u8; H512_LEN];
1160    digest.copy_from_slice(bytes);
1161    Ok(digest)
1162}
1163
1164fn validate_service_id(s: &str) -> Result<()> {
1165    ensure!(s.starts_with('#'), "service id must start with '#': {s:?}");
1166    ensure!(s.len() > 1, "service id must include a token: {s:?}");
1167    ensure!(
1168        s.as_bytes()[1..]
1169            .iter()
1170            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.')),
1171        "service id token contains invalid characters: {s:?}"
1172    );
1173    Ok(())
1174}
1175
1176fn validate_nonempty_no_ws(s: &str, field: &str) -> Result<()> {
1177    ensure!(!s.is_empty(), "{field} must not be empty");
1178    ensure!(
1179        !s.chars().any(char::is_whitespace),
1180        "{field} must not contain whitespace"
1181    );
1182    Ok(())
1183}
1184
1185fn validate_optional_no_ws(value: Option<&str>, field: &str) -> Result<()> {
1186    if let Some(value) = value {
1187        validate_nonempty_no_ws(value, field)?;
1188    }
1189    Ok(())
1190}
1191
1192fn validate_did_or_endpoint(s: &str, field: &str) -> Result<()> {
1193    validate_nonempty_no_ws(s, field)?;
1194    ensure!(
1195        s.starts_with("did:") || s.starts_with("https://") || s.starts_with("iroh:"),
1196        "{field} must be a did: identifier or endpoint URI"
1197    );
1198    Ok(())
1199}
1200
1201/// Strict ISO-8601 UTC datetime validator for at9p `expires-at` fields.
1202///
1203/// Accepts exactly `YYYY-MM-DDTHH:MM:SSZ` (20 chars, no fractional seconds,
1204/// `Z` zone designator). Unlike a separator-only check, this validates the
1205/// calendar fields — month 1..=12, day 1..=days-in-month (leap-aware), hour
1206/// 0..=23, minute/second 0..=59 (no leap-second `60`), year 0001..=9999 — so
1207/// nonsense like `0000-00-00T00:00:60Z` is rejected instead of passing. This
1208/// is the freshness-gate input for rotation records (#883/#879 §7.2); a loose
1209/// check would let a nonsensical `expires-at` reach the wire and the rollback
1210/// bound.
1211fn validate_datetime(s: &str) -> Result<()> {
1212    const EXPECTED_LEN: usize = 20; // YYYY-MM-DDTHH:MM:SSZ
1213    ensure!(
1214        s.len() == EXPECTED_LEN,
1215        "datetime must be {EXPECTED_LEN} chars (YYYY-MM-DDTHH:MM:SSZ): {s:?}"
1216    );
1217    let b = s.as_bytes();
1218    ensure!(
1219        b[4] == b'-'
1220            && b[7] == b'-'
1221            && b[10] == b'T'
1222            && b[13] == b':'
1223            && b[16] == b':'
1224            && b[19] == b'Z',
1225        "datetime must be ISO-8601 UTC (YYYY-MM-DDTHH:MM:SSZ): {s:?}"
1226    );
1227    let year = four_digit_field(&b[0..4], s, "year")?;
1228    let month = two_digit_field(&b[5..7], s, "month")?;
1229    let day = two_digit_field(&b[8..10], s, "day")?;
1230    let hour = two_digit_field(&b[11..13], s, "hour")?;
1231    let minute = two_digit_field(&b[14..16], s, "minute")?;
1232    let second = two_digit_field(&b[17..19], s, "second")?;
1233    ensure!(
1234        (1..=9999).contains(&year),
1235        "datetime year out of range 0001..=9999: {s:?}"
1236    );
1237    ensure!(
1238        (1..=12).contains(&month),
1239        "datetime month out of range 1..=12: {s:?}"
1240    );
1241    let max_day = days_in_month(year, month);
1242    ensure!(
1243        (1..=max_day).contains(&day),
1244        "datetime day out of range 1..={max_day} for {year}-{month:02}: {s:?}"
1245    );
1246    ensure!(hour <= 23, "datetime hour out of range 0..=23: {s:?}");
1247    ensure!(minute <= 59, "datetime minute out of range 0..=59: {s:?}");
1248    ensure!(
1249        second <= 59,
1250        "datetime second out of range 0..=59 (no leap seconds): {s:?}"
1251    );
1252    Ok(())
1253}
1254
1255/// Parse a fixed 2-digit decimal field, requiring both bytes to be ASCII
1256/// digits; returns the value or a datetime-shaped error.
1257fn two_digit_field(g: &[u8], s: &str, name: &str) -> Result<u32> {
1258    ensure!(
1259        g.len() == 2 && g[0].is_ascii_digit() && g[1].is_ascii_digit(),
1260        "datetime {name} must be two decimal digits: {s:?}"
1261    );
1262    Ok((g[0] - b'0') as u32 * 10 + (g[1] - b'0') as u32)
1263}
1264
1265/// Parse a fixed 4-digit decimal field (the year).
1266fn four_digit_field(g: &[u8], s: &str, name: &str) -> Result<u32> {
1267    ensure!(
1268        g.len() == 4 && g.iter().all(u8::is_ascii_digit),
1269        "datetime {name} must be four decimal digits: {s:?}"
1270    );
1271    let mut v = 0u32;
1272    for &c in g {
1273        v = v * 10 + (c - b'0') as u32;
1274    }
1275    Ok(v)
1276}
1277
1278/// Proleptic Gregorian leap-year test.
1279fn is_leap_year(year: u32) -> bool {
1280    year.is_multiple_of(4) && !year.is_multiple_of(100) || year.is_multiple_of(400)
1281}
1282
1283/// Days in a Gregorian month, leap-year aware. `month` is validated 1..=12 by
1284/// the caller; any other value is not a real calendar month and yields `0`
1285/// (the day-range check in [`validate_datetime`] then rejects it).
1286fn days_in_month(year: u32, month: u32) -> u32 {
1287    match month {
1288        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
1289        4 | 6 | 9 | 11 => 30,
1290        2 if is_leap_year(year) => 29,
1291        2 => 28,
1292        _ => 0,
1293    }
1294}
1295
1296fn validate_cid512(s: &str) -> Result<()> {
1297    let cid = hyprstream_rpc::cid::decode_cid(s)?;
1298    ensure!(
1299        cid.codec == Codec::At9pCapsule,
1300        "cid512 must use at9p-capsule multicodec"
1301    );
1302    ensure!(
1303        cid.multihash.algo == HashAlgo::Blake3 && cid.multihash.digest.len() == H512_LEN,
1304        "cid512 must use BLAKE3-512 multihash"
1305    );
1306    Ok(())
1307}
1308
1309fn validate_unique_services(services: &[ServiceEntry]) -> Result<()> {
1310    let mut ids = BTreeSet::new();
1311    for service in services {
1312        ensure!(
1313            ids.insert(service.id.as_str()),
1314            "duplicate service id {:?}",
1315            service.id
1316        );
1317    }
1318    Ok(())
1319}
1320
1321fn validate_unique_texts(values: &[String], field: &str) -> Result<()> {
1322    let mut seen = BTreeSet::new();
1323    for value in values {
1324        validate_nonempty_no_ws(value, field)?;
1325        ensure!(
1326            seen.insert(value.as_str()),
1327            "duplicate {field} entry {value:?}"
1328        );
1329    }
1330    Ok(())
1331}
1332
1333/// Validate the classical DID aliases a `did:at9p` capsule can reciprocally
1334/// attest to (#896 / D4): `did:web`, `did:key`, or `did:plc`, duplicate-free.
1335fn validate_classical_did_list(values: &[String], field: &str) -> Result<()> {
1336    validate_unique_texts(values, field)?;
1337    for value in values {
1338        ensure!(
1339            value.starts_with("did:web:")
1340                || value.starts_with("did:key:")
1341                || value.starts_with("did:plc:"),
1342            "{field} entry {value:?} must be a classical DID alias \
1343             (did:web, did:key, or did:plc)"
1344        );
1345    }
1346    Ok(())
1347}
1348
1349/// Reject duplicate `H512` digests. The list may be empty (no iteration), but
1350/// two equal digests are a meaningless repeat — used for `next_key_commitments`.
1351fn validate_unique_digests(digests: &[[u8; H512_LEN]], field: &str) -> Result<()> {
1352    let mut seen = BTreeSet::new();
1353    for digest in digests {
1354        ensure!(seen.insert(digest.as_slice()), "duplicate {field} entry");
1355    }
1356    Ok(())
1357}
1358
1359/// Reject an ambiguous `subjectKeys` *set* (#1188 / #1183).
1360///
1361/// `subjectKeys` publishes every currently-usable identity key so overlap
1362/// rotation and PQ-hybrid rollout work by publishing the new key alongside the
1363/// old and letting each verifier select the member it understands (the JWKS
1364/// `kid` discipline, applied to hybrid pairs). For that selection to be
1365/// unambiguous:
1366///
1367/// - no two entries may be the *same* atomic pair (identical commitment
1368///   digest) — a meaningless repeat; and
1369/// - no Ed25519 half may repeat across entries — application-signer selection
1370///   (admission #894, native announcements #1004) keys on the Ed25519 half, so
1371///   a repeated Ed25519 would make "which hybrid pair authorizes this signer?"
1372///   ambiguous, exactly the positional-authority failure #1188 removes.
1373fn validate_unique_subject_keys(keys: &[HybridKeyPair]) -> Result<()> {
1374    let mut seen_pairs = BTreeSet::new();
1375    let mut seen_ed25519 = BTreeSet::new();
1376    for key in keys {
1377        ensure!(
1378            seen_pairs.insert(key.commitment_digest()),
1379            "duplicate subjectKeys entry (identical hybrid pair)"
1380        );
1381        ensure!(
1382            seen_ed25519.insert(key.ed25519_pub.clone()),
1383            "duplicate subjectKeys Ed25519 half across hybrid pairs — \
1384             ambiguous key selection"
1385        );
1386    }
1387    Ok(())
1388}
1389
1390#[cfg(test)]
1391mod tests {
1392    #![allow(
1393        clippy::unwrap_used,
1394        clippy::expect_used,
1395        clippy::indexing_slicing,
1396        clippy::panic
1397    )]
1398
1399    use proptest::prelude::*;
1400
1401    use super::*;
1402
1403    fn bytes(len: usize, seed: u8) -> Vec<u8> {
1404        (0..len).map(|i| seed.wrapping_add(i as u8)).collect()
1405    }
1406
1407    fn digest(seed: u8) -> [u8; H512_LEN] {
1408        let mut out = [0u8; H512_LEN];
1409        for (i, b) in out.iter_mut().enumerate() {
1410            *b = seed.wrapping_add(i as u8);
1411        }
1412        out
1413    }
1414
1415    fn signature(context: &str, seed: u8) -> CoseCompositeSignature {
1416        CoseCompositeSignature::new(
1417            context,
1418            bytes(8, seed),
1419            bytes(ED25519_SIGNATURE_LEN, seed.wrapping_add(1)),
1420            bytes(ML_DSA65_SIGNATURE_LEN, seed.wrapping_add(2)),
1421        )
1422        .unwrap()
1423    }
1424
1425    fn key(seed: u8) -> HybridKeyPair {
1426        HybridKeyPair::new(
1427            bytes(ED25519_PUBLIC_KEY_LEN, seed),
1428            bytes(ML_DSA65_PUBLIC_KEY_LEN, seed.wrapping_add(16)),
1429        )
1430        .unwrap()
1431    }
1432
1433    fn service(id: String, service_type: ServiceType, seed: u8) -> ServiceEntry {
1434        let mut endpoint =
1435            ServiceEndpoint::new(Transport::Iroh, format!("iroh://node{seed}")).unwrap();
1436        endpoint.node_id = Some(format!("node{seed}"));
1437        endpoint.relay = Some(format!("https://relay{seed}.example"));
1438        endpoint.export = Some(format!("/exports/{seed}"));
1439        ServiceEntry::new(id, service_type, endpoint).unwrap()
1440    }
1441
1442    fn sample_capsule(seed: u8) -> Capsule {
1443        let mut body = CapsuleBody::new(
1444            vec![key(seed)],
1445            vec![
1446                service("#ns".to_owned(), ServiceType::NinePExport, seed),
1447                service(
1448                    "#pds".to_owned(),
1449                    ServiceType::AtprotoPds,
1450                    seed.wrapping_add(1),
1451                ),
1452            ],
1453        )
1454        .unwrap();
1455        body.next_key_commitments = vec![digest(seed.wrapping_add(3))];
1456        body.label_hints = Some(vec![format!("tenant{seed}")]);
1457        body.also_known_as = Some(vec![
1458            format!("did:web:node{seed}.example"),
1459            format!("did:key:z6Mkaka{seed}"),
1460        ]);
1461        body.witnesses = Some(vec![format!("did:at9p:witness{seed}")]);
1462        Capsule::new(body, signature(CAPSULE_SIGNATURE_CONTEXT, seed)).unwrap()
1463    }
1464
1465    fn arb_capsule() -> impl Strategy<Value = Capsule> {
1466        (0u8..=200).prop_map(sample_capsule)
1467    }
1468
1469    proptest! {
1470        #[test]
1471        fn capsule_round_trip_is_byte_stable(capsule in arb_capsule()) {
1472            let bytes = capsule.to_dag_cbor().unwrap();
1473            let decoded = Capsule::from_dag_cbor(&bytes).unwrap();
1474            prop_assert_eq!(&decoded, &capsule);
1475            prop_assert_eq!(decoded.to_dag_cbor().unwrap(), bytes);
1476            prop_assert!(decoded.cid512().unwrap().starts_with('b'));
1477        }
1478
1479        #[test]
1480        fn update_record_round_trip_is_byte_stable(capsule in arb_capsule(), epoch in 0u64..1000) {
1481            let subject_cid512 = capsule.cid512().unwrap();
1482            let record = UpdateRecord {
1483                subject_cid512,
1484                epoch,
1485                prev_record_digest: digest(42),
1486                new_capsule_body: capsule.body,
1487                expires_at: "2026-07-08T12:00:00Z".to_owned(),
1488                signatures: signature(UPDATE_SIGNATURE_CONTEXT, 7),
1489            };
1490            let bytes = record.to_dag_cbor().unwrap();
1491            let decoded = UpdateRecord::from_dag_cbor(&bytes).unwrap();
1492            prop_assert_eq!(&decoded, &record);
1493            prop_assert_eq!(decoded.to_dag_cbor().unwrap(), bytes);
1494        }
1495
1496        #[test]
1497        fn manifest_round_trip_is_byte_stable(capsule in arb_capsule(), shard_len in 1u64..4096) {
1498            let manifest = Manifest {
1499                subject_cid512: capsule.cid512().unwrap(),
1500                codec: "dag-cbor".to_owned(),
1501                total_len: shard_len,
1502                shards: vec![ShardEntry {
1503                    index: 0,
1504                    shard_len,
1505                    shard_digest: digest(9),
1506                }],
1507                signatures: signature(MANIFEST_SIGNATURE_CONTEXT, 10),
1508            };
1509            let bytes = manifest.to_dag_cbor().unwrap();
1510            let decoded = Manifest::from_dag_cbor(&bytes).unwrap();
1511            prop_assert_eq!(&decoded, &manifest);
1512            prop_assert_eq!(decoded.to_dag_cbor().unwrap(), bytes);
1513        }
1514    }
1515
1516    #[test]
1517    fn capsule_rejects_unsorted_map_keys() {
1518        let good = sample_capsule(1).to_dag_cbor().unwrap();
1519        let decoded = DagCbor::decode(&good).unwrap();
1520        let DagCbor::Map(mut pairs) = decoded else {
1521            panic!("capsule must encode as map");
1522        };
1523        pairs.reverse();
1524        let bad = DagCbor::Map(pairs).encode();
1525        assert!(Capsule::from_dag_cbor(&bad).is_err());
1526    }
1527
1528    #[test]
1529    fn capsule_rejects_duplicate_map_keys() {
1530        let bad = DagCbor::Map(vec![
1531            (
1532                DagCbor::Text("body".to_owned()),
1533                sample_capsule(1).body.to_value(),
1534            ),
1535            (
1536                DagCbor::Text("body".to_owned()),
1537                sample_capsule(2).body.to_value(),
1538            ),
1539            (
1540                DagCbor::Text("signatures".to_owned()),
1541                signature(CAPSULE_SIGNATURE_CONTEXT, 1).to_value(),
1542            ),
1543        ])
1544        .encode();
1545        assert!(Capsule::from_dag_cbor(&bad).is_err());
1546    }
1547
1548    #[test]
1549    fn update_rejects_non_minimal_ints() {
1550        let capsule = sample_capsule(5);
1551        let record = UpdateRecord {
1552            subject_cid512: capsule.cid512().unwrap(),
1553            epoch: 23,
1554            prev_record_digest: digest(44),
1555            new_capsule_body: capsule.body,
1556            expires_at: "2026-07-08T12:00:00Z".to_owned(),
1557            signatures: signature(UPDATE_SIGNATURE_CONTEXT, 8),
1558        };
1559        let mut bad = record.to_dag_cbor().unwrap();
1560        let pos = bad
1561            .windows(5)
1562            .position(|w| w == b"epoch")
1563            .expect("epoch key present")
1564            + 5;
1565        assert_eq!(bad[pos], 23);
1566        bad.splice(pos..pos + 1, [0x18, 23]);
1567        assert!(UpdateRecord::from_dag_cbor(&bad).is_err());
1568    }
1569
1570    #[test]
1571    fn capsule_cid512_uses_rpc_at9p_blake3_512_cid_api() {
1572        let capsule = sample_capsule(3);
1573        let cid = capsule.cid512().unwrap();
1574        let decoded = hyprstream_rpc::cid::decode_cid(&cid).unwrap();
1575        assert_eq!(decoded.codec, Codec::At9pCapsule);
1576        assert_eq!(decoded.multihash.algo, HashAlgo::Blake3);
1577        assert_eq!(decoded.multihash.digest.len(), H512_LEN);
1578    }
1579
1580    #[test]
1581    fn also_known_as_round_trips_and_round_trips_byte_stable() {
1582        let capsule = sample_capsule(7);
1583        // The fixture sets two classical aliases.
1584        assert_eq!(
1585            capsule.body.also_known_as.as_deref().unwrap(),
1586            &[
1587                "did:web:node7.example".to_owned(),
1588                "did:key:z6Mkaka7".to_owned()
1589            ]
1590        );
1591        // Byte-stable canonical round-trip carries alsoKnownAs.
1592        let bytes = capsule.to_dag_cbor().unwrap();
1593        let decoded = Capsule::from_dag_cbor(&bytes).unwrap();
1594        assert_eq!(&decoded, &capsule);
1595        assert_eq!(decoded.to_dag_cbor().unwrap(), bytes);
1596    }
1597
1598    #[test]
1599    fn also_known_as_rejects_non_did_and_duplicates() {
1600        let mut body = CapsuleBody::new(
1601            vec![key(1)],
1602            vec![service("#ns".to_owned(), ServiceType::NinePExport, 1)],
1603        )
1604        .unwrap();
1605        // Non-DID entry rejected at the schema gate.
1606        body.also_known_as = Some(vec!["https://not.a.did.example".to_owned()]);
1607        assert!(body.validate().is_err());
1608        // Duplicate entry rejected.
1609        body.also_known_as = Some(vec![
1610            "did:web:dup.example".to_owned(),
1611            "did:web:dup.example".to_owned(),
1612        ]);
1613        assert!(body.validate().is_err());
1614        // did:at9p is the capsule identity, not a classical alias.
1615        body.also_known_as = Some(vec!["did:at9p:bafynotaclassicalalias".to_owned()]);
1616        assert!(body.validate().is_err());
1617        // Empty list rejected (must not be empty when present).
1618        body.also_known_as = Some(Vec::new());
1619        assert!(body.validate().is_err());
1620        // Clean classical DID aliases validate.
1621        body.also_known_as = Some(vec!["did:web:clean.example".to_owned()]);
1622        assert!(body.validate().is_ok());
1623        body.also_known_as = Some(vec!["did:plc:clean".to_owned()]);
1624        assert!(body.validate().is_ok());
1625    }
1626
1627    /// Issue #934 (validate-on-encode): pub fields allow post-construction
1628    /// mutation, so encode must re-validate and fail closed rather than emit
1629    /// (or sign over / cid) bytes the decode side would reject.
1630    #[test]
1631    fn encode_rejects_post_construction_mutation() {
1632        let mut capsule = sample_capsule(1);
1633        capsule.body.subject_keys.clear(); // now invalid (empty subject keys)
1634        assert!(capsule.body.to_dag_cbor().is_err());
1635        assert!(
1636            capsule.to_dag_cbor().is_err(),
1637            "capsule encode must validate"
1638        );
1639        assert!(capsule.cid512().is_err(), "cid512 must validate");
1640
1641        // A record whose signature context was swapped still encodes its bytes
1642        // fine for content, but a fully-mutated invalid body fails signable too.
1643        let capsule2 = sample_capsule(2);
1644        let mut record = UpdateRecord {
1645            subject_cid512: capsule2.cid512().unwrap(),
1646            epoch: 0,
1647            prev_record_digest: digest(1),
1648            new_capsule_body: capsule2.body.clone(),
1649            expires_at: "2026-07-08T12:00:00Z".to_owned(),
1650            signatures: signature(UPDATE_SIGNATURE_CONTEXT, 3),
1651        };
1652        assert!(record.signable_bytes().is_ok(), "valid content encodes");
1653        assert!(record.to_dag_cbor().is_ok(), "valid record encodes");
1654        record.new_capsule_body.subject_keys.clear();
1655        assert!(record.signable_bytes().is_err(), "invalid content rejected");
1656        assert!(record.to_dag_cbor().is_err());
1657    }
1658
1659    /// Issue #934 (validating constructors): the new `new()` constructors close
1660    /// the "no validating constructor" gap for UpdateRecord/Manifest/Shard.
1661    #[test]
1662    fn validating_constructors_reject_invalid() {
1663        let capsule = sample_capsule(1);
1664        let cid = capsule.cid512().unwrap();
1665
1666        // UpdateRecord::new rejects a bad datetime.
1667        assert!(UpdateRecord::new(
1668            cid.clone(),
1669            0,
1670            digest(1),
1671            capsule.body.clone(),
1672            "0000-00-00T00:00:60Z".to_owned(),
1673            signature(UPDATE_SIGNATURE_CONTEXT, 2),
1674        )
1675        .is_err());
1676
1677        // Manifest::new rejects a mismatched totalLen (shard sum is 10, not 999).
1678        assert!(Manifest::new(
1679            cid.clone(),
1680            "dag-cbor".to_owned(),
1681            999,
1682            vec![ShardEntry {
1683                index: 0,
1684                shard_len: 10,
1685                shard_digest: digest(9),
1686            }],
1687            signature(MANIFEST_SIGNATURE_CONTEXT, 1),
1688        )
1689        .is_err());
1690
1691        // Shard::new rejects a malformed subjectCid512.
1692        assert!(Shard::new("not-a-cid".to_owned(), 0, vec![0u8; 4]).is_err());
1693        // ... and accepts a valid one.
1694        assert!(Shard::new(cid.clone(), 0, vec![0u8; 4]).is_ok());
1695    }
1696
1697    /// Issue #934 (datetime tightening): the old validator only checked
1698    /// separator positions, letting nonsense like `0000-00-00T00:00:60Z`
1699    /// through. Validate the actual calendar fields.
1700    #[test]
1701    fn validate_datetime_is_strict_iso8601_utc() {
1702        fn check(expires: &str) -> Result<()> {
1703            let capsule = sample_capsule(1);
1704            UpdateRecord {
1705                subject_cid512: capsule.cid512().unwrap(),
1706                epoch: 0,
1707                prev_record_digest: digest(1),
1708                new_capsule_body: capsule.body,
1709                expires_at: expires.to_owned(),
1710                signatures: signature(UPDATE_SIGNATURE_CONTEXT, 2),
1711            }
1712            .validate()
1713        }
1714        // The exact nonsense the old separator-only check let through.
1715        assert!(check("0000-00-00T00:00:60Z").is_err());
1716        // Leap second 60.
1717        assert!(check("2026-07-08T12:00:60Z").is_err());
1718        // Month 13 / day 0 / hour 24.
1719        assert!(check("2026-13-08T12:00:00Z").is_err());
1720        assert!(check("2026-07-00T12:00:00Z").is_err());
1721        assert!(check("2026-07-08T24:00:00Z").is_err());
1722        // Minute / second 60.
1723        assert!(check("2026-07-08T12:60:00Z").is_err());
1724        // Fractional seconds (wrong length / not the Z-terminated 20-char form).
1725        assert!(check("2026-07-08T12:00:00.5Z").is_err());
1726        // Feb 29 in a non-leap year.
1727        assert!(check("2023-02-29T00:00:00Z").is_err());
1728        // Day 32.
1729        assert!(check("2026-07-32T12:00:00Z").is_err());
1730        // Wrong length (too short).
1731        assert!(check("2026-07-08T12:00Z").is_err());
1732        // Non-UTC zone designator.
1733        assert!(check("2026-07-08T12:00:00+00:00").is_err());
1734
1735        // Valid values still pass — including a leap day and far-future dates.
1736        assert!(check("2026-07-08T12:00:00Z").is_ok());
1737        assert!(check("2024-02-29T00:00:00Z").is_ok()); // 2024 is a leap year
1738        assert!(check("2099-01-01T00:00:00Z").is_ok());
1739        assert!(check("2023-02-28T23:59:59Z").is_ok());
1740    }
1741
1742    /// Issue #934 (next_key_commitments): MAY be empty (#879 §5.3
1743    /// declared-immutable), but duplicate commitments are a meaningless repeat
1744    /// and must be rejected.
1745    #[test]
1746    fn next_key_commitments_empty_ok_duplicates_rejected() {
1747        let mut body = CapsuleBody::new(
1748            vec![key(1)],
1749            vec![service("#ns".to_owned(), ServiceType::NinePExport, 1)],
1750        )
1751        .unwrap();
1752        // Empty is allowed (declared-immutable identity).
1753        assert!(body.validate().is_ok());
1754        // A single commitment is fine.
1755        body.next_key_commitments = vec![digest(5)];
1756        assert!(body.validate().is_ok());
1757        // Two identical commitments are rejected.
1758        body.next_key_commitments = vec![digest(5), digest(5)];
1759        assert!(body.validate().is_err());
1760        // Two distinct commitments are fine.
1761        body.next_key_commitments = vec![digest(5), digest(6)];
1762        assert!(body.validate().is_ok());
1763    }
1764}