Skip to main content

hyprstream_pds/
commit.rs

1//! Signed atproto repository commits.
2//!
3//! A commit is the **signed mutable pointer**: it binds an MST root CID (the
4//! immutable record-store snapshot) to a DID at a revision, signed by the DID's
5//! `#atproto` P-256 key. This is what federation verifies to trust a host's
6//! claim about an account's state — the consensus-free versioning primitive.
7//!
8//! # Structure (atproto v3)
9//!
10//! ```text
11//! Commit {
12//!   did:     String,        // account DID (did:web / did:plc)
13//!   version: u64 = 3,       // protocol version
14//!   data:    Cid (link),    // MST root
15//!   rev:     String,        // TID revision
16//!   prev:    Option<Cid>,   // previous commit (None for genesis)
17//!   sig:     Vec<u8>,       // ES256 signature over the unsigned commit
18//! }
19//! ```
20//!
21//! # Signing
22//!
23//! `sig` is ES256 (P-256 ECDSA over SHA-256) of the DAG-CBOR encoding of the
24//! **unsigned commit** — the commit object with the `sig` field *omitted* (not
25//! present-and-empty). The verifier re-encodes the unsigned form and checks the
26//! signature against the DID's published `#atproto` P-256 verifying key.
27
28use anyhow::{anyhow, bail, ensure, Result};
29use p256::ecdsa::{signature::Signer, Signature, SigningKey, VerifyingKey};
30use sha2::{Digest, Sha256};
31
32use crate::cid::Cid;
33use crate::dag_cbor::DagCbor;
34use crate::tid::Tid;
35
36/// The commit version number (atproto v3).
37pub const COMMIT_VERSION: u64 = 3;
38
39/// An unsigned commit — the form that gets DAG-CBOR-encoded and signed.
40///
41/// Field order matches atproto (`did`, `version`, `data`, `rev`, `prev`); the
42/// existing native encoder re-sorts in its historical lexical text-key order.
43/// Public AT serialization is available through `to_atproto_dag_cbor` and uses
44/// encoded-key ordering without changing existing native bytes. `version` is
45/// always [`COMMIT_VERSION`] = 3.
46#[derive(Clone, Debug, Eq, PartialEq)]
47pub struct UnsignedCommit {
48    pub did: String,
49    pub version: u64,
50    pub data: Cid,
51    pub rev: Tid,
52    pub prev: Option<Cid>,
53}
54
55impl UnsignedCommit {
56    pub fn new(did: impl Into<String>, data: Cid, rev: Tid, prev: Option<Cid>) -> Self {
57        UnsignedCommit {
58            did: did.into(),
59            version: COMMIT_VERSION,
60            data,
61            rev,
62            prev,
63        }
64    }
65
66    /// DAG-CBOR encode the unsigned commit (no `sig` field). This is what gets signed.
67    pub fn to_dag_cbor(&self) -> Vec<u8> {
68        self.to_value().encode()
69    }
70
71    /// Encode this commit's unsigned body using public AT Protocol ordering.
72    /// The native `to_dag_cbor` format is retained for existing artifacts.
73    pub fn to_atproto_dag_cbor(&self) -> Result<Vec<u8>> {
74        crate::atproto_cbor::encode(&self.to_value())
75    }
76
77    pub fn to_value(&self) -> DagCbor {
78        DagCbor::str_map([
79            ("did", DagCbor::Text(self.did.clone())),
80            ("version", DagCbor::Unsigned(self.version)),
81            ("data", DagCbor::Link(self.data)),
82            ("rev", DagCbor::Text(self.rev.encode())),
83            (
84                "prev",
85                match &self.prev {
86                    Some(c) => DagCbor::Link(*c),
87                    None => DagCbor::Null,
88                },
89            ),
90        ])
91    }
92}
93
94/// A signed commit — the unsigned commit plus its ES256 `sig`.
95#[derive(Clone, Debug, Eq, PartialEq)]
96pub struct Commit {
97    pub did: String,
98    pub version: u64,
99    pub data: Cid,
100    pub rev: Tid,
101    pub prev: Option<Cid>,
102    pub sig: Vec<u8>,
103    /// Whether this value was produced or decoded through the public
104    /// AT Protocol canonical-signature boundary. Native commits are never
105    /// eligible for public CAR publication without an explicit conversion.
106    atproto_signature: bool,
107    /// Canonical public bytes at the provenance boundary. Public fields are
108    /// intentionally retained for compatibility, so publication must also
109    /// detect any mutation after signing or decoding.
110    atproto_canonical_bytes: Option<Vec<u8>>,
111}
112
113impl Commit {
114    /// Sign an unsigned commit with a P-256 (`#atproto`) signing key,
115    /// producing a [`Commit`].
116    ///
117    /// The signature is ES256: ECDSA over SHA-256 of the unsigned commit's
118    /// DAG-CBOR bytes. The signature is the fixed-width (64-byte) R‖V‖S
119    /// encoding — `Signature::to_vec` in `p256` 0.13 gives this form, which is
120    /// the JOSE/COSE/atproto-preferred raw concatenation (not DER).
121    pub fn sign(unsigned: &UnsignedCommit, key: &SigningKey) -> Self {
122        let unsigned_bytes = unsigned.to_dag_cbor();
123        // ES256 = ECDSA with SHA-256. p256's `Signer<Vec<u8>>` impl hashes
124        // internally and emits the raw 64-byte R‖V‖S form.
125        let sig: Signature = key.sign(&unsigned_bytes);
126        Commit {
127            did: unsigned.did.clone(),
128            version: unsigned.version,
129            data: unsigned.data,
130            rev: unsigned.rev,
131            prev: unsigned.prev,
132            sig: sig.to_vec(),
133            atproto_signature: false,
134            atproto_canonical_bytes: None,
135        }
136    }
137
138    /// Sign a commit using public AT Protocol canonical bytes.
139    pub fn sign_atproto(unsigned: &UnsignedCommit, key: &SigningKey) -> Result<Self> {
140        use p256::ecdsa::signature::Signer;
141        ensure!(
142            unsigned.version == COMMIT_VERSION,
143            "unsupported public commit version {} (expected {COMMIT_VERSION})",
144            unsigned.version
145        );
146        let sig: Signature = key.sign(&unsigned.to_atproto_dag_cbor()?);
147        let mut commit = Commit {
148            did: unsigned.did.clone(),
149            version: unsigned.version,
150            data: unsigned.data,
151            rev: unsigned.rev,
152            prev: unsigned.prev,
153            sig: sig.to_vec(),
154            atproto_signature: true,
155            atproto_canonical_bytes: None,
156        };
157        commit.atproto_canonical_bytes = Some(commit.to_atproto_dag_cbor()?);
158        Ok(commit)
159    }
160
161    /// Build a public commit from a signature produced by an external signer.
162    ///
163    /// The signer receives the exact canonical unsigned bytes and the supplied
164    /// verifying key is checked before the commit is marked as eligible for
165    /// public publication. This keeps private key material outside the repo
166    /// storage boundary while retaining the same signature and provenance
167    /// checks as [`Self::sign_atproto`].
168    pub fn from_atproto_signature(
169        unsigned: &UnsignedCommit,
170        signature: Vec<u8>,
171        verifying_key: &VerifyingKey,
172    ) -> Result<Self> {
173        use p256::ecdsa::signature::Verifier;
174        ensure!(
175            unsigned.version == COMMIT_VERSION,
176            "unsupported public commit version {} (expected {COMMIT_VERSION})",
177            unsigned.version
178        );
179        let parsed = Signature::from_slice(&signature)
180            .map_err(|error| anyhow!("invalid public ES256 signature bytes: {error}"))?;
181        verifying_key
182            .verify(&unsigned.to_atproto_dag_cbor()?, &parsed)
183            .map_err(|error| {
184                anyhow!("public ATProto ES256 signature verification failed: {error}")
185            })?;
186        let mut commit = Commit {
187            did: unsigned.did.clone(),
188            version: unsigned.version,
189            data: unsigned.data,
190            rev: unsigned.rev,
191            prev: unsigned.prev,
192            sig: signature,
193            atproto_signature: true,
194            atproto_canonical_bytes: None,
195        };
196        commit.atproto_canonical_bytes = Some(commit.to_atproto_dag_cbor()?);
197        Ok(commit)
198    }
199
200    /// DAG-CBOR encode the (signed) commit. The `sig` field is a byte string.
201    pub fn to_dag_cbor(&self) -> Vec<u8> {
202        self.to_value().encode()
203    }
204
205    /// Encode the signed commit using public AT Protocol canonical bytes.
206    pub fn to_atproto_dag_cbor(&self) -> Result<Vec<u8>> {
207        crate::atproto_cbor::encode(&self.to_value())
208    }
209
210    pub fn to_value(&self) -> DagCbor {
211        DagCbor::str_map([
212            ("did", DagCbor::Text(self.did.clone())),
213            ("version", DagCbor::Unsigned(self.version)),
214            ("data", DagCbor::Link(self.data)),
215            ("rev", DagCbor::Text(self.rev.encode())),
216            (
217                "prev",
218                match &self.prev {
219                    Some(c) => DagCbor::Link(*c),
220                    None => DagCbor::Null,
221                },
222            ),
223            ("sig", DagCbor::Bytes(self.sig.clone())),
224        ])
225    }
226
227    /// Classify this commit's account DID as an accepted repo authority for our
228    /// PDS (`did:web`/`did:plc`/`did:at9p`), or `Err` if the method is not one we
229    /// host a repo for.
230    ///
231    /// This is the method-level acceptance gate (#908); it is independent of and
232    /// additional to the signature check in [`Commit::verify`]. A caller ingesting
233    /// a commit should accept the authority *and* verify the signature.
234    pub fn repo_authority(&self) -> Result<crate::repo_authority::RepoAuthority> {
235        crate::repo_authority::accept_repo_authority(&self.did)
236    }
237
238    /// The [`UnsignedCommit`] form of this commit (drops `sig`).
239    pub fn unsigned(&self) -> UnsignedCommit {
240        UnsignedCommit {
241            did: self.did.clone(),
242            version: self.version,
243            data: self.data,
244            rev: self.rev,
245            prev: self.prev,
246        }
247    }
248
249    /// Decode a signed commit from DAG-CBOR bytes, validating structure.
250    pub fn from_dag_cbor(bytes: &[u8]) -> Result<Self> {
251        let value = DagCbor::decode(bytes)?;
252        Self::from_value(&value)
253    }
254
255    pub fn from_atproto_dag_cbor(bytes: &[u8]) -> Result<Self> {
256        let value = crate::atproto_cbor::decode(bytes)?;
257        Self::validate_atproto_fields(&value)?;
258        let commit = Self::from_value(&value)?;
259        // Public verification must bind the exact canonical block bytes. In
260        // particular, decoding and re-encoding the revision must preserve
261        // its exact text; no alternate field encoding may share verification.
262        ensure!(
263            commit.to_atproto_dag_cbor()?.as_slice() == bytes,
264            "public commit bytes are not canonical"
265        );
266        // Decoding canonical bytes proves only their shape and byte
267        // canonicality. It cannot prove that `sig` was produced over those
268        // bytes without the account's published verifying key, so decoded
269        // values remain untrusted until `verify_atproto_and_mark` succeeds.
270        Ok(commit)
271    }
272
273    fn validate_atproto_fields(value: &DagCbor) -> Result<()> {
274        const FIELDS: &[&str] = &["did", "version", "data", "rev", "prev", "sig"];
275        let fields = value.as_map()?;
276        ensure!(
277            fields.len() == FIELDS.len(),
278            "public commit must contain exactly these fields: {FIELDS:?}"
279        );
280        for (key, _) in fields {
281            let key = key.as_str()?;
282            ensure!(
283                FIELDS.contains(&key),
284                "public commit has unknown field {key:?}"
285            );
286        }
287        Ok(())
288    }
289
290    pub fn from_value(value: &DagCbor) -> Result<Self> {
291        let did = value
292            .get("did")
293            .ok_or_else(|| anyhow::anyhow!("commit missing 'did'"))?
294            .as_str()?
295            .to_owned();
296        let version = value
297            .get("version")
298            .ok_or_else(|| anyhow::anyhow!("commit missing 'version'"))?
299            .as_unsigned()?;
300        ensure!(
301            version == COMMIT_VERSION,
302            "unsupported commit version {version} (expected {COMMIT_VERSION})"
303        );
304        let data = *value
305            .get("data")
306            .ok_or_else(|| anyhow::anyhow!("commit missing 'data'"))?
307            .as_link()?;
308        let rev_str = value
309            .get("rev")
310            .ok_or_else(|| anyhow::anyhow!("commit missing 'rev'"))?
311            .as_str()?;
312        let rev = Tid::parse(rev_str)?;
313        let prev_val = value
314            .get("prev")
315            .ok_or_else(|| anyhow::anyhow!("commit missing 'prev'"))?;
316        let prev = if prev_val.is_null() {
317            None
318        } else {
319            Some(*prev_val.as_link()?)
320        };
321        let sig = value
322            .get("sig")
323            .ok_or_else(|| anyhow::anyhow!("commit missing 'sig'"))?
324            .as_bytes()?
325            .to_vec();
326        Ok(Commit {
327            did,
328            version,
329            data,
330            rev,
331            prev,
332            sig,
333            atproto_signature: false,
334            atproto_canonical_bytes: None,
335        })
336    }
337
338    pub(crate) fn ensure_atproto_signature(&self) -> Result<()> {
339        ensure!(
340            self.atproto_signature,
341            "public CAR publication requires a commit signed with AT Protocol canonical bytes"
342        );
343        ensure!(
344            self.version == COMMIT_VERSION,
345            "unsupported public commit version {} (expected {COMMIT_VERSION})",
346            self.version
347        );
348        let canonical = self
349            .atproto_canonical_bytes
350            .as_deref()
351            .ok_or_else(|| anyhow!("public signature provenance is missing canonical bytes"))?;
352        ensure!(
353            self.to_atproto_dag_cbor()?.as_slice() == canonical,
354            "public commit was mutated after its signature provenance was established"
355        );
356        Ok(())
357    }
358
359    /// Verify a decoded public commit with the account's published
360    /// `#atproto` key and mark the value eligible for public CAR publication.
361    ///
362    /// Canonical decoding alone is not signature provenance: a native commit
363    /// can be re-encoded into the public shape, and its bytes remain perfectly
364    /// canonical. This explicit key-bound verification is therefore required
365    /// before a decoded value crosses the public publication boundary.
366    pub fn verify_atproto_and_mark(mut self, vk: &VerifyingKey) -> Result<Self> {
367        self.verify_atproto(vk)?;
368        self.atproto_signature = true;
369        self.atproto_canonical_bytes = Some(self.to_atproto_dag_cbor()?);
370        Ok(self)
371    }
372
373    /// The CID of this (signed) commit block.
374    pub fn cid(&self) -> Cid {
375        Cid::from_dag_cbor(&self.to_dag_cbor())
376    }
377
378    pub fn cid_atproto(&self) -> Result<Cid> {
379        Ok(Cid::from_dag_cbor(&self.to_atproto_dag_cbor()?))
380    }
381
382    /// Verify the commit's signature against a `#atproto` P-256 verifying key.
383    ///
384    /// Re-encodes the unsigned commit, hashes with SHA-256, and verifies the
385    /// ES256 signature. Returns `Ok(())` on success.
386    ///
387    /// This is the core of the D5 untrusted-host posture: a host can serve any
388    /// commit it likes, but only commits signed by the account's `#atproto`
389    /// key are accepted by verifiers.
390    ///
391    /// For a rotated key set, use [`Commit::verify_against_published_keys`].
392    /// That path accepts only the active key and bounded, currently-live
393    /// `#atproto_drain` / `#atproto_lead` keys published in the DID document.
394    pub fn verify(&self, vk: &VerifyingKey) -> Result<()> {
395        use p256::ecdsa::signature::Verifier;
396        let unsigned = self.unsigned();
397        let unsigned_bytes = unsigned.to_dag_cbor();
398        // ES256 verification: parse the signature, then verify over the bytes.
399        // p256 0.13's `Signature::from_slice` accepts the 64-byte raw R‖V‖S form.
400        let signature = Signature::from_slice(&self.sig)
401            .map_err(|e| anyhow::anyhow!("invalid ES256 signature bytes: {e}"))?;
402        vk.verify(&unsigned_bytes, &signature)
403            .map_err(|e| anyhow::anyhow!("ES256 signature verification failed: {e}"))
404    }
405
406    pub fn verify_atproto(&self, vk: &VerifyingKey) -> Result<()> {
407        use p256::ecdsa::signature::Verifier;
408        ensure!(
409            self.version == COMMIT_VERSION,
410            "unsupported public commit version {} (expected {COMMIT_VERSION})",
411            self.version
412        );
413        let signature = Signature::from_slice(&self.sig)
414            .map_err(|e| anyhow::anyhow!("invalid ES256 signature bytes: {e}"))?;
415        vk.verify(&self.unsigned().to_atproto_dag_cbor()?, &signature)
416            .map_err(|e| anyhow::anyhow!("public ATProto ES256 signature verification failed: {e}"))
417    }
418
419    /// Verify against the bounded `#atproto` slot set currently published by a
420    /// DID document.  This is an overlap-availability mechanism: it accepts a
421    /// pre-rotation commit under the bounded drain key, but does not establish
422    /// that a key was valid at the commit's causal position (that is #1169).
423    pub fn verify_against_published_keys(
424        &self,
425        keys: &PublishedAtprotoKeys,
426        now: i64,
427    ) -> Result<()> {
428        let mut tried = 0usize;
429        let mut last_error = None;
430        for key in keys.live_keys(now) {
431            tried += 1;
432            match self.verify(key) {
433                Ok(()) => return Ok(()),
434                Err(error) => last_error = Some(error),
435            }
436        }
437        match last_error {
438            Some(error) => Err(error.context(format!(
439                "ES256 signature verified under none of the {tried} live published #atproto slot(s)"
440            ))),
441            None => bail!("no published #atproto verification slot is live at {now}"),
442        }
443    }
444
445    /// Compute the SHA-256 digest of the unsigned commit's DAG-CBOR bytes.
446    ///
447    /// Exposed for callers that compose their own signing/verification flow
448    /// (e.g. using the DID's key material from `hyprstream::auth::key_rotation`
449    /// directly). Standard ES256 signers hash internally, so most callers want
450    /// [`Commit::sign`] / [`Commit::verify`] instead.
451    pub fn unsigned_digest(unsigned: &UnsignedCommit) -> [u8; 32] {
452        Sha256::digest(unsigned.to_dag_cbor()).into()
453    }
454}
455
456/// The only auxiliary verification-method fragments understood by Hyprstream.
457/// Stock atproto implementations select the exact `#atproto` fragment, so the
458/// overlap keys deliberately use distinct fragments.
459const DRAIN_FRAGMENT: &str = "atproto_drain";
460const LEAD_FRAGMENT: &str = "atproto_lead";
461
462/// A P-256 key published for commit verification, with a half-open validity
463/// interval. The active slot is unbounded; drain and lead slots must carry
464/// explicit document bounds.
465#[derive(Clone, Debug)]
466pub struct PublishedAtprotoKey {
467    key: VerifyingKey,
468    nbf: i64,
469    exp: i64,
470}
471
472impl PublishedAtprotoKey {
473    fn active(key: VerifyingKey) -> Self {
474        Self {
475            key,
476            nbf: i64::MIN,
477            exp: i64::MAX,
478        }
479    }
480
481    fn bounded(key: VerifyingKey, nbf: i64, exp: i64) -> Result<Self> {
482        ensure!(
483            nbf < exp,
484            "published #atproto slot has an empty validity interval"
485        );
486        Ok(Self { key, nbf, exp })
487    }
488
489    fn is_live_at(&self, now: i64) -> bool {
490        self.nbf <= now && now < self.exp
491    }
492}
493
494/// A small, authority-checked set of verification keys from a DID document:
495/// exactly one active `#atproto` slot and at most one bounded drain and lead
496/// slot. Unknown DID verification methods are intentionally ignored.
497#[derive(Clone, Debug)]
498pub struct PublishedAtprotoKeys {
499    slots: Vec<PublishedAtprotoKey>,
500}
501
502impl PublishedAtprotoKeys {
503    pub const MAX_SLOTS: usize = 3;
504
505    /// Wrap a trusted single current key for existing resolver implementations.
506    pub fn single(key: VerifyingKey) -> Self {
507        Self {
508            slots: vec![PublishedAtprotoKey::active(key)],
509        }
510    }
511
512    /// Construct the same bounded authority that a root DID document publishes.
513    /// This is for local resolvers whose trusted publication source is the
514    /// rotation store that feeds that document; remote resolvers must parse the
515    /// resolved DID document with [`Self::from_did_document`].
516    pub fn from_published_slots(
517        active: VerifyingKey,
518        drain: Option<(VerifyingKey, i64, i64)>,
519        lead: Option<(VerifyingKey, i64, i64)>,
520    ) -> Result<Self> {
521        let mut slots = vec![PublishedAtprotoKey::active(active)];
522        if let Some((key, nbf, exp)) = drain {
523            slots.push(PublishedAtprotoKey::bounded(key, nbf, exp)?);
524        }
525        if let Some((key, nbf, exp)) = lead {
526            slots.push(PublishedAtprotoKey::bounded(key, nbf, exp)?);
527        }
528        Ok(Self { slots })
529    }
530
531    pub fn live_keys(&self, now: i64) -> impl Iterator<Item = &VerifyingKey> {
532        self.slots
533            .iter()
534            .filter(move |slot| slot.is_live_at(now))
535            .map(|slot| &slot.key)
536    }
537
538    pub fn len(&self) -> usize {
539        self.slots.len()
540    }
541
542    pub fn is_empty(&self) -> bool {
543        self.slots.is_empty()
544    }
545
546    /// Parse the active and bounded overlap slots from a resolved DID document.
547    /// Every recognised slot must have the expected full id, controller and
548    /// `Multikey` type; duplicates and malformed bounds fail closed.
549    pub fn from_did_document(doc: &serde_json::Value, expected_did: &str) -> Result<Self> {
550        let doc_id = doc
551            .get("id")
552            .and_then(serde_json::Value::as_str)
553            .ok_or_else(|| anyhow!("DID document has no `id`"))?;
554        ensure!(
555            doc_id == expected_did,
556            "DID document id {doc_id:?} does not match {expected_did:?}"
557        );
558        let vms = doc
559            .get("verificationMethod")
560            .and_then(serde_json::Value::as_array)
561            .ok_or_else(|| anyhow!("DID document has no verificationMethod array"))?;
562
563        let mut active = None;
564        let mut drain = None;
565        let mut lead = None;
566        for (fragment, destination, bounded) in [
567            ("atproto", &mut active, false),
568            (DRAIN_FRAGMENT, &mut drain, true),
569            (LEAD_FRAGMENT, &mut lead, true),
570        ] {
571            let full_id = format!("{expected_did}#{fragment}");
572            for vm in vms.iter().filter(|vm| {
573                vm.get("id").and_then(serde_json::Value::as_str) == Some(full_id.as_str())
574            }) {
575                ensure!(
576                    destination.is_none(),
577                    "DID document has more than one `{full_id}` method"
578                );
579                validate_vm_authority(vm, &full_id, expected_did)?;
580                let key = decode_p256_multibase_vm(vm, &format!("#{fragment}"))?;
581                *destination = Some(if bounded {
582                    let nbf = vm
583                        .get("nbf")
584                        .and_then(serde_json::Value::as_i64)
585                        .ok_or_else(|| anyhow!("`{full_id}` must carry integer `nbf`"))?;
586                    let exp = vm
587                        .get("exp")
588                        .and_then(serde_json::Value::as_i64)
589                        .ok_or_else(|| anyhow!("`{full_id}` must carry integer `exp`"))?;
590                    PublishedAtprotoKey::bounded(key, nbf, exp)?
591                } else {
592                    ensure!(
593                        vm.get("nbf").is_none() && vm.get("exp").is_none(),
594                        "`{full_id}` active slot must not carry `nbf`/`exp`"
595                    );
596                    PublishedAtprotoKey::active(key)
597                });
598            }
599        }
600        let active = active.ok_or_else(|| {
601            anyhow!("DID document has no `{expected_did}#atproto` verification method")
602        })?;
603        let mut slots = vec![active];
604        slots.extend(drain);
605        slots.extend(lead);
606        Ok(Self { slots })
607    }
608}
609
610/// Decode a `publicKeyMultibase` (multibase `z` + base58btc + multicodec
611/// `p256-pub` `0x80 0x24` + 33-byte compressed SEC1) into a P-256 verifying
612/// key, with the multicodec prefix checked.
613///
614/// `label` is the verification-method id suffix (`#atproto`)
615/// used in error messages; the caller already matched it.
616fn decode_p256_multibase_vm(vm: &serde_json::Value, label: &str) -> Result<VerifyingKey> {
617    const P256_PUB_MULTICODEC: [u8; 2] = [0x80, 0x24];
618    let mb = vm
619        .get("publicKeyMultibase")
620        .and_then(serde_json::Value::as_str)
621        .ok_or_else(|| anyhow!("{label} verification method has no publicKeyMultibase string"))?;
622    ensure!(
623        mb.starts_with('z'),
624        "{label} publicKeyMultibase must be multibase 'z' (base58btc)"
625    );
626    let payload = bs58::decode(&mb[1..])
627        .into_vec()
628        .map_err(|e| anyhow!("{label} publicKeyMultibase is not valid base58btc: {e}"))?;
629    ensure!(
630        payload.len() == 2 + 33,
631        "{label} publicKeyMultibase payload is {} bytes, expected 35 (multicodec + compressed SEC1)",
632        payload.len()
633    );
634    ensure!(
635        payload[0] == P256_PUB_MULTICODEC[0] && payload[1] == P256_PUB_MULTICODEC[1],
636        "{label} publicKeyMultibase has wrong multicodec prefix (not p256-pub 0x1200)"
637    );
638    VerifyingKey::from_sec1_bytes(&payload[2..])
639        .map_err(|e| anyhow!("{label} publicKeyMultibase SEC1 point invalid: {e}"))
640}
641
642/// Validate a `#atproto`-family verification method's authority: it MUST be
643/// `type: "Multikey"` and `controller: expected_did`. The id match (full
644/// `{did}#fragment`) is established by the caller; this checks the rest of the
645/// method so a method with the right id but a foreign controller/type is
646/// rejected (a document carrying an attacker VM with a spoofed id still fails
647/// closed on controller/type).
648fn validate_vm_authority(vm: &serde_json::Value, full_id: &str, expected_did: &str) -> Result<()> {
649    let vm_type = vm
650        .get("type")
651        .and_then(serde_json::Value::as_str)
652        .ok_or_else(|| anyhow!("`{full_id}` method has no `type`"))?;
653    ensure!(
654        vm_type == "Multikey",
655        "`{full_id}` method type is {vm_type:?}, expected \"Multikey\""
656    );
657    let controller = vm
658        .get("controller")
659        .and_then(serde_json::Value::as_str)
660        .ok_or_else(|| anyhow!("`{full_id}` method has no `controller`"))?;
661    ensure!(
662        controller == expected_did,
663        "`{full_id}` method controller is {controller:?}, expected {expected_did:?}"
664    );
665    Ok(())
666}
667
668/// Resolve the active `#atproto` P-256 verifying key for `expected_did`.
669///
670/// This compatibility helper intentionally ignores bounded overlap slots. Use
671/// [`PublishedAtprotoKeys::from_did_document`] for commit verification.
672pub fn atproto_verifying_key_from_did_document(
673    doc: &serde_json::Value,
674    expected_did: &str,
675) -> Result<VerifyingKey> {
676    PublishedAtprotoKeys::from_did_document(doc, expected_did)?
677        .slots
678        .first()
679        .map(|slot| slot.key)
680        .ok_or_else(|| anyhow!("DID document has no active #atproto verification key"))
681}
682
683#[cfg(test)]
684mod tests {
685    #![allow(
686        clippy::unwrap_used,
687        clippy::expect_used,
688        clippy::indexing_slicing,
689        clippy::panic
690    )]
691    use super::*;
692    use crate::record::{self, ModelRecord};
693    use crate::tid::Tid;
694    use std::collections::BTreeMap;
695
696    fn make_signed_commit() -> (Commit, VerifyingKey) {
697        // Build a small MST, sign a commit over its root.
698        let mut recs = BTreeMap::new();
699        for i in 0..3 {
700            let tid = Tid::from_micros(1_700_000_000_000_000 + i, i as u16);
701            let rec = ModelRecord::new(
702                "at://did:web:alice.example.com",
703                format!("bafyreiexampleoid{i:020}"),
704                "2026-06-23T12:34:56.789Z",
705            )
706            .expect("record");
707            recs.insert(tid, rec.cid());
708        }
709        let tree = crate::mst::Node::from_records(record::COLLECTION_NSID, &recs);
710        let root = tree.root_cid();
711
712        let signing_key = SigningKey::random(&mut rand::rngs::OsRng);
713        let verifying_key = VerifyingKey::from(&signing_key);
714
715        let unsigned = UnsignedCommit::new("did:web:alice.example.com", root, Tid::now(), None);
716        let commit = Commit::sign(&unsigned, &signing_key);
717        (commit, verifying_key)
718    }
719
720    #[test]
721    fn commit_sign_and_verify_round_trip() {
722        let (commit, vk) = make_signed_commit();
723        commit.verify(&vk).expect("signature must verify");
724    }
725
726    #[test]
727    fn commit_detects_wrong_key() {
728        let (commit, _vk) = make_signed_commit();
729        // A different key must fail.
730        let other = SigningKey::random(&mut rand::rngs::OsRng);
731        let other_vk = VerifyingKey::from(other);
732        assert!(
733            commit.verify(&other_vk).is_err(),
734            "signature must not verify under a different key"
735        );
736    }
737
738    #[test]
739    fn commit_detects_tampered_data() {
740        let (mut commit, vk) = make_signed_commit();
741        // Tamper with the MST root pointer — signature must fail.
742        commit.data = Cid::from_dag_cbor(b"tampered");
743        assert!(
744            commit.verify(&vk).is_err(),
745            "tampered data must fail signature verify"
746        );
747    }
748
749    #[test]
750    fn commit_dag_cbor_round_trip() {
751        let (commit, _vk) = make_signed_commit();
752        let bytes = commit.to_dag_cbor();
753        let back = Commit::from_dag_cbor(&bytes).expect("round-trip");
754        assert_eq!(commit, back);
755    }
756
757    #[test]
758    fn public_commit_rejects_unknown_fields() {
759        let (commit, _vk) = make_signed_commit();
760        let mut fields = commit.to_value().as_map().unwrap().to_vec();
761        fields.push((DagCbor::Text("extra".into()), DagCbor::Null));
762        let bytes = crate::atproto_cbor::encode(&DagCbor::Map(fields)).unwrap();
763        assert!(
764            Commit::from_atproto_dag_cbor(&bytes).is_err(),
765            "public commits must reject unknown fields"
766        );
767    }
768
769    #[test]
770    fn public_commit_preserves_odd_tid_revisions_and_rejects_changed_signature_input() {
771        let key = SigningKey::random(&mut rand::rngs::OsRng);
772        let unsigned = UnsignedCommit::new(
773            "did:web:alice.example.com",
774            Cid::from_dag_cbor(b"root"),
775            Tid::parse("3jzfcijpj2z2a").unwrap(),
776            None,
777        );
778        let commit = Commit::sign_atproto(&unsigned, &key).unwrap();
779        let mut fields = commit.to_value().as_map().unwrap().to_vec();
780        let rev = fields
781            .iter_mut()
782            .find(|(key, _)| matches!(key, DagCbor::Text(name) if name == "rev"))
783            .unwrap();
784        rev.1 = DagCbor::Text("3jzfcijpj2z2b".into());
785        let changed = crate::atproto_cbor::encode(&DagCbor::Map(fields.clone())).unwrap();
786        let decoded = Commit::from_atproto_dag_cbor(&changed).unwrap();
787        assert_eq!(decoded.rev.encode(), "3jzfcijpj2z2b");
788        assert_eq!(decoded.to_atproto_dag_cbor().unwrap(), changed);
789        assert!(decoded.verify_atproto(key.verifying_key()).is_err());
790        let signed_odd = Commit::sign_atproto(&decoded.unsigned(), &key).unwrap();
791        Commit::from_atproto_dag_cbor(&signed_odd.to_atproto_dag_cbor().unwrap())
792            .unwrap()
793            .verify_atproto(key.verifying_key())
794            .unwrap();
795        for invalid in ["kjzfcijpj2z2a", "3JZFCIJPJ2Z2B"] {
796            let mut fields = fields.clone();
797            fields
798                .iter_mut()
799                .find(|(key, _)| matches!(key, DagCbor::Text(name) if name == "rev"))
800                .unwrap()
801                .1 = DagCbor::Text(invalid.into());
802            assert!(Commit::from_atproto_dag_cbor(
803                &crate::atproto_cbor::encode(&DagCbor::Map(fields)).unwrap()
804            )
805            .is_err());
806        }
807    }
808
809    #[test]
810    fn decoded_public_commit_requires_explicit_signature_verification() {
811        let (native, native_vk) = make_signed_commit();
812        let public_signing = SigningKey::random(&mut rand::rngs::OsRng);
813        let public =
814            Commit::sign_atproto(&native.unsigned(), &public_signing).expect("public signature");
815        let bytes = public
816            .to_atproto_dag_cbor()
817            .expect("canonical public bytes");
818        let decoded = Commit::from_atproto_dag_cbor(&bytes).expect("canonical decode");
819        assert!(
820            decoded.ensure_atproto_signature().is_err(),
821            "canonical decoding must not establish signature provenance"
822        );
823        assert!(
824            decoded.clone().verify_atproto_and_mark(&native_vk).is_err(),
825            "verification with the wrong key must not mark the commit"
826        );
827        let verified = decoded
828            .verify_atproto_and_mark(public_signing.verifying_key())
829            .expect("published key verifies public commit");
830        verified
831            .ensure_atproto_signature()
832            .expect("verified public commit is publishable");
833    }
834
835    #[test]
836    fn commit_unsigned_has_no_sig_field() {
837        // The unsigned encoding MUST NOT carry a sig field (atproto signs the
838        // object without sig, not sig=empty).
839        let unsigned = UnsignedCommit::new(
840            "did:web:x",
841            Cid::from_dag_cbor(b"r"),
842            Tid::from_raw(1),
843            None,
844        );
845        let v = unsigned.to_value();
846        assert!(
847            v.get("sig").is_none(),
848            "unsigned commit must not have a sig field"
849        );
850    }
851
852    // ── #918: single-key DID-document verification (re-sign-on-rotation) ──────
853
854    /// Helper: encode a P-256 verifying key as the multibase string the DID
855    /// document producer emits (mirrors `did_document::p256_to_multibase`).
856    fn p256_to_multibase(vk: &VerifyingKey) -> String {
857        use p256::EncodedPoint;
858        let point: EncodedPoint = vk.to_encoded_point(true);
859        let mut payload = vec![0x80, 0x24];
860        payload.extend_from_slice(point.as_bytes());
861        format!("z{}", bs58::encode(payload).into_string())
862    }
863
864    fn did_doc_with_atproto(did: &str, vk: &VerifyingKey) -> serde_json::Value {
865        serde_json::json!({
866            "id": did,
867            "verificationMethod": [{
868                "id": format!("{did}#atproto"),
869                "type": "Multikey",
870                "controller": did,
871                "publicKeyMultibase": p256_to_multibase(vk),
872            }],
873        })
874    }
875
876    fn did_doc_with_overlap(
877        did: &str,
878        active: &VerifyingKey,
879        drain: Option<(&VerifyingKey, i64, i64)>,
880        lead: Option<(&VerifyingKey, i64, i64)>,
881    ) -> serde_json::Value {
882        let mut methods = vec![serde_json::json!({
883            "id": format!("{did}#atproto"),
884            "type": "Multikey",
885            "controller": did,
886            "publicKeyMultibase": p256_to_multibase(active),
887        })];
888        for (fragment, slot) in [(DRAIN_FRAGMENT, drain), (LEAD_FRAGMENT, lead)] {
889            if let Some((key, nbf, exp)) = slot {
890                methods.push(serde_json::json!({
891                    "id": format!("{did}#{fragment}"),
892                    "type": "Multikey",
893                    "controller": did,
894                    "publicKeyMultibase": p256_to_multibase(key),
895                    "nbf": nbf,
896                    "exp": exp,
897                }));
898            }
899        }
900        serde_json::json!({ "id": did, "verificationMethod": methods })
901    }
902
903    #[test]
904    fn pre_rotation_commit_verifies_during_bounded_drain_overlap() {
905        let (commit, old_key) = make_signed_commit();
906        let active = VerifyingKey::from(SigningKey::random(&mut rand::rngs::OsRng));
907        let doc = did_doc_with_overlap(
908            "did:web:alice.example.com",
909            &active,
910            Some((&old_key, 10, 20)),
911            None,
912        );
913        let keys = PublishedAtprotoKeys::from_did_document(&doc, "did:web:alice.example.com")
914            .expect("bounded drain document parses");
915        commit
916            .verify_against_published_keys(&keys, 15)
917            .expect("commit signed before rotation verifies during drain overlap");
918    }
919
920    #[test]
921    fn key_that_left_document_cannot_verify() {
922        let (commit, old_key) = make_signed_commit();
923        let active = VerifyingKey::from(SigningKey::random(&mut rand::rngs::OsRng));
924        let doc = did_doc_with_overlap("did:web:alice.example.com", &active, None, None);
925        let keys = PublishedAtprotoKeys::from_did_document(&doc, "did:web:alice.example.com")
926            .expect("active-only document parses");
927        assert!(
928            commit.verify_against_published_keys(&keys, 15).is_err(),
929            "a key absent from the published document must not verify"
930        );
931        let _ = old_key;
932    }
933
934    #[test]
935    fn overlap_slot_expires_and_is_not_consulted() {
936        let (commit, old_key) = make_signed_commit();
937        let active = VerifyingKey::from(SigningKey::random(&mut rand::rngs::OsRng));
938        let doc = did_doc_with_overlap(
939            "did:web:alice.example.com",
940            &active,
941            Some((&old_key, 10, 20)),
942            None,
943        );
944        let keys = PublishedAtprotoKeys::from_did_document(&doc, "did:web:alice.example.com")
945            .expect("bounded drain document parses");
946        assert!(
947            commit.verify_against_published_keys(&keys, 20).is_err(),
948            "drain key must not be consulted at its exclusive expiry boundary"
949        );
950    }
951
952    #[test]
953    fn currently_published_lead_key_is_accepted_for_verification_only() {
954        let lead_signing_key = SigningKey::random(&mut rand::rngs::OsRng);
955        let lead = VerifyingKey::from(&lead_signing_key);
956        let unsigned = UnsignedCommit::new(
957            "did:web:alice.example.com",
958            Cid::from_dag_cbor(b"lead-window"),
959            Tid::from_raw(42),
960            None,
961        );
962        let commit = Commit::sign(&unsigned, &lead_signing_key);
963        let active = VerifyingKey::from(SigningKey::random(&mut rand::rngs::OsRng));
964        let doc = did_doc_with_overlap(
965            "did:web:alice.example.com",
966            &active,
967            None,
968            Some((&lead, 10, 20)),
969        );
970        let keys = PublishedAtprotoKeys::from_did_document(&doc, "did:web:alice.example.com")
971            .expect("bounded lead document parses");
972        commit
973            .verify_against_published_keys(&keys, 15)
974            .expect("a currently-published lead key is a verification slot");
975    }
976
977    /// Resolve the single `#atproto` key from a document, then verify a commit
978    /// signed by that key passes and a forged (different-key) commit fails.
979    #[test]
980    fn atproto_key_from_did_document_verifies_head() {
981        let (commit, vk) = make_signed_commit();
982        let did = "did:web:alice.example.com";
983        let resolved =
984            atproto_verifying_key_from_did_document(&did_doc_with_atproto(did, &vk), did)
985                .expect("resolve #atproto key");
986        assert_eq!(resolved.to_sec1_bytes(), vk.to_sec1_bytes());
987        // Head signed by the resolved key verifies.
988        commit
989            .verify(&resolved)
990            .expect("head verifies under current #atproto");
991        // A head signed by a DIFFERENT key does not verify against this doc's key.
992        let (other_commit, _other_vk) = make_signed_commit();
993        assert!(
994            other_commit.verify(&resolved).is_err(),
995            "a commit signed by a different key must fail single-key verification"
996        );
997    }
998
999    /// The re-sign contract: a head still signed by the OLD key (not re-signed
1000    /// after rotation) does NOT verify against the current document (=new key).
1001    /// This is both directions of the #918 re-sign-on-rotation design.
1002    #[test]
1003    fn old_key_head_does_not_verify_against_rotated_doc() {
1004        let (old_commit, old_vk) = make_signed_commit();
1005        let new_vk = VerifyingKey::from(&SigningKey::random(&mut rand::rngs::OsRng));
1006        let did = "did:web:alice.example.com";
1007        // Current document publishes the NEW key (post-rotation).
1008        let resolved =
1009            atproto_verifying_key_from_did_document(&did_doc_with_atproto(did, &new_vk), did)
1010                .expect("resolve");
1011        // The head (still signed by the old key) fails — the producer's re-sign
1012        // is what would make it pass; without re-sign, verification correctly fails.
1013        assert!(
1014            old_commit.verify(&resolved).is_err(),
1015            "a head not re-signed after rotation must fail against the rotated-in key"
1016        );
1017        let _ = old_vk;
1018    }
1019
1020    /// Authority hygiene: a document whose `id` is for a different DID fails.
1021    #[test]
1022    fn atproto_key_rejects_wrong_did() {
1023        let (_c, vk) = make_signed_commit();
1024        let doc = did_doc_with_atproto("did:web:alice.example.com", &vk);
1025        assert!(
1026            atproto_verifying_key_from_did_document(&doc, "did:web:bob.example.com").is_err(),
1027            "a document for a different DID must fail closed"
1028        );
1029    }
1030
1031    /// Authority hygiene: a wrong controller / type is rejected.
1032    #[test]
1033    fn atproto_key_rejects_wrong_controller() {
1034        let (_c, vk) = make_signed_commit();
1035        let did = "did:web:alice.example.com";
1036        let doc = serde_json::json!({
1037            "id": did,
1038            "verificationMethod": [{
1039                "id": format!("{did}#atproto"),
1040                "type": "Multikey",
1041                "controller": "did:web:mallory.example.com",
1042                "publicKeyMultibase": p256_to_multibase(&vk),
1043            }],
1044        });
1045        assert!(
1046            atproto_verifying_key_from_did_document(&doc, did).is_err(),
1047            "a #atproto method with a foreign controller must fail closed"
1048        );
1049    }
1050
1051    /// Authority hygiene: duplicate `#atproto` methods are rejected.
1052    #[test]
1053    fn atproto_key_rejects_duplicate_method() {
1054        let (_c, vk) = make_signed_commit();
1055        let did = "did:web:alice.example.com";
1056        let vm = serde_json::json!({
1057            "id": format!("{did}#atproto"), "type": "Multikey",
1058            "controller": did, "publicKeyMultibase": p256_to_multibase(&vk),
1059        });
1060        let doc = serde_json::json!({ "id": did, "verificationMethod": [vm.clone(), vm] });
1061        let err = atproto_verifying_key_from_did_document(&doc, did)
1062            .expect_err("duplicate #atproto must fail closed");
1063        assert!(
1064            format!("{err}").contains("more than one"),
1065            "duplicate-method error should be explicit, got: {err}"
1066        );
1067    }
1068
1069    /// Authority hygiene: a wrong `type` (not "Multikey") is rejected.
1070    #[test]
1071    fn atproto_key_rejects_wrong_type() {
1072        let (_c, vk) = make_signed_commit();
1073        let did = "did:web:alice.example.com";
1074        let doc = serde_json::json!({
1075            "id": did,
1076            "verificationMethod": [{
1077                "id": format!("{did}#atproto"),
1078                "type": "JsonWebKey2020",
1079                "controller": did,
1080                "publicKeyMultibase": p256_to_multibase(&vk),
1081            }],
1082        });
1083        assert!(
1084            atproto_verifying_key_from_did_document(&doc, did).is_err(),
1085            "a #atproto method with the wrong type must fail closed"
1086        );
1087    }
1088}