Skip to main content

hyprstream_discovery/
plc_directory.rs

1//! Operable, fail-closed directory for Hyprstream's hybrid `did:plc` log.
2//!
3//! This is deliberately separate from `hyprstream_rpc::did_plc`: that module
4//! remains the read-only federation resolver for classical PLC directories.
5//! This module owns only locally registered hybrid identities and never stores
6//! or returns a tenant.
7//!
8//! Directory records contain canonical operation bytes and a PDS endpoint.
9//! They do not contain live transport reach. Every identity read decodes and
10//! verifies the complete operation log with [`crate::did_op::verify_did_op_log`].
11//! Every connect-time read then asks [`LivePlcDiscovery`] for current reach, so
12//! certificate rotation cannot leave stale pins on an inventory/directory row.
13
14use std::collections::BTreeMap;
15use std::sync::Arc;
16
17use anyhow::{bail, ensure, Context, Result};
18use base64::{engine::general_purpose::STANDARD, Engine as _};
19use ed25519_dalek::SigningKey;
20use hyprstream_crypto::cose_sign::{
21    assemble_composite_nested, sign_composite, split_composite, verify_composite,
22};
23use hyprstream_crypto::pq::{ml_dsa_vk_bytes, MlDsaSigningKey};
24use hyprstream_pds::dag_cbor::DagCbor;
25use hyprstream_rpc::identity::UNAUTHENTICATED_DID_SENTINEL;
26use hyprstream_rpc::service_entry::BrowserQuicReach;
27use parking_lot::RwLock;
28use serde::{Deserialize, Serialize};
29
30use crate::did_op::{verify_did_op_log, DidOp, HybridRotationKey, VerifiedDidOpLog};
31use crate::RegistryDeploymentVerifier;
32
33const DIRECTORY_GENESIS_TYPE: &str = "plc_directory_genesis";
34const DIRECTORY_GENESIS_SIGNATURE_CONTEXT: &[u8] = b"hyprstream.plc-directory-genesis/1";
35
36/// Hybrid-signed binding between operation zero and its PDS resolution pointer.
37///
38/// The merged operation-log format intentionally contains only authorization
39/// state. This companion artifact prevents the directory store from changing a
40/// PDS endpoint without a signature by one of genesis's declared Hybrid keys.
41#[derive(Clone, Debug, Eq, PartialEq)]
42pub struct SignedPlcDirectoryGenesis {
43    did: String,
44    genesis_cid: String,
45    pds_endpoint: String,
46    signature: crate::did_op::HybridDidOpSignature,
47}
48
49impl SignedPlcDirectoryGenesis {
50    /// Create the self-service artifact on the identity holder's signer.
51    pub fn sign(
52        genesis: &DidOp,
53        pds_endpoint: &str,
54        ed25519: &SigningKey,
55        mldsa65: &MlDsaSigningKey,
56    ) -> Result<Self> {
57        validate_https_endpoint(pds_endpoint, "PDS endpoint")?;
58        let did = genesis.genesis_did()?;
59        ensure!(
60            genesis
61                .rotation_keys
62                .iter()
63                .any(|key| key.matches_signers(ed25519, mldsa65)),
64            "directory genesis signer is not one of the declared Hybrid rotation keys"
65        );
66        let mut binding = Self {
67            did,
68            genesis_cid: genesis.cid().encode(),
69            pds_endpoint: pds_endpoint.to_owned(),
70            signature: crate::did_op::HybridDidOpSignature {
71                ed25519: Vec::new(),
72                mldsa65: Vec::new(),
73            },
74        };
75        let composite = sign_composite(
76            ed25519,
77            Some(mldsa65),
78            &binding.signable_bytes(),
79            DIRECTORY_GENESIS_SIGNATURE_CONTEXT,
80        )
81        .context("hybrid-signing PLC directory genesis binding")?;
82        let (ed25519, mldsa65) =
83            split_composite(&composite).context("splitting directory genesis signature")?;
84        binding.signature = crate::did_op::HybridDidOpSignature {
85            ed25519,
86            mldsa65: mldsa65.ok_or_else(|| {
87                anyhow::anyhow!("directory genesis signing produced no ML-DSA-65 component")
88            })?,
89        };
90        binding.signature.validate_shape()?;
91        Ok(binding)
92    }
93
94    #[must_use]
95    pub fn did(&self) -> &str {
96        &self.did
97    }
98
99    #[must_use]
100    pub fn pds_endpoint(&self) -> &str {
101        &self.pds_endpoint
102    }
103
104    /// Canonical signed storage form.
105    #[must_use]
106    pub fn to_dag_cbor(&self) -> Vec<u8> {
107        self.to_value(true).encode()
108    }
109
110    /// Strictly decode the canonical signed storage form.
111    pub fn from_dag_cbor(bytes: &[u8]) -> Result<Self> {
112        let value = DagCbor::decode(bytes).context("decoding directory genesis binding")?;
113        require_exact_fields(
114            &value,
115            &["did", "genesisCid", "pdsEndpoint", "sig", "type"],
116            "directory genesis binding",
117        )?;
118        ensure!(
119            required(&value, "type")?.as_str()? == DIRECTORY_GENESIS_TYPE,
120            "unsupported directory genesis binding type"
121        );
122        let signature = required(&value, "sig")?;
123        require_exact_fields(
124            signature,
125            &["ed25519", "mldsa65"],
126            "directory genesis signature",
127        )?;
128        let binding = Self {
129            did: required(&value, "did")?.as_str()?.to_owned(),
130            genesis_cid: required(&value, "genesisCid")?.as_str()?.to_owned(),
131            pds_endpoint: required(&value, "pdsEndpoint")?.as_str()?.to_owned(),
132            signature: crate::did_op::HybridDidOpSignature {
133                ed25519: required(signature, "ed25519")?.as_bytes()?.to_vec(),
134                mldsa65: required(signature, "mldsa65")?.as_bytes()?.to_vec(),
135            },
136        };
137        binding.signature.validate_shape()?;
138        ensure!(
139            binding.to_dag_cbor() == bytes,
140            "directory genesis binding is not canonical DAG-CBOR"
141        );
142        Ok(binding)
143    }
144
145    fn verify(&self, expected_did: &str, genesis: &DidOp) -> Result<()> {
146        ensure!(
147            self.did == expected_did,
148            "directory genesis binding DID does not match requested DID"
149        );
150        ensure!(
151            self.genesis_cid == genesis.cid().encode(),
152            "directory genesis binding does not match operation zero"
153        );
154        validate_https_endpoint(&self.pds_endpoint, "PDS endpoint")?;
155        self.signature.validate_shape()?;
156        let payload = self.signable_bytes();
157        let mut errors = Vec::new();
158        for key in &genesis.rotation_keys {
159            let result = (|| {
160                let (ed25519, mldsa65) = key.verifying_keys()?;
161                let composite = assemble_composite_nested(
162                    (ed25519.to_bytes().to_vec(), self.signature.ed25519.clone()),
163                    Some((ml_dsa_vk_bytes(&mldsa65), self.signature.mldsa65.clone())),
164                )
165                .context("assembling directory genesis signature")?;
166                let verified = verify_composite(
167                    &composite,
168                    &ed25519,
169                    Some(&mldsa65),
170                    &payload,
171                    DIRECTORY_GENESIS_SIGNATURE_CONTEXT,
172                    true,
173                )
174                .context("verifying directory genesis signature")?;
175                ensure!(
176                    verified.eddsa && verified.ml_dsa,
177                    "both directory genesis signature components were not verified"
178                );
179                Ok::<(), anyhow::Error>(())
180            })();
181            match result {
182                Ok(()) => return Ok(()),
183                Err(error) => errors.push(error.to_string()),
184            }
185        }
186        bail!(
187            "directory genesis binding did not verify under a declared Hybrid key: {}",
188            errors.join("; ")
189        )
190    }
191
192    fn signable_bytes(&self) -> Vec<u8> {
193        self.to_value(false).encode()
194    }
195
196    fn to_value(&self, include_signature: bool) -> DagCbor {
197        let mut fields = vec![
198            ("did", DagCbor::Text(self.did.clone())),
199            ("genesisCid", DagCbor::Text(self.genesis_cid.clone())),
200            ("pdsEndpoint", DagCbor::Text(self.pds_endpoint.clone())),
201            ("type", DagCbor::Text(DIRECTORY_GENESIS_TYPE.to_owned())),
202        ];
203        if include_signature {
204            fields.push((
205                "sig",
206                DagCbor::str_map([
207                    ("ed25519", DagCbor::Bytes(self.signature.ed25519.clone())),
208                    ("mldsa65", DagCbor::Bytes(self.signature.mldsa65.clone())),
209                ]),
210            ));
211        }
212        DagCbor::str_map(fields)
213    }
214}
215
216/// Persistence shape for one directory identity.
217///
218/// Operation bytes remain the storage boundary so resolution cannot inherit a
219/// stale "already verified" bit from a database. Implementations may persist
220/// this value in any authority-owned store; callers must treat loaded records
221/// as untrusted until [`PlcDirectory::resolve_identity`] returns.
222#[derive(Clone, Debug, Eq, PartialEq)]
223pub struct PlcDirectoryRecord {
224    operation_log: Vec<Vec<u8>>,
225    genesis_binding: Vec<u8>,
226}
227
228impl PlcDirectoryRecord {
229    /// Rehydrate a stored record. Validation intentionally happens at resolve.
230    #[must_use]
231    pub fn from_stored_parts(operation_log: Vec<Vec<u8>>, genesis_binding: Vec<u8>) -> Self {
232        Self {
233            operation_log,
234            genesis_binding,
235        }
236    }
237
238    /// Canonical signed operations, in log order.
239    #[must_use]
240    pub fn operation_log(&self) -> &[Vec<u8>] {
241        &self.operation_log
242    }
243
244    /// Hybrid-signed genesis binding in canonical DAG-CBOR.
245    #[must_use]
246    pub fn genesis_binding(&self) -> &[u8] {
247        &self.genesis_binding
248    }
249}
250
251/// Atomic genesis storage used by the operable directory.
252///
253/// There is intentionally no update method in the demo cut. Rotation and
254/// witness policy are deferred to #1168–1171.
255pub trait PlcDirectoryStore: Send + Sync {
256    /// Insert operation zero exactly once for `did`.
257    fn create_genesis(&self, did: &str, record: PlcDirectoryRecord) -> Result<()>;
258
259    /// Load one record for verification, or `None` when it is absent.
260    fn get(&self, did: &str) -> Result<Option<PlcDirectoryRecord>>;
261}
262
263/// In-memory store for embedded/demo deployments.
264#[derive(Default)]
265pub struct InMemoryPlcDirectoryStore {
266    records: RwLock<BTreeMap<String, PlcDirectoryRecord>>,
267}
268
269impl PlcDirectoryStore for InMemoryPlcDirectoryStore {
270    fn create_genesis(&self, did: &str, record: PlcDirectoryRecord) -> Result<()> {
271        let mut records = self.records.write();
272        ensure!(
273            !records.contains_key(did),
274            "did:plc genesis already exists for {did}"
275        );
276        records.insert(did.to_owned(), record);
277        Ok(())
278    }
279
280    fn get(&self, did: &str) -> Result<Option<PlcDirectoryRecord>> {
281        Ok(self.records.read().get(did).cloned())
282    }
283}
284
285/// Resolver for live PDS transport metadata.
286///
287/// Implementations are trusted service capabilities, not client callbacks.
288/// Any implementation performing network I/O must authenticate its caller and
289/// constrain egress before resolving the authority-stored PDS endpoint.
290pub trait LivePlcDiscovery: Send + Sync {
291    /// Resolve current reach for this verified directory identity.
292    fn current(&self, did: &str, pds_endpoint: &str) -> Result<BrowserQuicReach>;
293}
294
295/// Current verified identity state.
296#[derive(Clone, Debug, Eq, PartialEq)]
297pub struct ResolvedPlcIdentity {
298    did: String,
299    rotation_keys: Vec<HybridRotationKey>,
300    pds_endpoint: String,
301}
302
303impl ResolvedPlcIdentity {
304    #[must_use]
305    pub fn did(&self) -> &str {
306        &self.did
307    }
308
309    #[must_use]
310    pub fn rotation_keys(&self) -> &[HybridRotationKey] {
311        &self.rotation_keys
312    }
313
314    #[must_use]
315    pub fn pds_endpoint(&self) -> &str {
316        &self.pds_endpoint
317    }
318}
319
320/// Frontend connect-time discovery contract.
321#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
322#[serde(rename_all = "camelCase")]
323pub struct ConnectTimeDiscovery {
324    quic_url: String,
325    cert_hash: String,
326}
327
328impl ConnectTimeDiscovery {
329    #[must_use]
330    pub fn quic_url(&self) -> &str {
331        &self.quic_url
332    }
333
334    #[must_use]
335    pub fn cert_hash(&self) -> &str {
336        &self.cert_hash
337    }
338}
339
340/// Future authorization seam for a post-genesis successor.
341///
342/// #1168–1171 will supply the custody, recovery-window, fork, and witness
343/// implementation. The demo directory intentionally exposes no append method,
344/// so implementing this trait cannot mutate a log until that policy lands.
345pub trait DidOpSuccessorWitness: Send + Sync {
346    fn authorize_successor(&self, current: &VerifiedDidOpLog, successor: &DidOp) -> Result<()>;
347}
348
349/// Operable directory over canonical Hybrid DID operation logs.
350pub struct PlcDirectory {
351    store: Arc<dyn PlcDirectoryStore>,
352    live_discovery: Arc<dyn LivePlcDiscovery>,
353    deployment_authority: RegistryDeploymentVerifier,
354}
355
356impl PlcDirectory {
357    #[must_use]
358    pub fn new(
359        store: Arc<dyn PlcDirectoryStore>,
360        live_discovery: Arc<dyn LivePlcDiscovery>,
361        deployment_authority: RegistryDeploymentVerifier,
362    ) -> Self {
363        Self {
364            store,
365            live_discovery,
366            deployment_authority,
367        }
368    }
369
370    /// Register a self-service genesis signed by one declared Hybrid key.
371    ///
372    /// `claimed_did` is checked against the self-certifying genesis hash. A
373    /// client therefore cannot choose another DID or register the
374    /// unauthenticated sentinel.
375    pub fn create_self_service(
376        &self,
377        claimed_did: &str,
378        genesis: DidOp,
379        binding: SignedPlcDirectoryGenesis,
380    ) -> Result<ResolvedPlcIdentity> {
381        self.create_verified_genesis(claimed_did, genesis, binding)
382    }
383
384    /// Mint and register an operator-manual genesis.
385    ///
386    /// Both signing keys must match the authenticated deployment trust root
387    /// retained by [`RegistryDeploymentVerifier`]. The root must also appear
388    /// in `rotation_keys`; [`DidOp::signed_genesis`] enforces that binding.
389    pub fn create_operator_manual(
390        &self,
391        rotation_keys: Vec<HybridRotationKey>,
392        pds_endpoint: &str,
393        ed25519: &SigningKey,
394        mldsa65: &MlDsaSigningKey,
395    ) -> Result<ResolvedPlcIdentity> {
396        let pinned_root = self
397            .deployment_authority
398            .deployment_did_op_key()
399            .context("authenticated deployment root is not a valid DID operation key")?;
400        let supplied = HybridRotationKey::from_signing_keys(ed25519, mldsa65);
401        ensure!(
402            supplied == pinned_root,
403            "operator-manual genesis signer does not match the authenticated Hybrid deployment root"
404        );
405        let genesis = DidOp::signed_genesis(rotation_keys, ed25519, mldsa65)
406            .context("deployment-authority genesis signing failed")?;
407        let did = genesis.genesis_did()?;
408        let binding = SignedPlcDirectoryGenesis::sign(&genesis, pds_endpoint, ed25519, mldsa65)?;
409        self.create_verified_genesis(&did, genesis, binding)
410    }
411
412    fn create_verified_genesis(
413        &self,
414        claimed_did: &str,
415        genesis: DidOp,
416        binding: SignedPlcDirectoryGenesis,
417    ) -> Result<ResolvedPlcIdentity> {
418        ensure_registerable_did(claimed_did)?;
419        let verified = verify_did_op_log(claimed_did, std::slice::from_ref(&genesis))
420            .context("genesis operation failed Hybrid log verification")?;
421        ensure!(
422            verified.sequence == 0,
423            "genesis registration unexpectedly resolved a successor"
424        );
425        binding
426            .verify(claimed_did, &genesis)
427            .context("directory genesis binding failed Hybrid verification")?;
428        self.store.create_genesis(
429            claimed_did,
430            PlcDirectoryRecord {
431                operation_log: vec![genesis.to_dag_cbor()],
432                genesis_binding: binding.to_dag_cbor(),
433            },
434        )?;
435        self.resolve_identity(claimed_did)
436    }
437
438    /// Resolve current keys and the PDS pointer after full log verification.
439    pub fn resolve_identity(&self, did: &str) -> Result<ResolvedPlcIdentity> {
440        ensure_registerable_did(did)?;
441        let record = self
442            .store
443            .get(did)?
444            .ok_or_else(|| anyhow::anyhow!("did:plc identity not found: {did}"))?;
445        let log = record
446            .operation_log()
447            .iter()
448            .enumerate()
449            .map(|(index, bytes)| {
450                DidOp::from_dag_cbor(bytes)
451                    .with_context(|| format!("decoding DID operation {index}"))
452            })
453            .collect::<Result<Vec<_>>>()?;
454        let verified =
455            verify_did_op_log(did, &log).context("stored DID operation log failed verification")?;
456        let genesis = log
457            .first()
458            .ok_or_else(|| anyhow::anyhow!("stored DID operation log is empty"))?;
459        let binding = SignedPlcDirectoryGenesis::from_dag_cbor(record.genesis_binding())
460            .context("stored directory genesis binding is invalid")?;
461        binding
462            .verify(did, genesis)
463            .context("stored directory genesis binding failed Hybrid verification")?;
464        Ok(ResolvedPlcIdentity {
465            did: verified.did,
466            rotation_keys: verified.rotation_keys,
467            pds_endpoint: binding.pds_endpoint,
468        })
469    }
470
471    /// Resolve live `{quicUrl, certHash}` for one connection attempt.
472    ///
473    /// No live value is read from or written to [`PlcDirectoryStore`].
474    pub fn resolve(&self, did: &str) -> Result<ConnectTimeDiscovery> {
475        let identity = self.resolve_identity(did)?;
476        let reach = self
477            .live_discovery
478            .current(identity.did(), identity.pds_endpoint())
479            .context("live PLC discovery failed")?;
480        validate_https_endpoint(&reach.quic_url, "QUIC URL")?;
481        validate_cert_hash(&reach.cert_hash)?;
482        Ok(ConnectTimeDiscovery {
483            quic_url: reach.quic_url,
484            cert_hash: reach.cert_hash,
485        })
486    }
487}
488
489fn ensure_registerable_did(did: &str) -> Result<()> {
490    ensure!(
491        did != UNAUTHENTICATED_DID_SENTINEL,
492        "{UNAUTHENTICATED_DID_SENTINEL} is reserved for credential absence and is non-registerable"
493    );
494    ensure!(
495        hyprstream_rpc::did_plc::is_did_plc(did),
496        "operable PLC directory accepts only did:plc identities"
497    );
498    Ok(())
499}
500
501fn validate_https_endpoint(endpoint: &str, what: &str) -> Result<()> {
502    let url = reqwest::Url::parse(endpoint).with_context(|| format!("{what} is not a URL"))?;
503    ensure!(url.scheme() == "https", "{what} must use https");
504    ensure!(url.host().is_some(), "{what} must include a host");
505    ensure!(
506        url.username().is_empty() && url.password().is_none(),
507        "{what} must not contain credentials"
508    );
509    ensure!(
510        url.fragment().is_none(),
511        "{what} must not contain a fragment"
512    );
513    Ok(())
514}
515
516fn validate_cert_hash(cert_hash: &str) -> Result<()> {
517    let bytes = STANDARD
518        .decode(cert_hash)
519        .context("certificate hash is not canonical base64")?;
520    ensure!(
521        bytes.len() == 32,
522        "certificate hash must contain one SHA-256 digest"
523    );
524    ensure!(
525        STANDARD.encode(&bytes) == cert_hash,
526        "certificate hash is not canonical base64"
527    );
528    Ok(())
529}
530
531fn required<'a>(value: &'a DagCbor, field: &str) -> Result<&'a DagCbor> {
532    value
533        .get(field)
534        .ok_or_else(|| anyhow::anyhow!("missing required field {field:?}"))
535}
536
537fn require_exact_fields(value: &DagCbor, expected: &[&str], what: &str) -> Result<()> {
538    let map = value
539        .as_map()
540        .with_context(|| format!("{what} must be a map"))?;
541    ensure!(
542        map.len() == expected.len(),
543        "{what} must contain exactly fields {expected:?}"
544    );
545    for field in expected {
546        ensure!(
547            value.get(field).is_some(),
548            "{what} is missing required field {field:?}"
549        );
550    }
551    Ok(())
552}
553
554#[cfg(test)]
555#[allow(clippy::expect_used, clippy::unwrap_used)]
556mod tests {
557    use std::sync::atomic::{AtomicU8, Ordering};
558
559    use hyprstream_crypto::pq::{ml_dsa_sk_from_seed, MlDsaSigningKey};
560
561    use super::*;
562
563    struct Keys {
564        ed: SigningKey,
565        pq: MlDsaSigningKey,
566        public: HybridRotationKey,
567    }
568
569    fn keys(seed: u8) -> Keys {
570        let ed = SigningKey::from_bytes(&[seed; 32]);
571        let pq = ml_dsa_sk_from_seed(&[seed; 32]);
572        let public = HybridRotationKey::from_signing_keys(&ed, &pq);
573        Keys { ed, pq, public }
574    }
575
576    struct ChangingDiscovery {
577        generation: AtomicU8,
578    }
579
580    impl LivePlcDiscovery for ChangingDiscovery {
581        fn current(&self, _did: &str, pds_endpoint: &str) -> Result<BrowserQuicReach> {
582            let generation = self.generation.fetch_add(1, Ordering::SeqCst) + 1;
583            Ok(BrowserQuicReach {
584                quic_url: format!("{pds_endpoint}:4433/wt"),
585                cert_hash: STANDARD.encode([generation; 32]),
586            })
587        }
588    }
589
590    fn fixture() -> (Arc<InMemoryPlcDirectoryStore>, PlcDirectory, Keys) {
591        let authority = keys(41);
592        let verifier =
593            RegistryDeploymentVerifier::for_test_deployment_root(&authority.ed, &authority.pq)
594                .unwrap();
595        let store = Arc::new(InMemoryPlcDirectoryStore::default());
596        let directory = PlcDirectory::new(
597            store.clone(),
598            Arc::new(ChangingDiscovery {
599                generation: AtomicU8::new(0),
600            }),
601            verifier,
602        );
603        (store, directory, authority)
604    }
605
606    fn self_service_artifacts(
607        user: &Keys,
608        pds_endpoint: &str,
609    ) -> (String, DidOp, SignedPlcDirectoryGenesis) {
610        let genesis = DidOp::signed_genesis(vec![user.public.clone()], &user.ed, &user.pq).unwrap();
611        let did = genesis.genesis_did().unwrap();
612        let binding =
613            SignedPlcDirectoryGenesis::sign(&genesis, pds_endpoint, &user.ed, &user.pq).unwrap();
614        (did, genesis, binding)
615    }
616
617    #[test]
618    fn self_service_genesis_resolves_verified_keys_and_pds() {
619        let (_store, directory, _authority) = fixture();
620        let user = keys(7);
621        let (did, genesis, binding) = self_service_artifacts(&user, "https://pds.example");
622
623        let resolved = directory
624            .create_self_service(&did, genesis, binding)
625            .unwrap();
626
627        assert_eq!(resolved.did(), did);
628        assert_eq!(resolved.rotation_keys(), &[user.public]);
629        assert_eq!(resolved.pds_endpoint(), "https://pds.example");
630    }
631
632    #[test]
633    fn did_unknown_genesis_fails_closed_without_storage() {
634        let (store, directory, _authority) = fixture();
635        let user = keys(8);
636        let (_did, genesis, binding) = self_service_artifacts(&user, "https://pds.example");
637
638        let error = directory
639            .create_self_service(UNAUTHENTICATED_DID_SENTINEL, genesis, binding)
640            .unwrap_err();
641
642        assert!(error.to_string().contains("non-registerable"));
643        assert!(store.get(UNAUTHENTICATED_DID_SENTINEL).unwrap().is_none());
644    }
645
646    #[test]
647    fn operator_manual_genesis_requires_authenticated_hybrid_root() {
648        let (_store, directory, authority) = fixture();
649        let resolved = directory
650            .create_operator_manual(
651                vec![authority.public],
652                "https://operator-pds.example",
653                &authority.ed,
654                &authority.pq,
655            )
656            .unwrap();
657        assert!(resolved.did().starts_with("did:plc:"));
658
659        let wrong = keys(42);
660        let error = directory
661            .create_operator_manual(
662                vec![wrong.public],
663                "https://operator-pds.example",
664                &wrong.ed,
665                &wrong.pq,
666            )
667            .unwrap_err();
668        assert!(error
669            .to_string()
670            .contains("authenticated Hybrid deployment root"));
671    }
672
673    #[test]
674    fn classical_only_directory_binding_fails_closed() {
675        let (_store, directory, _authority) = fixture();
676        let user = keys(43);
677        let (did, genesis, mut binding) = self_service_artifacts(&user, "https://pds.example");
678        binding.signature.mldsa65.clear();
679
680        let error = directory
681            .create_self_service(&did, genesis, binding)
682            .unwrap_err();
683        assert!(format!("{error:#}").contains("ML-DSA-65 signature must be"));
684    }
685
686    #[test]
687    fn duplicate_genesis_is_rejected() {
688        let (_store, directory, _authority) = fixture();
689        let user = keys(9);
690        let (did, genesis, binding) = self_service_artifacts(&user, "https://pds.example");
691        directory
692            .create_self_service(&did, genesis.clone(), binding.clone())
693            .unwrap();
694
695        let error = directory
696            .create_self_service(&did, genesis, binding)
697            .unwrap_err();
698        assert!(error.to_string().contains("already exists"));
699    }
700
701    #[test]
702    fn stored_log_is_reverified_on_every_identity_resolution() {
703        let (store, directory, _authority) = fixture();
704        let user = keys(10);
705        let (did, genesis, binding) = self_service_artifacts(&user, "https://pds.example");
706        directory
707            .create_self_service(&did, genesis, binding)
708            .unwrap();
709
710        let mut records = store.records.write();
711        let record = records.get_mut(&did).unwrap();
712        let last = record.operation_log[0].len() - 1;
713        record.operation_log[0][last] ^= 1;
714        drop(records);
715
716        assert!(directory.resolve_identity(&did).is_err());
717    }
718
719    #[test]
720    fn stored_pds_binding_is_reverified_on_every_identity_resolution() {
721        let (store, directory, _authority) = fixture();
722        let user = keys(12);
723        let (did, genesis, binding) = self_service_artifacts(&user, "https://pds.example");
724        directory
725            .create_self_service(&did, genesis, binding)
726            .unwrap();
727
728        let mut records = store.records.write();
729        let record = records.get_mut(&did).unwrap();
730        let last = record.genesis_binding.len() - 1;
731        record.genesis_binding[last] ^= 1;
732        drop(records);
733
734        assert!(directory.resolve_identity(&did).is_err());
735    }
736
737    #[test]
738    fn connect_time_reach_is_live_and_never_stored_on_directory_row() {
739        let (store, directory, _authority) = fixture();
740        let user = keys(11);
741        let (did, genesis, binding) = self_service_artifacts(&user, "https://pds.example");
742        directory
743            .create_self_service(&did, genesis, binding)
744            .unwrap();
745
746        let first = directory.resolve(&did).unwrap();
747        let second = directory.resolve(&did).unwrap();
748        assert_ne!(first.cert_hash(), second.cert_hash());
749        assert_eq!(first.quic_url(), second.quic_url());
750
751        let stored = store.get(&did).unwrap().unwrap();
752        assert_eq!(stored.operation_log().len(), 1);
753        let binding = SignedPlcDirectoryGenesis::from_dag_cbor(stored.genesis_binding()).unwrap();
754        assert_eq!(binding.pds_endpoint(), "https://pds.example");
755        assert!(!stored
756            .genesis_binding()
757            .windows(b"certHash".len())
758            .any(|window| window == b"certHash"));
759    }
760}