Skip to main content

hyprstream_pds/
hosted_account.rs

1//! Hosted-account record and mint state machine.
2//!
3//! The mint path is intentionally split around the user signature:
4//!
5//! 1. [`HostedAccountMint::begin`] consumes an already-allocated account name
6//!    and generates a fresh per-account ES256 `#atproto` key.
7//! 2. [`HostedAccountMint::seal_did_document`] builds the canonical DID
8//!    document (B2/#1164) from that generated key, and
9//!    [`HostedAccountMint::prepare_genesis`] binds the sealed artifact.
10//! 3. The user signs [`PendingHostedAccountMint::signing_bytes`] with the
11//!    required priority-zero Hybrid rotation key.
12//! 4. [`PendingHostedAccountMint::seal`] verifies that signature before it can
13//!    produce an [`AccountRecord`].
14//!
15//! A host never receives the user's rotation private key. The generated ES256
16//! private key is returned separately from the public account record so a
17//! caller can place it in the deployment's secret store; it is never serialized
18//! into the record or genesis operation.
19//!
20//! A2 (#1160) owns label allocation and never-reuse. A3 (#1162) owns deriving
21//! the host from the configured deployment zone. This module consumes the
22//! narrow seam between them as [`AllocatedAccountName`] and independently
23//! revalidates the permanent host-form DID before signing anything.
24
25use std::collections::BTreeSet;
26use std::fs::{File, OpenOptions};
27use std::io::Write as _;
28use std::path::{Path, PathBuf};
29
30use anyhow::{bail, ensure, Context, Result};
31use p256::ecdsa::{SigningKey as AtprotoSigningKey, VerifyingKey as AtprotoVerifyingKey};
32use rand::rngs::OsRng;
33
34use crate::cid::Cid;
35use crate::dag_cbor::DagCbor;
36use crate::did_op::{
37    validate_host_form_did_web, DidOpSignature, GenesisDidOp, GenesisRepoHead, GenesisRotationKeys,
38    UnsignedGenesisDidOp,
39};
40use crate::hosted_did_document::SealedHostedDidDocument;
41use crate::AccountLabel;
42use hyprstream_rpc::identity::UNAUTHENTICATED_DID_SENTINEL;
43
44/// Version of the durable hosted-account record.
45pub const ACCOUNT_RECORD_VERSION: u16 = 1;
46const COMPRESSED_P256_PUBLIC_KEY_LEN: usize = 33;
47const ACCOUNT_RECORD_FILE: &str = "account-record.cbor";
48pub const GENESIS_DID_OP_FILE: &str = "genesis.didop.cbor";
49pub const DID_DOCUMENT_FILE: &str = "did-document.json";
50const ACCOUNT_STAGING_MARKER: &str = ".mint-";
51
52/// Return whether `name` is an unpublished account-mint staging directory.
53///
54/// The writer uses this exact private name shape while assembling a complete
55/// account bundle: `.{label}.mint-{random_u128}-{attempt}`. A crash can leave
56/// one of these directories behind, so readers may ignore only names that
57/// match the complete documented shape and contain a valid permanent label.
58pub fn is_hosted_account_staging_directory(name: &str) -> bool {
59    let Some(name) = name.strip_prefix('.') else {
60        return false;
61    };
62    let Some((label, suffix)) = name.split_once(ACCOUNT_STAGING_MARKER) else {
63        return false;
64    };
65    if AccountLabel::parse(label).is_err() {
66        return false;
67    }
68    let Some((random_text, attempt_text)) = suffix.rsplit_once('-') else {
69        return false;
70    };
71    let Ok(random) = random_text.parse::<u128>() else {
72        return false;
73    };
74    let Ok(attempt) = attempt_text.parse::<u32>() else {
75        return false;
76    };
77    // Keep this in lockstep with new_staging_directory's bounded retry loop.
78    random.to_string() == random_text && attempt.to_string() == attempt_text && attempt < 128
79}
80
81/// Secret account-specific P-256 key paired with the public `#atproto`
82/// verification method in the immutable account record and DID document.
83///
84/// Serving layers must never return this file. They may use it only after
85/// binding the caller to the exact hosted DID and re-checking that its public
86/// key matches the account record.
87pub const ATPROTO_SIGNING_KEY_FILE: &str = "atproto-signing-key";
88
89/// The output of the A2 allocation + A3 configured-zone seam.
90///
91/// Construction is strict but cannot itself prove never-reuse; the A2 allocator
92/// must only produce this value after atomically reserving the label forever.
93#[derive(Clone, Debug, Eq, PartialEq)]
94pub struct AllocatedAccountName {
95    label: String,
96    did: String,
97}
98
99impl AllocatedAccountName {
100    pub fn new(label: impl Into<String>, did: impl Into<String>) -> Result<Self> {
101        let name = Self {
102            label: label.into(),
103            did: did.into(),
104        };
105        name.validate()?;
106        Ok(name)
107    }
108
109    pub fn label(&self) -> &str {
110        &self.label
111    }
112
113    pub fn did(&self) -> &str {
114        &self.did
115    }
116
117    fn validate(&self) -> Result<()> {
118        ensure!(
119            self.did != UNAUTHENTICATED_DID_SENTINEL,
120            "{UNAUTHENTICATED_DID_SENTINEL} is reserved for the unauthenticated floor and cannot be registered or minted"
121        );
122        AccountLabel::parse(&self.label).context("allocated account label is invalid")?;
123        validate_host_form_did_web(&self.did)?;
124        let host = self
125            .did
126            .strip_prefix("did:web:")
127            .ok_or_else(|| anyhow::anyhow!("hosted account DID must use did:web"))?;
128        ensure!(
129            host.split('.').next() == Some(self.label.as_str()),
130            "allocated account label does not match the first label of its did:web host"
131        );
132        Ok(())
133    }
134}
135
136/// The public durable record locating a hosted account's permanent genesis.
137#[derive(Clone, Debug, Eq, PartialEq)]
138pub struct AccountRecord {
139    name: AllocatedAccountName,
140    atproto_key: Vec<u8>,
141    genesis_op: Cid,
142    current_op: Cid,
143    doc_cid: Cid,
144}
145
146impl AccountRecord {
147    fn new(
148        name: AllocatedAccountName,
149        atproto_key: Vec<u8>,
150        genesis_op: Cid,
151        doc_cid: Cid,
152    ) -> Result<Self> {
153        let record = Self {
154            name,
155            atproto_key,
156            genesis_op,
157            current_op: genesis_op,
158            doc_cid,
159        };
160        record.validate()?;
161        Ok(record)
162    }
163
164    pub fn version(&self) -> u16 {
165        ACCOUNT_RECORD_VERSION
166    }
167
168    pub fn name(&self) -> &AllocatedAccountName {
169        &self.name
170    }
171
172    pub fn atproto_key_bytes(&self) -> &[u8] {
173        &self.atproto_key
174    }
175
176    pub fn genesis_op(&self) -> Cid {
177        self.genesis_op
178    }
179
180    pub fn current_op(&self) -> Cid {
181        self.current_op
182    }
183
184    pub fn doc_cid(&self) -> Cid {
185        self.doc_cid
186    }
187
188    pub fn atproto_verifying_key(&self) -> Result<AtprotoVerifyingKey> {
189        AtprotoVerifyingKey::from_sec1_bytes(&self.atproto_key)
190            .context("account record contains an invalid #atproto P-256 key")
191    }
192
193    pub fn to_dag_cbor(&self) -> Result<Vec<u8>> {
194        self.validate()?;
195        Ok(self.to_value().encode())
196    }
197
198    pub fn from_dag_cbor(bytes: &[u8]) -> Result<Self> {
199        let value = DagCbor::decode(bytes)?;
200        reject_unknown(
201            &value,
202            &[
203                "version",
204                "label",
205                "did",
206                "atproto_key",
207                "genesis_op",
208                "current_op",
209                "doc_cid",
210            ],
211            "account record",
212        )?;
213        let version = required(&value, "version", "account record")?.as_unsigned()?;
214        ensure!(
215            version == u64::from(ACCOUNT_RECORD_VERSION),
216            "unsupported account record version {version}"
217        );
218        let record = Self {
219            name: AllocatedAccountName::new(
220                required(&value, "label", "account record")?
221                    .as_str()?
222                    .to_owned(),
223                required(&value, "did", "account record")?
224                    .as_str()?
225                    .to_owned(),
226            )?,
227            atproto_key: required(&value, "atproto_key", "account record")?
228                .as_bytes()?
229                .to_vec(),
230            genesis_op: *required(&value, "genesis_op", "account record")?.as_link()?,
231            current_op: *required(&value, "current_op", "account record")?.as_link()?,
232            doc_cid: *required(&value, "doc_cid", "account record")?.as_link()?,
233        };
234        record.validate()?;
235        ensure!(
236            record.to_dag_cbor()? == bytes,
237            "account record is not canonical DAG-CBOR"
238        );
239        Ok(record)
240    }
241
242    fn validate(&self) -> Result<()> {
243        self.name.validate()?;
244        ensure!(
245            self.atproto_key.len() == COMPRESSED_P256_PUBLIC_KEY_LEN,
246            "account #atproto key must be a {COMPRESSED_P256_PUBLIC_KEY_LEN}-byte compressed P-256 point"
247        );
248        self.atproto_verifying_key()?;
249        Ok(())
250    }
251
252    fn to_value(&self) -> DagCbor {
253        DagCbor::str_map([
254            ("atproto_key", DagCbor::Bytes(self.atproto_key.clone())),
255            ("current_op", DagCbor::Link(self.current_op)),
256            ("did", DagCbor::Text(self.name.did.clone())),
257            ("doc_cid", DagCbor::Link(self.doc_cid)),
258            ("genesis_op", DagCbor::Link(self.genesis_op)),
259            ("label", DagCbor::Text(self.name.label.clone())),
260            (
261                "version",
262                DagCbor::Unsigned(u64::from(ACCOUNT_RECORD_VERSION)),
263            ),
264        ])
265    }
266}
267
268/// Mint state after label allocation and per-account ES256 generation.
269///
270/// This type is deliberately neither `Clone` nor `Debug`: it owns secret key
271/// material.
272pub struct HostedAccountMint {
273    name: AllocatedAccountName,
274    rotations: GenesisRotationKeys,
275    atproto_signing_key: AtprotoSigningKey,
276}
277
278impl HostedAccountMint {
279    /// Begin minting. A user-held priority-zero key is mandatory in
280    /// `rotations`; there is no overload that omits it.
281    pub fn begin(name: AllocatedAccountName, rotations: GenesisRotationKeys) -> Result<Self> {
282        name.validate()?;
283        // Reconstructing from canonical bytes re-applies every slot invariant
284        // even if this crate later gains internal mutation helpers.
285        let rotations = GenesisRotationKeys::new(
286            rotations.user().clone(),
287            rotations.recovery().clone(),
288            rotations.host().clone(),
289        )?;
290        Ok(Self {
291            name,
292            rotations,
293            atproto_signing_key: AtprotoSigningKey::random(&mut OsRng),
294        })
295    }
296
297    /// The generated account-specific `#atproto` key used by B2 to build the
298    /// canonical DID document before genesis is signed.
299    pub fn atproto_verifying_key(&self) -> AtprotoVerifyingKey {
300        *self.atproto_signing_key.verifying_key()
301    }
302
303    /// Build the canonical DID document from this mint's DID and generated
304    /// account-specific `#atproto` key.
305    pub fn seal_did_document(&self, pds_endpoint: &str) -> Result<SealedHostedDidDocument> {
306        SealedHostedDidDocument::seal(
307            &self.name,
308            self.atproto_signing_key.verifying_key(),
309            pds_endpoint,
310        )
311    }
312
313    /// Bind the sealed DID document and deliberate genesis repo-head state.
314    ///
315    /// Accepting the artifact instead of a free-form CID makes DID/key
316    /// substitution unrepresentable at this boundary.
317    pub fn prepare_genesis(
318        self,
319        did_document: SealedHostedDidDocument,
320        head_at_op: GenesisRepoHead,
321    ) -> Result<PendingHostedAccountMint> {
322        ensure!(
323            did_document.did() == self.name.did(),
324            "sealed DID document names a different hosted account"
325        );
326        ensure!(
327            did_document.atproto_verifying_key()?.to_encoded_point(true)
328                == self
329                    .atproto_signing_key
330                    .verifying_key()
331                    .to_encoded_point(true),
332            "sealed DID document contains a different #atproto key"
333        );
334        let unsigned = UnsignedGenesisDidOp::new(
335            self.name.did.clone(),
336            did_document.cid(),
337            self.rotations,
338            head_at_op,
339        )?;
340        Ok(PendingHostedAccountMint {
341            name: self.name,
342            atproto_signing_key: self.atproto_signing_key,
343            did_document,
344            unsigned,
345        })
346    }
347
348    /// Create and sign the account's empty initial repo, then bind that commit
349    /// CID into the hosted DID's genesis operation.
350    ///
351    /// The generated `#atproto` key never crosses this boundary: it signs the
352    /// repo commit in place and remains owned by the pending account mint.
353    pub fn prepare_pds_genesis(
354        self,
355        did_document: SealedHostedDidDocument,
356        rev: crate::tid::Tid,
357    ) -> Result<(
358        PendingHostedAccountMint,
359        crate::hosted_repo::HostedRepoGenesis,
360    )> {
361        let repo = crate::hosted_repo::HostedRepoGenesis::seal(
362            self.name.did(),
363            &self.atproto_signing_key,
364            rev,
365        )?;
366        let pending =
367            self.prepare_genesis(did_document, GenesisRepoHead::Existing(repo.commit_cid()))?;
368        Ok((pending, repo))
369    }
370}
371
372/// Mint state waiting for the user-held priority-zero signature.
373///
374/// No [`AccountRecord`] exists yet.
375pub struct PendingHostedAccountMint {
376    name: AllocatedAccountName,
377    atproto_signing_key: AtprotoSigningKey,
378    did_document: SealedHostedDidDocument,
379    unsigned: UnsignedGenesisDidOp,
380}
381
382impl PendingHostedAccountMint {
383    pub fn unsigned_genesis(&self) -> &UnsignedGenesisDidOp {
384        &self.unsigned
385    }
386
387    /// Exact canonical bytes the user's Hybrid signer must sign.
388    pub fn signing_bytes(&self) -> Result<Vec<u8>> {
389        self.unsigned.to_dag_cbor()
390    }
391
392    /// Verify the user signature and produce the sealed account artifacts.
393    ///
394    /// Invalid, host-signed, classical-only, or tampered signatures fail before
395    /// an account record is constructed.
396    pub fn seal(self, signature: DidOpSignature) -> Result<SealedHostedAccount> {
397        let genesis = GenesisDidOp::seal(self.unsigned, signature)?;
398        let genesis_bytes = genesis.to_dag_cbor()?;
399        let genesis_cid = Cid::from_dag_cbor(&genesis_bytes);
400        let atproto_key = self
401            .atproto_signing_key
402            .verifying_key()
403            .to_encoded_point(true)
404            .as_bytes()
405            .to_vec();
406        let record = AccountRecord::new(
407            self.name,
408            atproto_key,
409            genesis_cid,
410            genesis.unsigned().doc_cid(),
411        )?;
412        let record_bytes = record.to_dag_cbor()?;
413        Ok(SealedHostedAccount {
414            record,
415            record_bytes,
416            genesis,
417            genesis_bytes,
418            did_document: self.did_document,
419            atproto_signing_key: self.atproto_signing_key,
420        })
421    }
422}
423
424/// Fully sealed account artifacts ready for an atomic persistence boundary.
425///
426/// The secret ES256 key is separate from both byte vectors. Persistence is a
427/// caller-owned seam because the deployment decides its secret store and B2
428/// decides its CAS; this type ensures those writers receive one coherent,
429/// already-verified generation.
430pub struct SealedHostedAccount {
431    record: AccountRecord,
432    record_bytes: Vec<u8>,
433    genesis: GenesisDidOp,
434    genesis_bytes: Vec<u8>,
435    did_document: SealedHostedDidDocument,
436    atproto_signing_key: AtprotoSigningKey,
437}
438
439impl SealedHostedAccount {
440    pub fn record(&self) -> &AccountRecord {
441        &self.record
442    }
443
444    pub fn record_bytes(&self) -> &[u8] {
445        &self.record_bytes
446    }
447
448    pub fn genesis(&self) -> &GenesisDidOp {
449        &self.genesis
450    }
451
452    pub fn genesis_bytes(&self) -> &[u8] {
453        &self.genesis_bytes
454    }
455
456    pub fn did_document(&self) -> &SealedHostedDidDocument {
457        &self.did_document
458    }
459
460    pub fn atproto_signing_key(&self) -> &AtprotoSigningKey {
461        &self.atproto_signing_key
462    }
463
464    /// Consume the bundle for a persistence implementation.
465    pub fn into_parts(
466        self,
467    ) -> (
468        AccountRecord,
469        Vec<u8>,
470        GenesisDidOp,
471        Vec<u8>,
472        SealedHostedDidDocument,
473        AtprotoSigningKey,
474    ) {
475        (
476            self.record,
477            self.record_bytes,
478            self.genesis,
479            self.genesis_bytes,
480            self.did_document,
481            self.atproto_signing_key,
482        )
483    }
484
485    /// Persist this mint generation and return its public account record.
486    ///
487    /// Retaining the bundle permits a retry after a crash or I/O error. The
488    /// sealed record fixes its label, so it cannot be redirected to another
489    /// account location.
490    pub fn write_to(&self, store: &DirectoryHostedAccountStore) -> Result<AccountRecord> {
491        store.write_new(self)?;
492        Ok(self.record.clone())
493    }
494}
495
496/// Fail-closed filesystem persistence for newly minted hosted accounts.
497///
498/// Each allocated label gets one directory beneath `root`. Files are first
499/// written and synced in an unpublished private staging directory, then that
500/// complete directory is atomically published without replacement. Files are
501/// written in this order:
502///
503/// 1. the generated `#atproto` private key;
504/// 2. the sealed canonical DID document;
505/// 3. the sealed genesis operation;
506/// 4. the public account record, **last**, as the publication marker.
507///
508/// A crash before publication leaves no label directory. A crash after
509/// publication leaves the complete account. A retry removes only an invalid or
510/// incomplete legacy residue; it never replaces a complete account.
511/// C2 (#1168) owns later crash-atomic *rotation*; this writer only establishes
512/// the immutable first generation.
513#[derive(Clone, Debug)]
514pub struct DirectoryHostedAccountStore {
515    root: PathBuf,
516    #[cfg(test)]
517    fault: Option<WriteFault>,
518}
519
520impl DirectoryHostedAccountStore {
521    /// Configure the caller-selected durable account root.
522    ///
523    /// There is intentionally no default path.
524    pub fn new(root: impl Into<PathBuf>) -> Self {
525        Self {
526            root: root.into(),
527            #[cfg(test)]
528            fault: None,
529        }
530    }
531
532    pub fn root(&self) -> &Path {
533        &self.root
534    }
535
536    /// Location of an account record after a successful mint.
537    pub fn account_record_path(&self, label: &str) -> PathBuf {
538        self.root.join(label).join(ACCOUNT_RECORD_FILE)
539    }
540
541    fn write_new(&self, account: &SealedHostedAccount) -> Result<()> {
542        validate_sealed_bundle(account)?;
543        ensure_private_directory(&self.root)?;
544        let account_dir = self.root.join(account.record.name().label());
545        if complete_account_matches(&account_dir, account)? {
546            return Ok(());
547        }
548        remove_incomplete_account_directory(&account_dir)?;
549
550        let staging_dir = self.new_staging_directory(account.record.name().label())?;
551        self.inject_fault(WriteFault::StagingDirectoryCreate)?;
552
553        self.write_new_file(
554            &staging_dir.join(ATPROTO_SIGNING_KEY_FILE),
555            account.atproto_signing_key.to_bytes().as_slice(),
556            WriteFault::AtprotoFileCreate,
557            WriteFault::AtprotoFileWrite,
558            WriteFault::AtprotoFileSync,
559        )?;
560        self.write_new_file(
561            &staging_dir.join(DID_DOCUMENT_FILE),
562            account.did_document.as_bytes(),
563            WriteFault::DidDocumentFileCreate,
564            WriteFault::DidDocumentFileWrite,
565            WriteFault::DidDocumentFileSync,
566        )?;
567        self.write_new_file(
568            &staging_dir.join(GENESIS_DID_OP_FILE),
569            &account.genesis_bytes,
570            WriteFault::GenesisFileCreate,
571            WriteFault::GenesisFileWrite,
572            WriteFault::GenesisFileSync,
573        )?;
574        self.write_new_file(
575            &staging_dir.join(ACCOUNT_RECORD_FILE),
576            &account.record_bytes,
577            WriteFault::RecordFileCreate,
578            WriteFault::RecordFileWrite,
579            WriteFault::RecordFileSync,
580        )?;
581        sync_directory(&staging_dir)?;
582        self.inject_fault(WriteFault::StagingDirectorySync)?;
583
584        match rename_no_replace(&staging_dir, &account_dir) {
585            Ok(()) => {}
586            Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
587                if complete_account_matches(&account_dir, account)? {
588                    return Ok(());
589                }
590                bail!(
591                    "hosted-account label directory {:?} was concurrently claimed by an incomplete account",
592                    account_dir
593                );
594            }
595            Err(error) => {
596                return Err(error).with_context(|| {
597                    format!(
598                        "failed to atomically publish hosted-account label directory {:?}",
599                        account_dir
600                    )
601                });
602            }
603        }
604        self.inject_fault(WriteFault::Publish)?;
605        sync_directory(&self.root)?;
606        self.inject_fault(WriteFault::RootDirectorySync)?;
607        Ok(())
608    }
609
610    fn new_staging_directory(&self, label: &str) -> Result<PathBuf> {
611        for attempt in 0_u32..128 {
612            let staging = self.root.join(format!(
613                ".{label}.mint-{}-{attempt}",
614                rand::random::<u128>()
615            ));
616            match std::fs::create_dir(&staging) {
617                Ok(()) => {
618                    set_private_directory_permissions(&staging)?;
619                    return Ok(staging);
620                }
621                Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
622                Err(error) => {
623                    return Err(error).with_context(|| {
624                        format!("failed to create hosted-account staging directory {staging:?}")
625                    });
626                }
627            }
628        }
629        bail!("could not allocate a unique hosted-account staging directory")
630    }
631
632    fn write_new_file(
633        &self,
634        path: &Path,
635        bytes: &[u8],
636        create_fault: WriteFault,
637        write_fault: WriteFault,
638        sync_fault: WriteFault,
639    ) -> Result<()> {
640        let mut options = OpenOptions::new();
641        options.write(true).create_new(true);
642        #[cfg(unix)]
643        {
644            use std::os::unix::fs::OpenOptionsExt as _;
645            options.mode(0o600);
646        }
647        let mut file = options
648            .open(path)
649            .with_context(|| format!("failed to create hosted-account file {path:?}"))?;
650        self.inject_fault(create_fault)?;
651        file.write_all(bytes)
652            .with_context(|| format!("failed to write hosted-account file {path:?}"))?;
653        self.inject_fault(write_fault)?;
654        file.sync_all()
655            .with_context(|| format!("failed to sync hosted-account file {path:?}"))?;
656        self.inject_fault(sync_fault)
657    }
658
659    #[cfg(test)]
660    fn with_fault(root: impl Into<PathBuf>, fault: WriteFault) -> Self {
661        Self {
662            root: root.into(),
663            fault: Some(fault),
664        }
665    }
666
667    #[cfg(test)]
668    fn inject_fault(&self, point: WriteFault) -> Result<()> {
669        if self.fault == Some(point) {
670            bail!("injected crash after {point:?}")
671        }
672        Ok(())
673    }
674
675    #[cfg(not(test))]
676    fn inject_fault(&self, _point: WriteFault) -> Result<()> {
677        Ok(())
678    }
679}
680
681#[derive(Clone, Copy, Debug, Eq, PartialEq)]
682enum WriteFault {
683    StagingDirectoryCreate,
684    AtprotoFileCreate,
685    AtprotoFileWrite,
686    AtprotoFileSync,
687    DidDocumentFileCreate,
688    DidDocumentFileWrite,
689    DidDocumentFileSync,
690    GenesisFileCreate,
691    GenesisFileWrite,
692    GenesisFileSync,
693    RecordFileCreate,
694    RecordFileWrite,
695    RecordFileSync,
696    StagingDirectorySync,
697    Publish,
698    RootDirectorySync,
699}
700
701#[cfg(test)]
702const WRITE_FAULTS: [WriteFault; 16] = [
703    WriteFault::StagingDirectoryCreate,
704    WriteFault::AtprotoFileCreate,
705    WriteFault::AtprotoFileWrite,
706    WriteFault::AtprotoFileSync,
707    WriteFault::DidDocumentFileCreate,
708    WriteFault::DidDocumentFileWrite,
709    WriteFault::DidDocumentFileSync,
710    WriteFault::GenesisFileCreate,
711    WriteFault::GenesisFileWrite,
712    WriteFault::GenesisFileSync,
713    WriteFault::RecordFileCreate,
714    WriteFault::RecordFileWrite,
715    WriteFault::RecordFileSync,
716    WriteFault::StagingDirectorySync,
717    WriteFault::Publish,
718    WriteFault::RootDirectorySync,
719];
720
721/// Return `true` only for a fully valid, byte-identical already-published
722/// account. Invalid or partial legacy directories are deliberately reported as
723/// incomplete so a mint retry can replace them through the no-replace publish
724/// transition; a valid different account is never removed or overwritten.
725fn complete_account_matches(path: &Path, expected: &SealedHostedAccount) -> Result<bool> {
726    let metadata = match std::fs::symlink_metadata(path) {
727        Ok(metadata) => metadata,
728        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(false),
729        Err(error) => {
730            return Err(error)
731                .with_context(|| format!("failed to inspect hosted-account directory {path:?}"));
732        }
733    };
734    ensure!(
735        metadata.file_type().is_dir(),
736        "hosted-account label path {path:?} is not a directory"
737    );
738
739    let read = |name: &str| -> Result<Option<Vec<u8>>> {
740        let file = path.join(name);
741        match std::fs::read(&file) {
742            Ok(bytes) => Ok(Some(bytes)),
743            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
744            Err(error) => {
745                Err(error).with_context(|| format!("failed to read hosted-account file {file:?}"))
746            }
747        }
748    };
749    let document_bytes = read(DID_DOCUMENT_FILE)?;
750    let (Some(record_bytes), Some(genesis_bytes), Some(secret_bytes)) = (
751        read(ACCOUNT_RECORD_FILE)?,
752        read(GENESIS_DID_OP_FILE)?,
753        read(ATPROTO_SIGNING_KEY_FILE)?,
754    ) else {
755        return Ok(false);
756    };
757
758    let Ok(record) = AccountRecord::from_dag_cbor(&record_bytes) else {
759        return Ok(false);
760    };
761    let Ok(genesis) = GenesisDidOp::from_dag_cbor(&genesis_bytes) else {
762        return Ok(false);
763    };
764    let Ok(secret) = AtprotoSigningKey::from_slice(&secret_bytes) else {
765        return Ok(false);
766    };
767    if record.genesis_op() != genesis.cid()?
768        || record.current_op() != record.genesis_op()
769        || record.doc_cid() != genesis.unsigned().doc_cid()
770        || record.atproto_verifying_key()?.to_encoded_point(true)
771            != secret.verifying_key().to_encoded_point(true)
772    {
773        return Ok(false);
774    }
775
776    ensure!(
777        record_bytes == expected.record_bytes
778            && genesis_bytes == expected.genesis_bytes
779            && secret_bytes == expected.atproto_signing_key.to_bytes().as_slice(),
780        "hosted-account label directory {path:?} already contains a different complete account"
781    );
782    let document_bytes = document_bytes.ok_or_else(|| {
783        anyhow::anyhow!(
784            "hosted-account label directory {path:?} is a valid pre-B2 account without its sealed DID document; preserve it and run an explicit migration"
785        )
786    })?;
787    let document = SealedHostedDidDocument::from_canonical_json(&document_bytes)
788        .context("hosted-account directory contains an invalid sealed DID document")?;
789    ensure!(
790        record.doc_cid() == document.cid()
791            && record.name().did() == document.did()
792            && record.atproto_verifying_key()?.to_encoded_point(true)
793                == document.atproto_verifying_key()?.to_encoded_point(true),
794        "hosted-account directory's sealed DID document does not match its account record"
795    );
796    ensure!(
797        document_bytes == expected.did_document.as_bytes(),
798        "hosted-account label directory {path:?} contains a different sealed DID document"
799    );
800    Ok(true)
801}
802
803fn remove_incomplete_account_directory(path: &Path) -> Result<()> {
804    match std::fs::symlink_metadata(path) {
805        Ok(metadata) => {
806            ensure!(
807                metadata.file_type().is_dir(),
808                "hosted-account label path {path:?} is not a directory"
809            );
810            std::fs::remove_dir_all(path).with_context(|| {
811                format!("failed to remove incomplete hosted-account directory {path:?}")
812            })?;
813            sync_directory(
814                path.parent()
815                    .ok_or_else(|| anyhow::anyhow!("hosted-account directory has no parent"))?,
816            )?;
817            Ok(())
818        }
819        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
820        Err(error) => Err(error)
821            .with_context(|| format!("failed to inspect hosted-account directory {path:?}")),
822    }
823}
824
825#[cfg(target_os = "linux")]
826fn rename_no_replace(from: &Path, to: &Path) -> std::io::Result<()> {
827    rustix::fs::renameat_with(
828        rustix::fs::CWD,
829        from,
830        rustix::fs::CWD,
831        to,
832        rustix::fs::RenameFlags::NOREPLACE,
833    )?;
834    Ok(())
835}
836
837#[cfg(not(target_os = "linux"))]
838fn rename_no_replace(_from: &Path, _to: &Path) -> std::io::Result<()> {
839    Err(std::io::Error::new(
840        std::io::ErrorKind::Unsupported,
841        "atomic no-replace directory publication requires Linux renameat2",
842    ))
843}
844
845fn validate_sealed_bundle(account: &SealedHostedAccount) -> Result<()> {
846    ensure!(
847        AccountRecord::from_dag_cbor(&account.record_bytes)? == account.record,
848        "sealed account record bytes do not match the in-memory record"
849    );
850    ensure!(
851        GenesisDidOp::from_dag_cbor(&account.genesis_bytes)? == account.genesis,
852        "sealed genesis bytes do not match the in-memory operation"
853    );
854    ensure!(
855        account.record.genesis_op() == account.genesis.cid()?,
856        "account record does not name its sealed genesis operation"
857    );
858    ensure!(
859        account.record.doc_cid() == account.genesis.unsigned().doc_cid(),
860        "account record and genesis operation disagree on the DID document CID"
861    );
862    ensure!(
863        account.record.doc_cid() == account.did_document.cid(),
864        "account record does not name its sealed DID document"
865    );
866    ensure!(
867        account.record.name().did() == account.did_document.did(),
868        "account record and sealed DID document name different accounts"
869    );
870    ensure!(
871        account
872            .record
873            .atproto_verifying_key()?
874            .to_encoded_point(true)
875            == account
876                .did_document
877                .atproto_verifying_key()?
878                .to_encoded_point(true),
879        "account record and sealed DID document contain different #atproto keys"
880    );
881    ensure!(
882        account
883            .record
884            .atproto_verifying_key()?
885            .to_encoded_point(true)
886            == account
887                .atproto_signing_key
888                .verifying_key()
889                .to_encoded_point(true),
890        "account record #atproto public key does not match the generated private key"
891    );
892    Ok(())
893}
894
895fn ensure_private_directory(path: &Path) -> Result<()> {
896    std::fs::create_dir_all(path)
897        .with_context(|| format!("failed to create hosted-account root {path:?}"))?;
898    ensure!(
899        std::fs::symlink_metadata(path)?.file_type().is_dir(),
900        "hosted-account root is not a directory"
901    );
902    set_private_directory_permissions(path)
903}
904
905#[cfg(unix)]
906fn set_private_directory_permissions(path: &Path) -> Result<()> {
907    use std::os::unix::fs::PermissionsExt as _;
908    std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700))
909        .with_context(|| format!("failed to secure hosted-account directory {path:?}"))
910}
911
912#[cfg(not(unix))]
913fn set_private_directory_permissions(_path: &Path) -> Result<()> {
914    Ok(())
915}
916
917fn sync_directory(path: &Path) -> Result<()> {
918    File::open(path)
919        .with_context(|| format!("failed to open hosted-account directory {path:?} for sync"))?
920        .sync_all()
921        .with_context(|| format!("failed to sync hosted-account directory {path:?}"))
922}
923
924fn required<'a>(value: &'a DagCbor, key: &str, what: &str) -> Result<&'a DagCbor> {
925    value
926        .get(key)
927        .ok_or_else(|| anyhow::anyhow!("{what} missing required field {key:?}"))
928}
929
930fn reject_unknown(value: &DagCbor, allowed: &[&str], what: &str) -> Result<()> {
931    let allowed = allowed.iter().copied().collect::<BTreeSet<_>>();
932    for (key, _) in value.as_map()? {
933        let key = key.as_str()?;
934        if !allowed.contains(key) {
935            bail!("{what} contains unknown field {key:?}");
936        }
937    }
938    Ok(())
939}
940
941#[cfg(test)]
942mod tests {
943    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing)]
944
945    use super::*;
946    use crate::did_op::{
947        sign_genesis, HostKeyEnrollment, HybridRotationKey, RecoveryKeyEnrollment, UserRotationKey,
948    };
949    use ed25519_dalek::SigningKey;
950    use hyprstream_crypto::pq::{ml_dsa_generate_keypair, ml_dsa_vk_bytes, MlDsaSigningKey};
951
952    struct UserSigner {
953        ed: SigningKey,
954        pq: MlDsaSigningKey,
955        public: HybridRotationKey,
956    }
957
958    fn user_signer() -> UserSigner {
959        let ed = SigningKey::generate(&mut OsRng);
960        let (pq, pq_vk) = ml_dsa_generate_keypair();
961        let public =
962            HybridRotationKey::new(ed.verifying_key().to_bytes(), ml_dsa_vk_bytes(&pq_vk)).unwrap();
963        UserSigner { ed, pq, public }
964    }
965
966    fn begin(user: &UserSigner) -> HostedAccountMint {
967        HostedAccountMint::begin(
968            AllocatedAccountName::new("alice", "did:web:alice.acct.example.com").unwrap(),
969            GenesisRotationKeys::new(
970                UserRotationKey::new(user.public.clone()),
971                RecoveryKeyEnrollment::Declined,
972                HostKeyEnrollment::Absent,
973            )
974            .unwrap(),
975        )
976        .unwrap()
977    }
978
979    fn prepare(mint: HostedAccountMint) -> PendingHostedAccountMint {
980        let document = mint.seal_did_document("https://pds.example.com").unwrap();
981        mint.prepare_genesis(document, GenesisRepoHead::EmptyRepo)
982            .unwrap()
983    }
984
985    #[test]
986    fn mint_generates_account_specific_atproto_key_and_never_serializes_secret() {
987        let user = user_signer();
988        let first = begin(&user);
989        let first_public = first.atproto_verifying_key();
990        let second = begin(&user);
991        assert_ne!(
992            first_public.to_encoded_point(true),
993            second.atproto_verifying_key().to_encoded_point(true)
994        );
995
996        let pending = prepare(first);
997        let signature = sign_genesis(pending.unsigned_genesis(), &user.ed, &user.pq).unwrap();
998        let sealed = pending.seal(signature).unwrap();
999        assert_eq!(
1000            sealed
1001                .record()
1002                .atproto_verifying_key()
1003                .unwrap()
1004                .to_encoded_point(true),
1005            first_public.to_encoded_point(true)
1006        );
1007        let secret = sealed.atproto_signing_key().to_bytes();
1008        assert!(
1009            !sealed
1010                .record_bytes()
1011                .windows(secret.len())
1012                .any(|window| window == secret.as_slice()),
1013            "account record must never contain the #atproto private key"
1014        );
1015        assert!(
1016            !sealed
1017                .genesis_bytes()
1018                .windows(secret.len())
1019                .any(|window| window == secret.as_slice()),
1020            "genesis operation must never contain the #atproto private key"
1021        );
1022    }
1023
1024    #[test]
1025    fn account_record_is_not_produced_before_valid_user_signature() {
1026        let user = user_signer();
1027        let attacker = user_signer();
1028        let pending = prepare(begin(&user));
1029        assert!(sign_genesis(pending.unsigned_genesis(), &attacker.ed, &attacker.pq).is_err());
1030    }
1031
1032    #[test]
1033    fn genesis_rejects_a_document_from_another_mint() {
1034        let user = user_signer();
1035        let first = begin(&user);
1036        let other_document = first.seal_did_document("https://pds.example.com").unwrap();
1037        let second = begin(&user);
1038        let error = second
1039            .prepare_genesis(other_document, GenesisRepoHead::EmptyRepo)
1040            .err()
1041            .expect("a document with another mint's #atproto key must fail");
1042        assert!(
1043            error.to_string().contains("different #atproto key"),
1044            "{error:#}"
1045        );
1046    }
1047
1048    #[test]
1049    fn account_and_genesis_roundtrip_byte_exactly() {
1050        let user = user_signer();
1051        let pending = prepare(begin(&user));
1052        let signature = sign_genesis(pending.unsigned_genesis(), &user.ed, &user.pq).unwrap();
1053        let sealed = pending.seal(signature).unwrap();
1054        let account = AccountRecord::from_dag_cbor(sealed.record_bytes()).unwrap();
1055        assert_eq!(account.to_dag_cbor().unwrap(), sealed.record_bytes());
1056        let genesis = GenesisDidOp::from_dag_cbor(sealed.genesis_bytes()).unwrap();
1057        assert_eq!(genesis.to_dag_cbor().unwrap(), sealed.genesis_bytes());
1058        assert_eq!(account.genesis_op(), genesis.cid().unwrap());
1059        assert_eq!(account.current_op(), account.genesis_op());
1060        assert_eq!(account.doc_cid(), genesis.unsigned().doc_cid());
1061        assert_eq!(account.doc_cid(), sealed.did_document().cid());
1062    }
1063
1064    #[test]
1065    fn allocated_name_rejects_path_form_and_label_mismatch() {
1066        assert!(AllocatedAccountName::new("alice", "did:web:example.com:users:alice").is_err());
1067        assert!(AllocatedAccountName::new("alice", "did:web:bob.acct.example.com").is_err());
1068        assert!(AllocatedAccountName::new(
1069            "alice.example",
1070            "did:web:alice.example.acct.example.com"
1071        )
1072        .is_err());
1073    }
1074
1075    #[test]
1076    fn unauthenticated_sentinel_cannot_be_registered_or_minted() {
1077        let error = AllocatedAccountName::new("unknown", UNAUTHENTICATED_DID_SENTINEL).unwrap_err();
1078        assert!(
1079            error.to_string().contains("cannot be registered or minted"),
1080            "{error:#}"
1081        );
1082    }
1083
1084    #[test]
1085    fn operation_one_version_is_sealed_before_account_record() {
1086        let user = user_signer();
1087        let pending = prepare(begin(&user));
1088        let signing_value = DagCbor::decode(&pending.signing_bytes().unwrap()).unwrap();
1089        assert_eq!(
1090            signing_value.get("version").unwrap().as_unsigned().unwrap(),
1091            1
1092        );
1093        let signature = sign_genesis(pending.unsigned_genesis(), &user.ed, &user.pq).unwrap();
1094        assert!(pending.seal(signature).is_ok());
1095    }
1096
1097    #[test]
1098    fn durable_writer_publishes_record_last_and_never_overwrites() {
1099        let user = user_signer();
1100        let pending = prepare(begin(&user));
1101        let signature = sign_genesis(pending.unsigned_genesis(), &user.ed, &user.pq).unwrap();
1102        let sealed = pending.seal(signature).unwrap();
1103        let expected_record = sealed.record().clone();
1104        let expected_record_bytes = sealed.record_bytes().to_vec();
1105        let expected_genesis_bytes = sealed.genesis_bytes().to_vec();
1106        let expected_document_bytes = sealed.did_document().as_bytes().to_vec();
1107        let expected_secret = sealed.atproto_signing_key().to_bytes();
1108
1109        let temporary = tempfile::tempdir().unwrap();
1110        let store = DirectoryHostedAccountStore::new(temporary.path().join("accounts"));
1111        let stored_record = sealed.write_to(&store).unwrap();
1112        assert_eq!(stored_record, expected_record);
1113
1114        let account_dir = store.root().join("alice");
1115        assert_eq!(
1116            std::fs::read(account_dir.join(ACCOUNT_RECORD_FILE)).unwrap(),
1117            expected_record_bytes
1118        );
1119        assert_eq!(
1120            std::fs::read(account_dir.join(GENESIS_DID_OP_FILE)).unwrap(),
1121            expected_genesis_bytes
1122        );
1123        assert_eq!(
1124            std::fs::read(account_dir.join(DID_DOCUMENT_FILE)).unwrap(),
1125            expected_document_bytes
1126        );
1127        assert_eq!(
1128            std::fs::read(account_dir.join(ATPROTO_SIGNING_KEY_FILE)).unwrap(),
1129            expected_secret.as_slice()
1130        );
1131
1132        // The label directory is the exclusive never-overwrite boundary.
1133        let second = prepare(begin(&user));
1134        let second_signature = sign_genesis(second.unsigned_genesis(), &user.ed, &user.pq).unwrap();
1135        assert!(second
1136            .seal(second_signature)
1137            .unwrap()
1138            .write_to(&store)
1139            .is_err());
1140        assert_eq!(
1141            std::fs::read(account_dir.join(ACCOUNT_RECORD_FILE)).unwrap(),
1142            expected_record_bytes
1143        );
1144
1145        #[cfg(unix)]
1146        {
1147            use std::os::unix::fs::PermissionsExt as _;
1148            assert_eq!(
1149                std::fs::metadata(account_dir.join(ATPROTO_SIGNING_KEY_FILE))
1150                    .unwrap()
1151                    .permissions()
1152                    .mode()
1153                    & 0o777,
1154                0o600
1155            );
1156        }
1157    }
1158
1159    #[test]
1160    fn durable_writer_recovers_from_every_interrupted_boundary() {
1161        let user = user_signer();
1162        let pending = prepare(begin(&user));
1163        let signature = sign_genesis(pending.unsigned_genesis(), &user.ed, &user.pq).unwrap();
1164        let sealed = pending.seal(signature).unwrap();
1165
1166        for fault in WRITE_FAULTS {
1167            let temporary = tempfile::tempdir().unwrap();
1168            let root = temporary.path().join("accounts");
1169            let interrupted = DirectoryHostedAccountStore::with_fault(&root, fault);
1170            assert!(
1171                interrupted.write_new(&sealed).is_err(),
1172                "fault injection at {fault:?} must interrupt mint publication"
1173            );
1174
1175            let final_directory = root.join(sealed.record().name().label());
1176            if final_directory.exists() {
1177                assert!(
1178                    complete_account_matches(&final_directory, &sealed).unwrap(),
1179                    "a crash at {fault:?} may publish only a complete account"
1180                );
1181            }
1182
1183            let recovery = DirectoryHostedAccountStore::new(&root);
1184            recovery.write_new(&sealed).unwrap();
1185            assert!(complete_account_matches(&final_directory, &sealed).unwrap());
1186        }
1187    }
1188
1189    #[test]
1190    fn durable_writer_preserves_a_valid_pre_b2_account_for_explicit_migration() {
1191        let user = user_signer();
1192        let pending = prepare(begin(&user));
1193        let signature = sign_genesis(pending.unsigned_genesis(), &user.ed, &user.pq).unwrap();
1194        let sealed = pending.seal(signature).unwrap();
1195
1196        let temporary = tempfile::tempdir().unwrap();
1197        let store = DirectoryHostedAccountStore::new(temporary.path().join("accounts"));
1198        sealed.write_to(&store).unwrap();
1199        let account_dir = store.root().join("alice");
1200        std::fs::remove_file(account_dir.join(DID_DOCUMENT_FILE)).unwrap();
1201
1202        let error = sealed
1203            .write_to(&store)
1204            .expect_err("pre-B2 account must require an explicit migration");
1205        assert!(error.to_string().contains("pre-B2"), "{error:#}");
1206        assert!(account_dir.join(ACCOUNT_RECORD_FILE).exists());
1207        assert!(account_dir.join(GENESIS_DID_OP_FILE).exists());
1208        assert!(account_dir.join(ATPROTO_SIGNING_KEY_FILE).exists());
1209        assert!(!account_dir.join(DID_DOCUMENT_FILE).exists());
1210    }
1211}