Skip to main content

acdp_server/registry/
server.rs

1//! Logical registry handler (feature = "server").
2//!
3//! Wires [`PublishValidator`] together with a [`RegistryStore`] backend
4//! to provide the seven core registry operations enumerated in
5//! RFC-ACDP-0003 §2.1 and RFC-ACDP-0005:
6//!
7//! - capabilities — return the [`CapabilitiesDocument`].
8//! - publish — validate, verify signature, assign identifiers, persist.
9//! - retrieve — fetch a stored body + registry_state (visibility-filtered).
10//! - retrieve_body — fetch just the body (visibility-filtered).
11//! - lineage / current — lineage graph queries.
12//! - search — keyword + filter projection (visibility-filtered).
13//!
14//! This is the building block an HTTP-binding layer can sit on top of;
15//! the integration tests in this crate exercise it directly without
16//! mocking.
17//!
18//! # Conformant publish
19//!
20//! [`RegistryServer::publish_verified`] runs the full RFC-ACDP-0003 §2.1
21//! algorithm — structural validation, hash recomputation, DID resolution,
22//! signature verification — before persistence. It requires the `client`
23//! feature for [`acdp_did::WebResolver`].
24//!
25//! [`RegistryServer::publish_unverified_for_tests`] (and its
26//! idempotency/tenant-capable sibling
27//! [`RegistryServer::publish_unverified_in_tenant_for_tests`]) perform
28//! only steps 1–6 (skipping DID resolution + signature verification)
29//! and are intentionally **not** RFC-conformant; use only in tests
30//! where DID resolution would require a live network or mock server.
31//!
32//! [`RegistryServer::publish_pinned_verified_in_tenant_with_outcome`] (and
33//! [`RegistryServer::prove_publish_identity_pinned`]) are a third,
34//! distinct, RFC-conformant category — not a laxer variant of the
35//! `_unverified_for_tests` pair above. Steps 1–6 run here as usual; steps
36//! 7–8 (signature verification against a resolved key) are the *caller's*
37//! responsibility, already done before this method is reached, against an
38//! operator-pinned key rather than a live-resolved DID document. See that
39//! method's own doc comment for the full trust argument.
40
41use crate::registry::rate_limit::{NoopRateLimiter, RateLimiter};
42use crate::registry::store::RegistryStore;
43use crate::registry::validator::{
44    check_revocation_supersession, key_revocation_gate_applies, PublishValidator,
45};
46use acdp_primitives::error::AcdpError;
47use acdp_types::{
48    body::{Body, FullContext},
49    capabilities::CapabilitiesDocument,
50    primitives::{AgentDid, ContentHash, CtxId, LineageId, Status, Visibility},
51    publish::{PublishRequest, PublishResponse},
52    revocation::KeyRevocation,
53    search::{SearchParams, SearchResponse},
54};
55
56/// Logical registry handler over an arbitrary [`RegistryStore`].
57///
58/// `L` is the rate-limiting policy (RFC-ACDP-0008 §4.3). The default
59/// [`NoopRateLimiter`] accepts every publish; operators that need a
60/// real limiter construct via [`Self::with_rate_limiter`].
61pub struct RegistryServer<S: RegistryStore, L: RateLimiter = NoopRateLimiter> {
62    store: S,
63    caps: CapabilitiesDocument,
64    authority: String,
65    rate_limiter: L,
66    /// Receipt minting identity (ACDP 0.2, RFC-ACDP-0010). `None` =
67    /// 0.1.0-mode registry (no receipts). Set via
68    /// [`Self::with_receipt_signer`], which also advertises the
69    /// `acdp-registry-receipts` profile.
70    receipt_signer: Option<acdp_types::receipt::ReceiptSigner>,
71    /// Lineage-head receipt minting (ACDP 0.3, RFC-ACDP-0011). Enabled
72    /// via [`Self::with_lineage_head_receipts`], which also advertises
73    /// the `acdp-registry-head-receipts` profile. When enabled,
74    /// [`Self::current`] mints a fresh head receipt per response with
75    /// the RFC-ACDP-0010 receipt signing key. Never true without
76    /// `receipt_signer` (the profile's prerequisite).
77    mint_head_receipts: bool,
78    /// Lifecycle events & retraction (ACDP 0.3, RFC-ACDP-0013). Enabled
79    /// via [`Self::with_lifecycle`], which also advertises the
80    /// `acdp-registry-lifecycle` profile. When disabled, the lifecycle
81    /// operations return [`AcdpError::NotImplemented`] (the §6 rule for
82    /// non-advertising registries: HTTP 501) and the registry never
83    /// emits `lifecycle_events` or the `retracted` status.
84    lifecycle_enabled: bool,
85}
86
87/// Proof that a [`PublishRequest`]'s identity has been established —
88/// RFC-ACDP-0003 §2.1 steps 1–8 (schema/hash validation, DID resolution,
89/// signature verification) plus the RFC-ACDP-0014 §5 step 2 self-revocation
90/// check, whichever of those the request's `context_type` and the
91/// registry's `acdp_version` require — but nothing has been persisted yet.
92///
93/// Produced only by a successful [`RegistryServer::prove_publish_identity`] /
94/// [`RegistryServer::prove_publish_identity_did_key`] /
95/// [`RegistryServer::prove_publish_identity_pinned`] call — there is no
96/// public constructor, so a caller cannot manufacture one from an
97/// unverified request. Not [`Clone`]: a `Proven` that outlived its single
98/// intended [`RegistryServer::commit_proven`] call risks being committed
99/// twice against different tenants/idempotency keys, so this is a
100/// move-only, "prove once, commit once" value.
101///
102/// Borrows `req` rather than owning a clone — the did:web caller already
103/// holds an owned request across its `.await`, and the did:key caller
104/// already clones into its blocking closure, so an owned `Proven` would
105/// force a needless clone on the async path for no benefit on the sync
106/// one.
107#[derive(Debug)]
108pub struct Proven<'a> {
109    req: &'a PublishRequest,
110    fingerprint: Option<String>,
111    /// The `content_hash` recomputed over `req`'s `ProducerContent` during
112    /// proving (RFC-ACDP-0003 §2.1 step 4) — not exposed publicly, since
113    /// it is provably always equal to `req.content_hash` by the time a
114    /// `Proven` exists (a mismatch fails `prove_publish_identity*` with
115    /// [`AcdpError::HashMismatch`] first, and `req` — with its own `pub
116    /// content_hash` — is already reachable via [`Self::request`]).
117    /// [`RegistryServer::commit_proven`] asserts that invariant against it
118    /// in debug builds.
119    recomputed_hash: ContentHash,
120    authority: String,
121}
122
123impl<'a> Proven<'a> {
124    /// The request this proof was established for.
125    pub fn request(&self) -> &PublishRequest {
126        self.req
127    }
128
129    /// The producer's agent DID.
130    pub fn agent_id(&self) -> &AgentDid {
131        &self.req.agent_id
132    }
133
134    /// The verified producer key's fingerprint, when one was computed.
135    ///
136    /// Computed only when the registry has a receipt signer configured
137    /// (RFC-ACDP-0010) or `req` is a key-revocation subject to the
138    /// RFC-ACDP-0014 §5 step 2 self-sign check — `None` otherwise, exactly
139    /// mirroring the conditions the pre-`Proven` publish pipeline already
140    /// used to decide whether fingerprinting was worth its cost.
141    pub fn key_fingerprint(&self) -> Option<&str> {
142        self.fingerprint.as_deref()
143    }
144}
145
146impl<S: RegistryStore> RegistryServer<S, NoopRateLimiter> {
147    /// Unchecked constructor. Skips capabilities and DID-authority binding
148    /// validation; prefer [`Self::try_new`] in production. Retained for
149    /// tests that build a server from known-good fixtures.
150    #[doc(hidden)]
151    pub fn new(store: S, caps: CapabilitiesDocument, authority: impl Into<String>) -> Self {
152        Self {
153            store,
154            caps,
155            authority: authority.into(),
156            rate_limiter: NoopRateLimiter,
157            receipt_signer: None,
158            mint_head_receipts: false,
159            lifecycle_enabled: false,
160        }
161    }
162
163    /// Production constructor.
164    ///
165    /// Validates that `authority` is a bare lowercase DNS hostname,
166    /// validates capabilities against RFC-ACDP-0007 §3, and enforces that
167    /// `caps.registry_did` equals `did:web:<authority>` (per
168    /// RFC-ACDP-0006 §4.1 step 3 — the registry's DID document binds it
169    /// to the authority it claims).
170    ///
171    /// A `host:port`, scheme-prefixed, or uppercase authority is rejected:
172    /// the server uses `authority` to mint `ctx_id` (`acdp://<authority>/…`)
173    /// and `origin_registry`, and a colon or slash there violates the
174    /// `acdp://` URI authority rule (RFC-ACDP-0002 §3.1). For `host:port`
175    /// test setups use [`Self::try_new_for_test_authority`].
176    pub fn try_new(
177        store: S,
178        caps: CapabilitiesDocument,
179        authority: impl Into<String>,
180    ) -> Result<Self, AcdpError> {
181        let authority = authority.into();
182        // Production authority MUST be a bare lowercase DNS hostname — no
183        // port, no scheme, no DID prefix (RFC-ACDP-0002 §3.1).
184        if !acdp_types::primitives::is_valid_dns_authority(&authority) {
185            return Err(AcdpError::SchemaViolation(format!(
186                "registry authority '{authority}' is not a valid DNS hostname \
187                 (must be lowercase labels, e.g. 'registry.example.com'); \
188                 use RegistryServer::try_new_for_test_authority for host:port test setups"
189            )));
190        }
191        acdp_validation::validate_capabilities(&caps)?;
192        // BUG-06: percent-encode `:` in `host:port` authorities — the
193        // colon is a structural separator in did:web.
194        let expected_did = acdp_did::authority_to_did_web(&authority);
195        if caps.registry_did != expected_did {
196            return Err(AcdpError::SchemaViolation(format!(
197                "capabilities.registry_did '{}' does not match expected '{expected_did}' \
198                 for authority '{authority}'",
199                caps.registry_did
200            )));
201        }
202        Ok(Self {
203            store,
204            caps,
205            authority,
206            rate_limiter: NoopRateLimiter,
207            receipt_signer: None,
208            mint_head_receipts: false,
209            lifecycle_enabled: false,
210        })
211    }
212
213    /// Test-only constructor that accepts a `host:port` authority such as
214    /// `"localhost:8443"`. The authority is **not** validated as a DNS
215    /// hostname; capabilities and the DID binding are still checked.
216    ///
217    /// **Non-production only.** A server built with this constructor will
218    /// mint `ctx_id` and `origin_registry` values that do not conform to
219    /// the `acdp://` URI syntax rules (a colon in the authority segment).
220    /// Use [`Self::try_new`] for production registries.
221    #[doc(hidden)]
222    pub fn try_new_for_test_authority(
223        store: S,
224        caps: CapabilitiesDocument,
225        authority: impl Into<String>,
226    ) -> Result<Self, AcdpError> {
227        let authority = authority.into();
228        acdp_validation::validate_capabilities(&caps)?;
229        let expected_did = acdp_did::authority_to_did_web(&authority);
230        if caps.registry_did != expected_did {
231            return Err(AcdpError::SchemaViolation(format!(
232                "capabilities.registry_did '{}' does not match expected '{expected_did}' \
233                 for authority '{authority}'",
234                caps.registry_did
235            )));
236        }
237        Ok(Self {
238            store,
239            caps,
240            authority,
241            rate_limiter: NoopRateLimiter,
242            receipt_signer: None,
243            mint_head_receipts: false,
244            lifecycle_enabled: false,
245        })
246    }
247}
248
249impl<S: RegistryStore, L: RateLimiter> RegistryServer<S, L> {
250    /// Replace the rate-limiting policy (RFC-ACDP-0008 §4.3).
251    pub fn with_rate_limiter<L2: RateLimiter>(self, limiter: L2) -> RegistryServer<S, L2> {
252        RegistryServer {
253            store: self.store,
254            caps: self.caps,
255            authority: self.authority,
256            rate_limiter: limiter,
257            receipt_signer: self.receipt_signer,
258            mint_head_receipts: self.mint_head_receipts,
259            lifecycle_enabled: self.lifecycle_enabled,
260        }
261    }
262
263    /// Configure receipt minting (ACDP 0.2, RFC-ACDP-0010). Every
264    /// subsequent verified publish mints a registry-signed receipt
265    /// atomically with persistence, returns it in the publish response,
266    /// and serves it on retrieval.
267    ///
268    /// Also advertises the `acdp-registry-receipts` profile — a
269    /// registry without a signing key MUST NOT advertise it, so the
270    /// profile is bound to this call rather than to raw capabilities
271    /// input. Fails if the signer's `registry_did` does not match
272    /// `caps.registry_did` (a receipt minted under a foreign DID would
273    /// fail every consumer's serving-authority cross-check).
274    ///
275    /// Note: [`Self::publish_unverified_for_tests`] and
276    /// [`Self::publish_unverified_in_tenant_for_tests`] never mint — the
277    /// producer key is not resolved on either path, so a fingerprint
278    /// attestation would be false.
279    pub fn with_receipt_signer(
280        mut self,
281        signer: acdp_types::receipt::ReceiptSigner,
282    ) -> Result<Self, AcdpError> {
283        if signer.registry_did() != self.caps.registry_did {
284            return Err(AcdpError::SchemaViolation(format!(
285                "receipt signer registry_did '{}' ≠ capabilities.registry_did '{}'",
286                signer.registry_did(),
287                self.caps.registry_did
288            )));
289        }
290        // RFC-ACDP-0010 §11: registries advertising the receipts
291        // profile MUST advertise acdp_version >= 0.2.0.
292        self.require_min_acdp_version((0, 2, 0), "acdp-registry-receipts")?;
293        let profile = acdp_types::profile::Profile::RegistryReceipts.as_str();
294        if !self.caps.profiles.iter().any(|p| p == profile) {
295            self.caps.profiles.push(profile.to_string());
296        }
297        self.receipt_signer = Some(signer);
298        Ok(self)
299    }
300
301    /// Enable lineage-head receipt minting (ACDP 0.3, RFC-ACDP-0011).
302    /// Every subsequent [`Self::current`] response carries a freshly
303    /// minted head receipt (`as_of` = the registry clock at response
304    /// time, ms-truncated), signed with the RFC-ACDP-0010 receipt
305    /// signing key — head receipts introduce no new key role (§5, §8).
306    ///
307    /// Also advertises the `acdp-registry-head-receipts` profile. The
308    /// profile's prerequisite is `acdp-registry-receipts` (§9): this
309    /// method fails unless [`Self::with_receipt_signer`] was configured
310    /// first — a registry with no receipt key has nothing to sign head
311    /// receipts with, and MUST NOT advertise the profile (§6: no
312    /// degraded mode on `/current`). Registries advertising the profile
313    /// MUST advertise `acdp_version` >= 0.3.0 (§9).
314    pub fn with_lineage_head_receipts(mut self) -> Result<Self, AcdpError> {
315        if self.receipt_signer.is_none() {
316            return Err(AcdpError::SchemaViolation(
317                "acdp-registry-head-receipts requires the acdp-registry-receipts profile \
318                 (RFC-ACDP-0011 §9): call with_receipt_signer first"
319                    .into(),
320            ));
321        }
322        self.require_min_acdp_version((0, 3, 0), "acdp-registry-head-receipts")?;
323        let profile = acdp_types::profile::Profile::RegistryHeadReceipts.as_str();
324        if !self.caps.profiles.iter().any(|p| p == profile) {
325            self.caps.profiles.push(profile.to_string());
326        }
327        self.mint_head_receipts = true;
328        Ok(self)
329    }
330
331    /// Enable lifecycle events & retraction (ACDP 0.3, RFC-ACDP-0013).
332    /// Advertises the `acdp-registry-lifecycle` profile (prerequisite:
333    /// `acdp-registry-core`) and activates the
334    /// [`Self::retract_verified`] / [`Self::republish_verified`]
335    /// operation surface, the §7 status derivation (`retracted`
336    /// dominating `superseded` and `expired`), the §8.2 default-search
337    /// exclusion, and the §8.3 `/current` head exclusion.
338    ///
339    /// Registries advertising the profile MUST advertise `acdp_version`
340    /// ≥ 0.3.0 (§10). The paired [`RegistryStore`] must implement
341    /// [`RegistryStore::commit_lifecycle_event`] — the default trait
342    /// impl fails with `not_implemented`, so a mispaired backend fails
343    /// loudly on the first lifecycle write rather than silently
344    /// dropping a retraction.
345    pub fn with_lifecycle(mut self) -> Result<Self, AcdpError> {
346        self.require_min_acdp_version((0, 3, 0), "acdp-registry-lifecycle")?;
347        let profile = acdp_types::profile::Profile::RegistryLifecycle.as_str();
348        if !self.caps.profiles.iter().any(|p| p == profile) {
349            self.caps.profiles.push(profile.to_string());
350        }
351        self.lifecycle_enabled = true;
352        Ok(self)
353    }
354
355    /// Profile version gate: `capabilities.acdp_version` must be a plain
356    /// `MAJOR.MINOR.PATCH` version (the capabilities schema's
357    /// `^\d+\.\d+\.\d+$` form — malformed input is an error, never
358    /// coerced) and at least `min`.
359    fn require_min_acdp_version(&self, min: (u64, u64, u64), what: &str) -> Result<(), AcdpError> {
360        let parts: Vec<u64> = self
361            .caps
362            .acdp_version
363            .split('.')
364            .map(|p| p.parse::<u64>())
365            .collect::<Result<_, _>>()
366            .map_err(|_| {
367                AcdpError::SchemaViolation(format!(
368                    "capabilities.acdp_version '{}' is not a plain MAJOR.MINOR.PATCH version",
369                    self.caps.acdp_version
370                ))
371            })?;
372        let [major, minor, patch] = parts.as_slice() else {
373            return Err(AcdpError::SchemaViolation(format!(
374                "capabilities.acdp_version '{}' is not a plain MAJOR.MINOR.PATCH version",
375                self.caps.acdp_version
376            )));
377        };
378        if (*major, *minor, *patch) < min {
379            return Err(AcdpError::SchemaViolation(format!(
380                "{what} requires capabilities.acdp_version >= {}.{}.{}, got '{}'",
381                min.0, min.1, min.2, self.caps.acdp_version
382            )));
383        }
384        Ok(())
385    }
386
387    /// Borrow the underlying store. Useful for tests that want to
388    /// inspect side-effects directly.
389    pub fn store(&self) -> &S {
390        &self.store
391    }
392
393    /// `GET /.well-known/acdp.json`.
394    pub fn capabilities(&self) -> &CapabilitiesDocument {
395        &self.caps
396    }
397
398    /// **RFC-conformant publish.**
399    ///
400    /// Runs RFC-ACDP-0003 §2.1 steps 1–11:
401    ///
402    /// - **1–6.** [`PublishValidator::validate_post_schema`] — schema,
403    ///   payload + embedded size, hash recomputation, algorithm /
404    ///   key_id binding.
405    /// - **7–8.** [`acdp_verify::verify_publish_request_signature`] —
406    ///   DID resolution + signature verification.
407    /// - **9.** Identifier assignment (`ctx_id`, `lineage_id`).
408    /// - **10.** Lineage coherence on supersession.
409    /// - **11.** Persistence and predecessor supersession.
410    ///
411    /// Steps 7–8 require a [`acdp_did::WebResolver`], so this method
412    /// is gated on the `client` feature.
413    #[cfg(feature = "client")]
414    #[cfg_attr(
415        feature = "tracing",
416        tracing::instrument(
417            name = "acdp.publish_verified",
418            skip_all,
419            fields(
420                agent_id = req.agent_id.as_str(),
421                version = req.version,
422                idempotency_key = idempotency_key.is_some(),
423            ),
424            err(Display)
425        )
426    )]
427    pub async fn publish_verified(
428        &self,
429        req: &PublishRequest,
430        idempotency_key: Option<&str>,
431        resolver: &acdp_did::WebResolver,
432    ) -> Result<PublishResponse, AcdpError> {
433        self.publish_verified_in_tenant(req, idempotency_key, resolver, None)
434            .await
435    }
436
437    /// Like [`Self::publish_verified`] but binds the publish to a tenant so a
438    /// multi-tenant store persists `tenant_id` atomically with the context row
439    /// (rather than via a separate, non-transactional stamping UPDATE that a
440    /// crash could leave stranded in the default bucket).
441    ///
442    /// `tenant = None` behaves identically to [`Self::publish_verified`] —
443    /// but note this method returns the commit OUTCOME, not a bare
444    /// `PublishResponse`, so it is not a drop-in for it. The bare-response
445    /// equivalent is [`Self::publish_verified_in_tenant`].
446    ///
447    /// Which entry points have an outcome twin, and why the rest do not:
448    /// the three `*_in_tenant` publish forms do (this one, `did_key`, and
449    /// `pinned`), because those are the paths a registry front-end answers a
450    /// real `POST /contexts` through. The non-tenant forms do not — each is a
451    /// `(…, None)` delegate to its `_in_tenant` twin, so a caller wanting the
452    /// outcome passes `tenant = None`. `publish_unverified_in_tenant_for_tests`
453    /// does not either, deliberately: it skips DID resolution and signature
454    /// verification, is not an RFC-conformant publish path, and no registry
455    /// serves production traffic through it.
456    #[cfg(feature = "client")]
457    pub async fn publish_verified_in_tenant_with_outcome(
458        &self,
459        req: &PublishRequest,
460        idempotency_key: Option<&str>,
461        resolver: &acdp_did::WebResolver,
462        tenant: Option<&str>,
463    ) -> Result<crate::registry::store::PublishCommitOutcome, AcdpError> {
464        // FEAT-01: hand the rest of the pipeline to the store as a
465        // single atomic commit. Idempotency lookup, predecessor
466        // verification, body insertion, predecessor supersession
467        // marking, and idempotency record writing all happen under one
468        // critical section. Two concurrent publishes against the same
469        // `supersedes` (or the same `Idempotency-Key`) can no longer
470        // both succeed.
471        let proven = self.prove_publish_identity(req, resolver).await?;
472        self.commit_proven(proven, idempotency_key, tenant)
473    }
474
475    /// **Prove** a did:web producer's identity for `req` — RFC-ACDP-0003
476    /// §2.1 steps 1–8 (schema/hash validation, DID resolution, signature
477    /// verification) plus the RFC-ACDP-0014 §5 step 2 self-revocation
478    /// check — without persisting anything. Pair with
479    /// [`Self::commit_proven`] to complete the publish; the two together
480    /// are exactly what [`Self::publish_verified_in_tenant_with_outcome`]
481    /// composes.
482    #[cfg(feature = "client")]
483    pub async fn prove_publish_identity<'a>(
484        &self,
485        req: &'a PublishRequest,
486        resolver: &acdp_did::WebResolver,
487    ) -> Result<Proven<'a>, AcdpError> {
488        // Rate-limit gate runs before any expensive work — RFC-ACDP-0008 §4.3.
489        self.check_publish_rate_limit(&req.agent_id)?;
490
491        let raw_bytes = serde_json::to_vec(req)?.len();
492        let validator = PublishValidator::for_authority(&self.caps, &self.authority);
493        let validated = validator.validate_post_schema(req, raw_bytes)?;
494
495        // Steps 7–8: DID resolution + signature verification.
496        acdp_verify::verify_publish_request_signature(req, resolver).await?;
497
498        // RFC-ACDP-0014 §5 step 2 on the did:web publish path: a
499        // revocation MUST NOT be signed by the very key it revokes.
500        // `PublishValidator::validate_post_schema` (above) already
501        // enforces this for a did:key signer offline, purely from the
502        // body (`KeyRevocation::from_parts`'s did:key sub-case) — but a
503        // did:web signer's fingerprint is not derivable without
504        // resolving its DID document. That resolution already happened
505        // unconditionally just above, to verify the signature
506        // (RFC-ACDP-0003 steps 7–8) — so this is NOT a new resolution.
507        // `producer_key_fingerprint` dispatches by method
508        // internally, so a did:key signer reaching this line would be a
509        // harmless, resolver-free recheck of what was already enforced
510        // above; a did:web signer instead gets a second, cache-hit
511        // resolve of the same DID (via `WebResolver`'s LRU cache)
512        // purely to derive a fingerprint from the key that already
513        // verified — no new I/O, no new failure mode. Scoped to
514        // key-revocation bodies at `acdp_version >= 0.3.0` so no other
515        // publish pays even that cached-lookup cost.
516        let revocation_check_needed = req.context_type.is_key_revocation()
517            && key_revocation_gate_applies(&self.caps.acdp_version);
518
519        // RFC-ACDP-0010: fingerprint the key that was just resolved and
520        // verified, for the receipt's `key_fingerprint` binding. Also
521        // needed (and computed here, not a second time) when the §5
522        // step 2 check above applies, so a key-revocation publish never
523        // triggers two DID resolutions for one fingerprint.
524        let fingerprint = if self.receipt_signer.is_some() || revocation_check_needed {
525            Some(producer_key_fingerprint(req, resolver).await?)
526        } else {
527            None
528        };
529
530        if revocation_check_needed {
531            // `fingerprint` is `Some` here because `revocation_check_needed`
532            // was one of the two disjuncts in the `if` just above that
533            // decided whether to compute it — but that's a non-local
534            // invariant spanning several lines, so treat a `None` as a
535            // recoverable internal-state error rather than panicking the
536            // publish path (this crate is `forbid(unsafe_code)` and ships
537            // to crates.io; see `AcdpError::RegistryInternal`'s other use
538            // in this file for the same "impossible state" idiom).
539            let fp = fingerprint.as_deref().ok_or_else(|| {
540                AcdpError::RegistryInternal(
541                    "key-revocation fingerprint missing despite revocation_check_needed \
542                     — this is an internal invariant violation, not a caller error"
543                        .into(),
544                )
545            })?;
546            KeyRevocation::from_publish_request(req)?.check_not_self_signed(fp)?;
547        }
548
549        Ok(Proven {
550            req,
551            fingerprint,
552            recomputed_hash: validated.recomputed_hash,
553            authority: self.authority.clone(),
554        })
555    }
556
557    /// [`Self::publish_verified_in_tenant_with_outcome`] with the insert/replay
558    /// distinction discarded — see that method for the full contract, which is
559    /// otherwise identical. This form is a one-line delegate to it, so the two
560    /// cannot drift.
561    ///
562    /// Answering `POST /contexts` needs the twin: RFC-ACDP-0003 requires
563    /// `201 Created` + `Location` on a fresh publish and `200 OK` on a same-hash
564    /// retry (idem-002 says NOT 201), and this signature cannot express which
565    /// one happened.
566    #[cfg(feature = "client")]
567    pub async fn publish_verified_in_tenant(
568        &self,
569        req: &PublishRequest,
570        idempotency_key: Option<&str>,
571        resolver: &acdp_did::WebResolver,
572        tenant: Option<&str>,
573    ) -> Result<PublishResponse, AcdpError> {
574        self.publish_verified_in_tenant_with_outcome(req, idempotency_key, resolver, tenant)
575            .await
576            .map(|o| o.into_response())
577    }
578
579    /// **RFC-conformant publish for `did:key` producers — no resolver.**
580    ///
581    /// Runs the same RFC-ACDP-0003 §2.1 pipeline as
582    /// [`Self::publish_verified`], but performs steps 7–8 via the pure
583    /// did:key verifier
584    /// ([`acdp_verify::verify_publish_request_signature_offline`]),
585    /// so it is available without the `client` feature. Rejects
586    /// `did:web` (and any other method) producers with
587    /// `key_resolution_failed` — those need the resolver-backed
588    /// [`Self::publish_verified`].
589    ///
590    /// The capabilities gate still applies: the request is refused
591    /// unless `supported_did_methods` includes `"did:key"`.
592    pub fn publish_verified_did_key(
593        &self,
594        req: &PublishRequest,
595        idempotency_key: Option<&str>,
596    ) -> Result<PublishResponse, AcdpError> {
597        self.publish_verified_did_key_in_tenant(req, idempotency_key, None)
598    }
599
600    /// Like [`Self::publish_verified_did_key`] but binds the publish to a
601    /// tenant so a multi-tenant store persists `tenant_id` atomically with
602    /// the context row — the same contract as
603    /// [`Self::publish_verified_in_tenant`].
604    ///
605    /// `tenant = None` behaves identically to
606    /// [`Self::publish_verified_did_key`] — but note this method returns the
607    /// commit OUTCOME, not a bare `PublishResponse`, so it is not a drop-in
608    /// for it. The bare-response equivalent is
609    /// [`Self::publish_verified_did_key_in_tenant`].
610    #[cfg_attr(
611        feature = "tracing",
612        tracing::instrument(
613            name = "acdp.publish_verified_did_key",
614            skip_all,
615            fields(
616                agent_id = req.agent_id.as_str(),
617                version = req.version,
618                idempotency_key = idempotency_key.is_some(),
619            ),
620            err(Display)
621        )
622    )]
623    pub fn publish_verified_did_key_in_tenant_with_outcome(
624        &self,
625        req: &PublishRequest,
626        idempotency_key: Option<&str>,
627        tenant: Option<&str>,
628    ) -> Result<crate::registry::store::PublishCommitOutcome, AcdpError> {
629        let proven = self.prove_publish_identity_did_key(req)?;
630        self.commit_proven(proven, idempotency_key, tenant)
631    }
632
633    /// **Prove** a did:key producer's identity for `req` — RFC-ACDP-0003
634    /// §2.1 steps 1–8, pure (no resolver, no network) — without
635    /// persisting anything. Pair with [`Self::commit_proven`] to complete
636    /// the publish; the two together are exactly what
637    /// [`Self::publish_verified_did_key_in_tenant_with_outcome`] composes.
638    pub fn prove_publish_identity_did_key<'a>(
639        &self,
640        req: &'a PublishRequest,
641    ) -> Result<Proven<'a>, AcdpError> {
642        self.check_publish_rate_limit(&req.agent_id)?;
643
644        let raw_bytes = serde_json::to_vec(req)?.len();
645        let validator = PublishValidator::for_authority(&self.caps, &self.authority);
646        let validated = validator.validate_post_schema(req, raw_bytes)?;
647
648        // Steps 7–8, pure: did:key resolution + signature verification.
649        acdp_verify::verify_publish_request_signature_offline(req)?;
650
651        // did:key fingerprints are derivable from the DID itself — no
652        // resolver needed for the receipt binding.
653        let fingerprint = if self.receipt_signer.is_some() {
654            let material = acdp_did::key::resolve_did_key(req.agent_id.as_str())?;
655            Some(acdp_crypto::fingerprint::fingerprint_did_key_material(
656                &material,
657            )?)
658        } else {
659            None
660        };
661
662        Ok(Proven {
663            req,
664            fingerprint,
665            recomputed_hash: validated.recomputed_hash,
666            authority: self.authority.clone(),
667        })
668    }
669
670    /// [`Self::publish_verified_did_key_in_tenant_with_outcome`] with the insert/replay
671    /// distinction discarded — see that method for the full contract, which is
672    /// otherwise identical. This form is a one-line delegate to it, so the two
673    /// cannot drift.
674    ///
675    /// Answering `POST /contexts` needs the twin: RFC-ACDP-0003 requires
676    /// `201 Created` + `Location` on a fresh publish and `200 OK` on a same-hash
677    /// retry (idem-002 says NOT 201), and this signature cannot express which
678    /// one happened.
679    pub fn publish_verified_did_key_in_tenant(
680        &self,
681        req: &PublishRequest,
682        idempotency_key: Option<&str>,
683        tenant: Option<&str>,
684    ) -> Result<PublishResponse, AcdpError> {
685        self.publish_verified_did_key_in_tenant_with_outcome(req, idempotency_key, tenant)
686            .map(|o| o.into_response())
687    }
688
689    /// **NOT RFC-conformant.** Skips DID resolution and signature
690    /// verification (RFC-ACDP-0003 §2.1 steps 7–8).
691    ///
692    /// Intended for integration tests where DID resolution would require
693    /// a live network or mock server. Production callers MUST use
694    /// [`Self::publish_verified`].
695    ///
696    /// Delegates to [`Self::publish_unverified_in_tenant_for_tests`] with
697    /// no idempotency key and no tenant; use that method directly for an
698    /// idempotent-replay or tenant-stamped test publish.
699    #[doc(hidden)]
700    pub fn publish_unverified_for_tests(
701        &self,
702        req: &PublishRequest,
703    ) -> Result<PublishResponse, AcdpError> {
704        self.publish_unverified_in_tenant_for_tests(req, None, None)
705    }
706
707    /// Like [`Self::publish_unverified_for_tests`] but additionally
708    /// accepts an idempotency key and a tenant, so tests can exercise the
709    /// idempotent-replay and tenant-stamping behavior of
710    /// [`Self::commit_via_store`] without resorting to store-level
711    /// workarounds. `(None, None)` is identical to
712    /// [`Self::publish_unverified_for_tests`].
713    ///
714    /// **NOT RFC-conformant** — same caveats as
715    /// [`Self::publish_unverified_for_tests`]: skips RFC-ACDP-0003 §2.1
716    /// steps 7–8 (DID resolution + signature verification). Production
717    /// callers MUST use [`Self::publish_verified_in_tenant`].
718    ///
719    /// Passing an idempotency key to a registry whose capabilities don't
720    /// advertise `supports_idempotency_key` is a silent no-op — mirrors
721    /// [`Self::publish_verified_in_tenant`]'s contract via the shared
722    /// [`Self::commit_via_store`] gate.
723    #[doc(hidden)]
724    pub fn publish_unverified_in_tenant_for_tests(
725        &self,
726        req: &PublishRequest,
727        idempotency_key: Option<&str>,
728        tenant: Option<&str>,
729    ) -> Result<PublishResponse, AcdpError> {
730        // Rate-limit gate fires here too — the limiter is intentionally
731        // wired BEFORE validation so it works as a defensive cap even
732        // when the test path is used.
733        self.check_publish_rate_limit(&req.agent_id)?;
734
735        // RFC-ACDP-0010 §7: a receipts-advertising registry has no
736        // degraded mode — every persisted context must carry a receipt,
737        // and minting here would attest a `key_fingerprint` that was
738        // never resolved. Refuse outright rather than persist a
739        // receipt-less context — from either unverified test entry
740        // point, since neither resolves a producer key.
741        if self.receipt_signer.is_some() {
742            return Err(AcdpError::SchemaViolation(
743                "publish_unverified_for_tests / publish_unverified_in_tenant_for_tests are \
744                 unavailable on a receipts-advertising registry (RFC-ACDP-0010 §7: no \
745                 degraded mode); use publish_verified or publish_verified_did_key"
746                    .into(),
747            ));
748        }
749        // RFC-ACDP-0014 §5 step 2 is deliberately NOT extended here for
750        // a did:web signer: this method's entire contract (see its doc
751        // comment above) is to skip DID resolution + signature
752        // verification, so there is no resolved key — and no
753        // resolver — to fingerprint. `validate_post_schema` below still
754        // enforces the did:key sub-case offline (`KeyRevocation::from_parts`),
755        // since that needs no resolution either; a did:web self-revocation
756        // published through this test-only bypass is not caught until a
757        // conformant path re-verifies it.
758        let raw_bytes = serde_json::to_vec(req)?.len();
759        let validator = PublishValidator::for_authority(&self.caps, &self.authority);
760        let _validated = validator.validate_post_schema(req, raw_bytes)?;
761        self.commit_via_store(req, idempotency_key, tenant, None)
762            .map(|o| o.into_response())
763    }
764
765    /// **Publish already verified by the caller against an
766    /// operator-pinned key** (e.g. a demo/playground registry's
767    /// out-of-band pinned-key allowlist — a config-supplied public key
768    /// checked instead of a live-resolved DID document).
769    ///
770    /// Unlike [`Self::publish_unverified_for_tests`], this is safe to call
771    /// on a receipts-advertising registry: the caller has ALREADY
772    /// cryptographically verified `req`'s signature against
773    /// `verified_public_key_b64` before calling this method (steps 7–8 are
774    /// the caller's responsibility, not this method's — there is no DID
775    /// document or did:key to resolve for a pinned key, so this crate has
776    /// nothing further to verify), so the fingerprint of that key can be
777    /// attested in the minted receipt (RFC-ACDP-0010 §7: no degraded mode,
778    /// every persisted context must carry a receipt with a genuinely
779    /// resolved key_fingerprint).
780    ///
781    /// `verified_algorithm` MUST be `"ed25519"` or `"ecdsa-p256"` and MUST
782    /// be the algorithm the caller actually verified `verified_public_key_b64`
783    /// against — this method trusts the caller completely for verification;
784    /// it does not re-verify the signature itself, only recomputes the
785    /// fingerprint of the key the caller names.
786    pub fn publish_pinned_verified_in_tenant_with_outcome(
787        &self,
788        req: &PublishRequest,
789        idempotency_key: Option<&str>,
790        tenant: Option<&str>,
791        verified_public_key_b64: &str,
792        verified_algorithm: &str,
793    ) -> Result<crate::registry::store::PublishCommitOutcome, AcdpError> {
794        let proven =
795            self.prove_publish_identity_pinned(req, verified_public_key_b64, verified_algorithm)?;
796        self.commit_proven(proven, idempotency_key, tenant)
797    }
798
799    /// **Prove** an operator-pinned-key producer's identity for `req` —
800    /// RFC-ACDP-0003 §2.1 steps 1–6 plus the RFC-ACDP-0014 §5 step 2
801    /// self-revocation check (steps 7–8 are the CALLER's responsibility —
802    /// see the doc comment on
803    /// [`Self::publish_pinned_verified_in_tenant_with_outcome`]) — without
804    /// persisting anything. Pair with [`Self::commit_proven`] to complete
805    /// the publish; the two together are exactly what
806    /// [`Self::publish_pinned_verified_in_tenant_with_outcome`] composes.
807    pub fn prove_publish_identity_pinned<'a>(
808        &self,
809        req: &'a PublishRequest,
810        verified_public_key_b64: &str,
811        verified_algorithm: &str,
812    ) -> Result<Proven<'a>, AcdpError> {
813        self.check_publish_rate_limit(&req.agent_id)?;
814
815        let raw_bytes = serde_json::to_vec(req)?.len();
816        let validator = PublishValidator::for_authority(&self.caps, &self.authority);
817        let validated = validator.validate_post_schema(req, raw_bytes)?;
818
819        // RFC-ACDP-0014 §5 step 2 applies here too, and at no extra
820        // resolution cost: `verified_public_key_b64` is the key the
821        // *caller* already verified the signature against — there is
822        // no DID document to fetch, so fingerprinting it is a pure,
823        // local computation regardless of receipt minting. Unlike the
824        // did:web hook in `prove_publish_identity`, this adds no new I/O.
825        let revocation_check_needed = req.context_type.is_key_revocation()
826            && key_revocation_gate_applies(&self.caps.acdp_version);
827
828        let fingerprint = if self.receipt_signer.is_some() || revocation_check_needed {
829            Some(fingerprint_pinned_key(
830                verified_public_key_b64,
831                verified_algorithm,
832            )?)
833        } else {
834            None
835        };
836
837        if revocation_check_needed {
838            // See the identical guard in `prove_publish_identity` for why
839            // this is `ok_or_else` rather than `expect`: the `Some`-ness
840            // of `fingerprint` here depends on the `if` a few lines above
841            // matching this same `revocation_check_needed`, a non-local
842            // invariant that shouldn't panic the publish path if it's
843            // ever broken by a future edit.
844            let fp = fingerprint.as_deref().ok_or_else(|| {
845                AcdpError::RegistryInternal(
846                    "key-revocation fingerprint missing despite revocation_check_needed \
847                     — this is an internal invariant violation, not a caller error"
848                        .into(),
849                )
850            })?;
851            KeyRevocation::from_publish_request(req)?.check_not_self_signed(fp)?;
852        }
853
854        Ok(Proven {
855            req,
856            fingerprint,
857            recomputed_hash: validated.recomputed_hash,
858            authority: self.authority.clone(),
859        })
860    }
861
862    /// [`Self::publish_pinned_verified_in_tenant_with_outcome`] with the insert/replay
863    /// distinction discarded — see that method for the full contract, which is
864    /// otherwise identical. This form is a one-line delegate to it, so the two
865    /// cannot drift.
866    ///
867    /// `#[doc(hidden)]`, as it was before the twin was split out — splitting a
868    /// method must not quietly publish a deliberately hidden one. Its twin is
869    /// NOT hidden, and that asymmetry is deliberate: a registry front-end has
870    /// to call the twin to answer `201` vs `200` correctly, so it needs to be
871    /// discoverable in rustdoc and tracked by `cargo semver-checks`.
872    ///
873    /// Answering `POST /contexts` needs the twin: RFC-ACDP-0003 requires
874    /// `201 Created` + `Location` on a fresh publish and `200 OK` on a same-hash
875    /// retry (idem-002 says NOT 201), and this signature cannot express which
876    /// one happened.
877    #[doc(hidden)]
878    pub fn publish_pinned_verified_in_tenant(
879        &self,
880        req: &PublishRequest,
881        idempotency_key: Option<&str>,
882        tenant: Option<&str>,
883        verified_public_key_b64: &str,
884        verified_algorithm: &str,
885    ) -> Result<PublishResponse, AcdpError> {
886        self.publish_pinned_verified_in_tenant_with_outcome(
887            req,
888            idempotency_key,
889            tenant,
890            verified_public_key_b64,
891            verified_algorithm,
892        )
893        .map(|o| o.into_response())
894    }
895
896    /// Rate-limit gate shared by every publish path (RFC-ACDP-0008 §4.3).
897    /// Under the `tracing` feature a rejection emits a structured warn
898    /// event so operators can see limiter hits per agent.
899    fn check_publish_rate_limit(
900        &self,
901        agent_id: &acdp_types::primitives::AgentDid,
902    ) -> Result<(), AcdpError> {
903        match self.rate_limiter.check_publish(agent_id) {
904            Ok(()) => Ok(()),
905            Err(e) => {
906                #[cfg(feature = "tracing")]
907                tracing::warn!(
908                    agent_id = agent_id.as_str(),
909                    "publish rejected by rate limiter"
910                );
911                Err(e)
912            }
913        }
914    }
915
916    /// Drive `RegistryStore::commit_publish` from a validated request.
917    ///
918    /// Returns the `PublishCommitOutcome` **whole**. It used to unwrap both
919    /// variants to the same `PublishResponse` here, on the grounds that the
920    /// distinction "only matters internally for logging/tracing" — that was
921    /// wrong. A registry front-end needs it to answer `201 Created` on a
922    /// fresh publish and `200 OK` on an idempotent replay, and flattening it
923    /// at this layer made that undecidable for every caller: three of the
924    /// four publish paths in `acdp-registry-rs` had no way to tell a replay
925    /// from an insert and would have answered `201` to both.
926    ///
927    /// Callers that genuinely do not care unwrap with
928    /// [`PublishCommitOutcome::into_response`].
929    fn commit_via_store(
930        &self,
931        req: &PublishRequest,
932        idempotency_key: Option<&str>,
933        tenant: Option<&str>,
934        producer_key_fingerprint: Option<String>,
935    ) -> Result<crate::registry::store::PublishCommitOutcome, AcdpError> {
936        let idempotency = if self.caps.supports_idempotency_key {
937            idempotency_key.map(|key| crate::registry::store::PendingIdempotencyCommit {
938                key,
939                ttl: chrono::Duration::seconds(
940                    self.caps
941                        .limits
942                        .idempotency_key_ttl_seconds
943                        .unwrap_or(86_400) as i64,
944                ),
945            })
946        } else {
947            None
948        };
949        // RFC-ACDP-0010 minting hook — runs inside the store's critical
950        // section so the receipt persists atomically with the context.
951        #[allow(clippy::type_complexity)]
952        let minter: Option<
953            Box<dyn Fn(&Body) -> Result<serde_json::Value, AcdpError> + Send + Sync>,
954        > = match (&self.receipt_signer, producer_key_fingerprint) {
955            (Some(signer), Some(fp)) => Some(Box::new(move |body: &Body| {
956                let receipt = signer.mint(
957                    &body.ctx_id,
958                    &body.lineage_id,
959                    &body.origin_registry,
960                    body.created_at,
961                    &body.content_hash,
962                    &fp,
963                )?;
964                serde_json::to_value(receipt).map_err(AcdpError::from)
965            })),
966            _ => None,
967        };
968        // Keyed on the COMMITTING server's own config, not on whether
969        // `minter` happened to build — `minter` also depends on
970        // `producer_key_fingerprint`, which a caller external to this
971        // method controls (see `commit_proven`'s own additional guard for
972        // the specific case this protects against: a `Proven` established
973        // against a different, differently-configured `RegistryServer`
974        // instance that merely shares this one's `authority` string). A
975        // receipts-advertising registry with no fingerprint to mint from
976        // must still fail the §7 check below, not silently skip it.
977        let minted_expected = self.receipt_signer.is_some();
978
979        // RFC-ACDP-0014 §4 `supersedes`-row admission hook. `Some` iff
980        // the version gate is on AND this request actually carries a
981        // `supersedes` — the mandatory carry-forward from Phase 5:
982        // `check_revocation_supersession` has no internal version
983        // guard, so calling it unconditionally would reject a
984        // key-revocation-shaped body at e.g. acdp_version 0.2.0, where
985        // RFC §4:60 reserves that rejection for ≥0.3.0 registries.
986        //
987        // Captures `req` by reference (not `move`-owned data like
988        // `receipt_minter` above) so it can call
989        // `check_revocation_supersession(prev, req, acdp_version)` — the
990        // closure's hidden lifetime is exactly `req`'s, which the store
991        // threads through the same call as `PublishCommit::req`, so the
992        // two `'a`-tied fields agree. `acdp_version` is threaded through
993        // too (RFC-ACDP-0014 §10) so Arm 3 can pick its error code —
994        // `self.caps.acdp_version` outlives the closure via `self`.
995        let admission_closure =
996            if key_revocation_gate_applies(&self.caps.acdp_version) && req.supersedes.is_some() {
997                Some(move |prev: &Body| {
998                    check_revocation_supersession(prev, req, &self.caps.acdp_version)
999                })
1000            } else {
1001                None
1002            };
1003        #[allow(clippy::type_complexity)]
1004        let predecessor_admission: Option<
1005            &(dyn Fn(&Body) -> Result<(), AcdpError> + Send + Sync),
1006        > = admission_closure
1007            .as_ref()
1008            .map(|f| f as &(dyn Fn(&Body) -> Result<(), AcdpError> + Send + Sync));
1009
1010        let outcome = self
1011            .store
1012            .commit_publish(crate::registry::store::PublishCommit {
1013                req,
1014                authority: &self.authority,
1015                idempotency,
1016                tenant,
1017                receipt_minter: minter.as_deref(),
1018                predecessor_admission,
1019            })?;
1020        // Borrow rather than move: the tracing fields and the RFC-ACDP-0010
1021        // §7 check below both only read, and `outcome` is returned whole.
1022        let (response, replayed) = match &outcome {
1023            crate::registry::store::PublishCommitOutcome::Inserted(r) => (r, false),
1024            crate::registry::store::PublishCommitOutcome::IdempotentReplay(r) => (r, true),
1025        };
1026        #[cfg(feature = "tracing")]
1027        tracing::debug!(
1028            ctx_id = %response.ctx_id.0,
1029            lineage_id = %response.lineage_id.0,
1030            version = response.version,
1031            replayed,
1032            "publish committed"
1033        );
1034        // RFC-ACDP-0010 §7 belt-and-braces: a receipts-advertising
1035        // registry has no degraded mode. A store implementation that
1036        // ignores `receipt_minter` (e.g. compiled against the older
1037        // trait shape) must fail loudly here, not silently persist a
1038        // receipt-less context.
1039        //
1040        // Scoped to NEWLY INSERTED contexts only: an idempotent replay
1041        // returns the ORIGINAL publish response verbatim, and that
1042        // original may legitimately predate receipts (a record minted
1043        // before the registry enabled its signer, still inside the
1044        // idempotency TTL). Failing such a replay would turn a correct
1045        // producer retry into a 500 across the upgrade boundary — §7
1046        // attests what was persisted at publish time, not re-mint time.
1047        if minted_expected && !replayed && response.registry_receipt.is_none() {
1048            return Err(AcdpError::RegistryInternal(
1049                "receipt signer is configured but the store returned no receipt — \
1050                 the RegistryStore implementation must invoke PublishCommit::receipt_minter \
1051                 inside its commit (RFC-ACDP-0010 §7: no degraded mode)"
1052                    .into(),
1053            ));
1054        }
1055        Ok(outcome)
1056    }
1057
1058    /// **Commit** a [`Proven`] publish — the second half of the
1059    /// `prove → commit` split (`prove_publish_identity*` /
1060    /// `commit_proven`, #273). Everything through RFC-ACDP-0003 §2.1
1061    /// steps 1–8 (and the RFC-ACDP-0014 §5 step 2 self-revocation check,
1062    /// where applicable) already passed to produce `proven` — this call
1063    /// runs the same atomic store commit
1064    /// (idempotency lookup, predecessor verification, insertion,
1065    /// predecessor-supersession marking) that
1066    /// [`Self::publish_verified_in_tenant_with_outcome`] and its siblings
1067    /// have always run, just reachable without re-deriving identity.
1068    ///
1069    /// Rejects a `proven` minted for a different registry authority with
1070    /// [`AcdpError::RegistryInternal`] rather than silently committing
1071    /// under the wrong one — a `Proven` carries the authority it was
1072    /// proved against specifically so this cross-registry mismatch is
1073    /// cheap to catch here, before persistence.
1074    pub fn commit_proven(
1075        &self,
1076        proven: Proven<'_>,
1077        idempotency_key: Option<&str>,
1078        tenant: Option<&str>,
1079    ) -> Result<crate::registry::store::PublishCommitOutcome, AcdpError> {
1080        if proven.authority != self.authority {
1081            return Err(AcdpError::RegistryInternal(format!(
1082                "commit_proven: Proven was established against authority '{}', but this \
1083                 registry's authority is '{}' — refusing to commit a proof against the \
1084                 wrong registry",
1085                proven.authority, self.authority
1086            )));
1087        }
1088        // The authority string alone is not a full registry-instance
1089        // identity check: two `RegistryServer`s can legitimately (or by
1090        // misconfiguration) share an `authority` while differing in
1091        // `receipt_signer`. Catch the dangerous direction explicitly —
1092        // proving against a signer-less instance, then committing on a
1093        // receipts-advertising one — here, with a message that names the
1094        // actual mistake, rather than relying solely on the generic §7
1095        // belt-and-braces check inside `commit_via_store` to catch it.
1096        if self.receipt_signer.is_some() && proven.fingerprint.is_none() {
1097            return Err(AcdpError::RegistryInternal(
1098                "commit_proven: this registry requires receipts (a receipt_signer is \
1099                 configured) but the Proven carries no producer key fingerprint — it was \
1100                 most likely established via a different RegistryServer instance (one with \
1101                 no receipt_signer configured) that happens to share this one's authority; \
1102                 refusing to commit rather than silently persist a receipt-less context \
1103                 (RFC-ACDP-0010 §7: no degraded mode)"
1104                    .into(),
1105            ));
1106        }
1107        debug_assert_eq!(
1108            proven.recomputed_hash, proven.req.content_hash,
1109            "Proven's recomputed_hash must always equal its request's content_hash by \
1110             construction — prove_publish_identity* fails closed with HashMismatch before \
1111             a Proven can exist otherwise"
1112        );
1113        self.commit_via_store(proven.req, idempotency_key, tenant, proven.fingerprint)
1114    }
1115
1116    /// `GET /contexts/{ctx_id}`.
1117    ///
1118    /// Applies the RFC-ACDP-0008 §4.5 disclosure rules:
1119    ///
1120    /// | Visibility   | Authorized requester for retrieval                  |
1121    /// |--------------|-----------------------------------------------------|
1122    /// | `public`     | anyone (when `caps.anonymous_public_reads` is true) |
1123    /// | `restricted` | producer (`agent_id`) **or** any DID in `audience`  |
1124    /// | `private`    | producer (`agent_id`) **or** any DID in `audience`  |
1125    ///
1126    /// Returns `Ok(None)` (not `Err`) for unauthorized callers — prevents
1127    /// existence leakage via error codes.
1128    pub fn retrieve(
1129        &self,
1130        ctx_id: &CtxId,
1131        requester: Option<&AgentDid>,
1132    ) -> Result<Option<FullContext>, AcdpError> {
1133        let Some(ctx) = self.store.get(ctx_id)? else {
1134            return Ok(None);
1135        };
1136        if !can_retrieve(&ctx.body, requester, &self.caps) {
1137            return Ok(None);
1138        }
1139        Ok(Some(ctx))
1140    }
1141
1142    /// `GET /contexts/{ctx_id}/body`. See [`Self::retrieve`] for visibility rules.
1143    pub fn retrieve_body(
1144        &self,
1145        ctx_id: &CtxId,
1146        requester: Option<&AgentDid>,
1147    ) -> Result<Option<Body>, AcdpError> {
1148        Ok(self.retrieve(ctx_id, requester)?.map(|c| c.body))
1149    }
1150
1151    /// `GET /lineages/{lineage_id}`.
1152    ///
1153    /// BUG-03: applies the same visibility filter as `retrieve`. A
1154    /// caller who knows or guesses a `lineage_id` must not be able to
1155    /// surface restricted or private bodies through the lineage
1156    /// endpoint when `retrieve(ctx_id, requester)` would deny them.
1157    pub fn lineage(
1158        &self,
1159        lineage_id: &LineageId,
1160        requester: Option<&AgentDid>,
1161    ) -> Result<Vec<FullContext>, AcdpError> {
1162        let all = self.store.lineage(lineage_id)?;
1163        Ok(all
1164            .into_iter()
1165            .filter(|ctx| can_retrieve(&ctx.body, requester, &self.caps))
1166            .collect())
1167    }
1168
1169    /// `GET /lineages/{lineage_id}/current`.
1170    ///
1171    /// BUG-03 + BUG-04: returns the newest version visible to the
1172    /// requester that is neither `Superseded` nor `Retracted` (a
1173    /// retracted version is NEVER a head — RFC-ACDP-0013 §8.3, fixture
1174    /// `lc-003`; contrast `Expired`, which remains a servable head).
1175    /// `None` when the lineage is unknown, when every version is
1176    /// superseded or retracted (RFC-ACDP-0004 §5 as amended), or when
1177    /// no visible version exists. Because head selection excludes
1178    /// retracted versions, a lineage-head receipt can never name a
1179    /// retracted head (RFC-ACDP-0011 §4 as amended; the signer's mint
1180    /// refusal is the backstop).
1181    ///
1182    /// When the registry advertises `acdp-registry-head-receipts`
1183    /// ([`Self::with_lineage_head_receipts`]), the response carries a
1184    /// freshly minted lineage-head receipt (RFC-ACDP-0011 §6 rule 1:
1185    /// REQUIRED on `/current`, no degraded mode). Because the head is
1186    /// resolved *after* visibility filtering, the receipt attests the
1187    /// head as visible to this requester (§4: never an existence leak).
1188    pub fn current(
1189        &self,
1190        lineage_id: &LineageId,
1191        requester: Option<&AgentDid>,
1192    ) -> Result<Option<FullContext>, AcdpError> {
1193        let all = self.store.lineage(lineage_id)?;
1194        // `lineage` returns versions ordered from v1 → vN; iterate in
1195        // reverse to find the newest non-superseded version. `Active`
1196        // and `Expired` both qualify as valid current heads (a body
1197        // that expired without being superseded is still the latest
1198        // and the consumer needs to see it to know it has lapsed).
1199        for mut ctx in all.into_iter().rev() {
1200            if !matches!(
1201                ctx.registry_state.status,
1202                Status::Superseded | Status::Retracted
1203            ) && can_retrieve(&ctx.body, requester, &self.caps)
1204            {
1205                if self.mint_head_receipts {
1206                    // RFC-ACDP-0011 §6: as_of is the registry's clock at
1207                    // response time (ms-truncated by the signer); the
1208                    // head fields are exactly the served response's, so
1209                    // the §7 step 5 byte-match holds by construction.
1210                    let signer = self.receipt_signer.as_ref().ok_or_else(|| {
1211                        AcdpError::RegistryInternal(
1212                            "head-receipt minting enabled without a receipt signer \
1213                             (RFC-ACDP-0011 §9 prerequisite violated)"
1214                                .into(),
1215                        )
1216                    })?;
1217                    let receipt = signer.mint_lineage_head(
1218                        lineage_id,
1219                        &ctx.body.ctx_id,
1220                        ctx.body.version,
1221                        &ctx.registry_state.status,
1222                        chrono::Utc::now(),
1223                    )?;
1224                    ctx.lineage_head_receipt = Some(serde_json::to_value(receipt)?);
1225                }
1226                return Ok(Some(ctx));
1227            }
1228        }
1229        Ok(None)
1230    }
1231
1232    /// `GET /contexts/search`.
1233    ///
1234    /// Applies the RFC-ACDP-0008 §4.5 search disclosure rules (note the
1235    /// asymmetry vs retrieval): private contexts surface in search only
1236    /// to their producer (audience members must already know the ctx_id).
1237    ///
1238    /// When `caps.anonymous_public_reads` is `false`, an anonymous search
1239    /// request is rejected outright with [`AcdpError::NotAuthorized`]
1240    /// (HTTP 403) rather than returning an empty `200`. An empty result
1241    /// set would still leak the registry's existence and confirm that
1242    /// the keyword query ran; the required response is `not_authorized`
1243    /// (RFC-ACDP-0005 §2.5.5, RFC-ACDP-0008 §6.3, fixture `vis-009`).
1244    pub fn search(
1245        &self,
1246        params: &SearchParams,
1247        requester: Option<&AgentDid>,
1248    ) -> Result<SearchResponse, AcdpError> {
1249        // BUG-01 + vis-009: reject anonymous search when the registry
1250        // does not allow anonymous reads. An empty 200 would still leak
1251        // the registry's existence (and that the query executed); the
1252        // normative response is 403 not_authorized.
1253        if requester.is_none() && !self.caps.anonymous_public_reads {
1254            return Err(AcdpError::NotAuthorized(
1255                "anonymous search requires authentication \
1256                 (registry caps: anonymous_public_reads=false)"
1257                    .into(),
1258            ));
1259        }
1260        // BUG-02: pass `anonymous_public_reads` to the store so search
1261        // and retrieve agree. A registry advertising the flag as false
1262        // MUST suppress public contexts for anonymous callers in BOTH
1263        // endpoints (RFC-ACDP-0008 §4.5).
1264        self.store
1265            .search(params, requester, self.caps.anonymous_public_reads)
1266    }
1267
1268    // ── Lifecycle events & retraction (ACDP 0.3, RFC-ACDP-0013 §6) ──────
1269    //
1270    // The logical handlers behind `POST /contexts/{ctx_id}/retract` and
1271    // `POST /contexts/{ctx_id}/republish`. An HTTP binding layer should
1272    // first run the raw request body through
1273    // [`crate::registry::lifecycle::parse_lifecycle_request`] (the
1274    // closed-envelope / `immutable_field` check of §6 step 2, fixture
1275    // `lc-002`), then hand the parsed event here. The typed
1276    // [`acdp_types::lifecycle::LifecycleEvent`] round-trips
1277    // byte-identically, so signature verification over its
1278    // re-serialization equals verification over the received bytes.
1279
1280    /// §6 steps 1–3, shared by both endpoints and all verification
1281    /// modes (signature *verification* itself is the caller's step —
1282    /// it differs by DID method):
1283    ///
1284    /// 1. **Visibility first** (RFC-ACDP-0008 §4.5): a context the
1285    ///    requester could not retrieve yields `not_found` — lifecycle
1286    ///    endpoints never leak existence, and error ordering never lets
1287    ///    an unauthorized caller distinguish "exists but not yours".
1288    /// 2. **Event validation**: closed §4 semantics, the
1289    ///    endpoint-binding rule (`retracted` on `/retract`,
1290    ///    `republished` on `/republish` — which also excludes every
1291    ///    unregistered `event_type`, §7.3), and the future-`occurred_at`
1292    ///    rejection (120 s skew allowance, §4).
1293    /// 3. **Actor authentication**: `actor` MUST equal `body.agent_id`
1294    ///    (`not_authorized` — the supersession rule of RFC-ACDP-0003
1295    ///    §3.1 step 3; delegation remains out of scope) and the event
1296    ///    MUST be signed (`schema_violation` when missing, §5).
1297    ///
1298    /// Returns the resolved context for the caller's verification step.
1299    fn lifecycle_precheck(
1300        &self,
1301        event: &acdp_types::lifecycle::LifecycleEvent,
1302        expected_type: &acdp_types::lifecycle::LifecycleEventType,
1303        requester: Option<&AgentDid>,
1304    ) -> Result<FullContext, AcdpError> {
1305        if !self.lifecycle_enabled {
1306            return Err(AcdpError::NotImplemented(
1307                "this registry does not advertise acdp-registry-lifecycle \
1308                 (RFC-ACDP-0013 §6: lifecycle endpoints are not implemented)"
1309                    .into(),
1310            ));
1311        }
1312        // Step 1 — resolve + visibility before ANY other check.
1313        let ctx = self
1314            .retrieve(&event.ctx_id, requester)?
1315            .ok_or_else(|| AcdpError::NotFound(format!("context '{}' not found", event.ctx_id)))?;
1316        // Step 2 — event validation.
1317        event.validate()?;
1318        if &event.event_type != expected_type {
1319            return Err(AcdpError::SchemaViolation(format!(
1320                "event_type '{}' does not match this endpoint (expected '{}', \
1321                 RFC-ACDP-0013 §6 step 2)",
1322                event.event_type, expected_type
1323            )));
1324        }
1325        let now = chrono::Utc::now();
1326        if event.occurred_at > now + chrono::Duration::seconds(120) {
1327            return Err(AcdpError::SchemaViolation(format!(
1328                "event occurred_at '{}' is in the future beyond the 120s skew allowance \
1329                 (RFC-ACDP-0013 §4)",
1330                event.occurred_at.format("%Y-%m-%dT%H:%M:%S%.3fZ")
1331            )));
1332        }
1333        // Step 3 — actor authentication.
1334        if event.actor != ctx.body.agent_id {
1335            return Err(AcdpError::NotAuthorized(format!(
1336                "event actor '{}' is not the context's producer — only the producer \
1337                 (agent_id) may use the lifecycle endpoints (RFC-ACDP-0013 §6 step 3)",
1338                event.actor
1339            )));
1340        }
1341        // Producer-initiated events MUST be signed (§5); presence and
1342        // the key_id-DID == actor binding are checked here, the
1343        // cryptographic verification by the caller.
1344        event.actor_bound_signature()?;
1345        Ok(ctx)
1346    }
1347
1348    /// §6 steps 4–5: atomic transition + append via the store, mapping
1349    /// both outcomes (fresh append, byte-identical idempotent retry) to
1350    /// the post-transition full-retrieval envelope.
1351    fn lifecycle_commit(
1352        &self,
1353        event: &acdp_types::lifecycle::LifecycleEvent,
1354    ) -> Result<FullContext, AcdpError> {
1355        Ok(self.store.commit_lifecycle_event(event)?.into_context())
1356    }
1357
1358    /// Shared verified pipeline for both endpoints (resolver-backed).
1359    #[cfg(feature = "client")]
1360    async fn lifecycle_transition_verified(
1361        &self,
1362        event: &acdp_types::lifecycle::LifecycleEvent,
1363        expected_type: acdp_types::lifecycle::LifecycleEventType,
1364        requester: Option<&AgentDid>,
1365        resolver: &acdp_did::WebResolver,
1366    ) -> Result<FullContext, AcdpError> {
1367        let ctx = self.lifecycle_precheck(event, &expected_type, requester)?;
1368        // Full RFC-ACDP-0001 §5.11 pipeline over the event hash
1369        // (RFC-ACDP-0013 §5): resolution, assertionMethod, algorithm
1370        // binding, SSRF protections — the same pipeline as a publish.
1371        acdp_verify::verify_lifecycle_event(
1372            &serde_json::to_value(event)?,
1373            &event.ctx_id,
1374            &ctx.body.agent_id,
1375            None, // producer-only: registry events do not use the endpoints
1376            resolver,
1377        )
1378        .await?;
1379        self.lifecycle_commit(event)
1380    }
1381
1382    /// Shared verified pipeline for did:key producers — no resolver.
1383    fn lifecycle_transition_verified_did_key(
1384        &self,
1385        event: &acdp_types::lifecycle::LifecycleEvent,
1386        expected_type: acdp_types::lifecycle::LifecycleEventType,
1387        requester: Option<&AgentDid>,
1388    ) -> Result<FullContext, AcdpError> {
1389        let ctx = self.lifecycle_precheck(event, &expected_type, requester)?;
1390        acdp_verify::verify_lifecycle_event_offline(
1391            &serde_json::to_value(event)?,
1392            &event.ctx_id,
1393            &ctx.body.agent_id,
1394            None,
1395        )?;
1396        self.lifecycle_commit(event)
1397    }
1398
1399    /// **RFC-conformant retraction** — `POST /contexts/{ctx_id}/retract`
1400    /// (RFC-ACDP-0013 §6). Runs the full §6 pipeline: visibility, event
1401    /// validation (`retracted` on this endpoint), actor authentication,
1402    /// signature verification through the RFC-ACDP-0001 §5.11 resolver
1403    /// pipeline, strict-alternation transition validation, and the
1404    /// atomic append. Returns the post-transition full-retrieval
1405    /// envelope (`status: retracted`, event appended) — or the current
1406    /// state unchanged on a byte-identical `event_id` retry.
1407    ///
1408    /// Retraction is **mark-not-delete**: the body remains retrievable
1409    /// (§8.1), falls out of default searches (§8.2), and is never
1410    /// served from `/current` (§8.3).
1411    #[cfg(feature = "client")]
1412    pub async fn retract_verified(
1413        &self,
1414        event: &acdp_types::lifecycle::LifecycleEvent,
1415        requester: Option<&AgentDid>,
1416        resolver: &acdp_did::WebResolver,
1417    ) -> Result<FullContext, AcdpError> {
1418        self.lifecycle_transition_verified(
1419            event,
1420            acdp_types::lifecycle::LifecycleEventType::Retracted,
1421            requester,
1422            resolver,
1423        )
1424        .await
1425    }
1426
1427    /// **RFC-conformant republication** — `POST
1428    /// /contexts/{ctx_id}/republish` (RFC-ACDP-0013 §6): reverses a
1429    /// prior retraction. `status` re-derives per RFC-ACDP-0004 §4 as
1430    /// though the retraction had not occurred; both events remain in
1431    /// the append-only history. Same pipeline as
1432    /// [`Self::retract_verified`].
1433    #[cfg(feature = "client")]
1434    pub async fn republish_verified(
1435        &self,
1436        event: &acdp_types::lifecycle::LifecycleEvent,
1437        requester: Option<&AgentDid>,
1438        resolver: &acdp_did::WebResolver,
1439    ) -> Result<FullContext, AcdpError> {
1440        self.lifecycle_transition_verified(
1441            event,
1442            acdp_types::lifecycle::LifecycleEventType::Republished,
1443            requester,
1444            resolver,
1445        )
1446        .await
1447    }
1448
1449    /// [`Self::retract_verified`] for `did:key` producers — the §5
1450    /// signature verification is pure (the DID is the key), so this is
1451    /// available without the `client` feature. Rejects `did:web` (and
1452    /// any other method) actors with `key_resolution_failed`.
1453    pub fn retract_verified_did_key(
1454        &self,
1455        event: &acdp_types::lifecycle::LifecycleEvent,
1456        requester: Option<&AgentDid>,
1457    ) -> Result<FullContext, AcdpError> {
1458        self.lifecycle_transition_verified_did_key(
1459            event,
1460            acdp_types::lifecycle::LifecycleEventType::Retracted,
1461            requester,
1462        )
1463    }
1464
1465    /// [`Self::republish_verified`] for `did:key` producers.
1466    pub fn republish_verified_did_key(
1467        &self,
1468        event: &acdp_types::lifecycle::LifecycleEvent,
1469        requester: Option<&AgentDid>,
1470    ) -> Result<FullContext, AcdpError> {
1471        self.lifecycle_transition_verified_did_key(
1472            event,
1473            acdp_types::lifecycle::LifecycleEventType::Republished,
1474            requester,
1475        )
1476    }
1477
1478    /// **NOT RFC-conformant.** Skips signature verification (the §6
1479    /// step 3 cryptographic half; presence and actor binding are still
1480    /// enforced). Test-only, mirroring
1481    /// [`Self::publish_unverified_for_tests`].
1482    #[doc(hidden)]
1483    pub fn retract_unverified_for_tests(
1484        &self,
1485        event: &acdp_types::lifecycle::LifecycleEvent,
1486        requester: Option<&AgentDid>,
1487    ) -> Result<FullContext, AcdpError> {
1488        self.lifecycle_precheck(
1489            event,
1490            &acdp_types::lifecycle::LifecycleEventType::Retracted,
1491            requester,
1492        )?;
1493        self.lifecycle_commit(event)
1494    }
1495
1496    /// **NOT RFC-conformant.** See [`Self::retract_unverified_for_tests`].
1497    #[doc(hidden)]
1498    pub fn republish_unverified_for_tests(
1499        &self,
1500        event: &acdp_types::lifecycle::LifecycleEvent,
1501        requester: Option<&AgentDid>,
1502    ) -> Result<FullContext, AcdpError> {
1503        self.lifecycle_precheck(
1504            event,
1505            &acdp_types::lifecycle::LifecycleEventType::Republished,
1506            requester,
1507        )?;
1508        self.lifecycle_commit(event)
1509    }
1510
1511    /// Record a **registry-initiated** lifecycle event (RFC-ACDP-0013
1512    /// §6: deployment policy, legal compulsion). Does NOT use the
1513    /// producer endpoints or their actor rule: `actor` MUST equal the
1514    /// registry's own DID (`capabilities.registry_did`). Subject to the
1515    /// same append-only, uniqueness, transition, and shape rules; the
1516    /// event SHOULD be signed under a key in the registry's DID
1517    /// document (a registry advertising `acdp-registry-receipts` MUST
1518    /// sign — enforced here when a receipt signer is configured, per
1519    /// the §5 same-key precedent). This is the protocol-visible form of
1520    /// "removed by policy": the body stays served, the withdrawal is
1521    /// explicit and attributed.
1522    pub fn record_registry_lifecycle_event(
1523        &self,
1524        event: &acdp_types::lifecycle::LifecycleEvent,
1525    ) -> Result<FullContext, AcdpError> {
1526        if !self.lifecycle_enabled {
1527            return Err(AcdpError::NotImplemented(
1528                "this registry does not advertise acdp-registry-lifecycle \
1529                 (RFC-ACDP-0013 §6)"
1530                    .into(),
1531            ));
1532        }
1533        event.validate()?;
1534        if !event.event_type.is_registered() {
1535            return Err(AcdpError::SchemaViolation(format!(
1536                "event_type '{}' is not registered for acceptance in 0.3.0 \
1537                 (RFC-ACDP-0013 §7.3)",
1538                event.event_type
1539            )));
1540        }
1541        if event.actor.as_str() != self.caps.registry_did {
1542            return Err(AcdpError::NotAuthorized(format!(
1543                "registry-initiated event actor '{}' ≠ this registry's DID '{}' \
1544                 (RFC-ACDP-0013 §6)",
1545                event.actor, self.caps.registry_did
1546            )));
1547        }
1548        if self.receipt_signer.is_some() && !event.is_signed() {
1549            return Err(AcdpError::SchemaViolation(
1550                "a registry advertising acdp-registry-receipts MUST sign its lifecycle \
1551                 events (RFC-ACDP-0013 §5)"
1552                    .into(),
1553            ));
1554        }
1555        if event.is_signed() {
1556            // §5 actor binding for the registry key.
1557            event.actor_bound_signature()?;
1558        }
1559        self.lifecycle_commit(event)
1560    }
1561}
1562
1563/// RFC-ACDP-0008 §4.5 retrieval disclosure rule.
1564pub(crate) fn can_retrieve(
1565    body: &Body,
1566    requester: Option<&AgentDid>,
1567    caps: &CapabilitiesDocument,
1568) -> bool {
1569    match body.visibility {
1570        Visibility::Public => caps.anonymous_public_reads || requester.is_some(),
1571        Visibility::Restricted | Visibility::Private => match requester {
1572            None => false,
1573            Some(r) => {
1574                r == &body.agent_id
1575                    || body
1576                        .audience
1577                        .as_deref()
1578                        .is_some_and(|a| a.iter().any(|d| d == r))
1579            }
1580        },
1581    }
1582}
1583
1584/// Resolve and fingerprint the producer key named by
1585/// `signature.key_id` — the binding recorded in a receipt's
1586/// `key_fingerprint` (RFC-ACDP-0010), and (as of RFC-ACDP-0014 §5 step 2)
1587/// also checked against a did:web key-revocation's own
1588/// `revoked_key_fingerprint` in [`RegistryServer::publish_verified_in_tenant`].
1589/// Delegates to the same
1590/// [`acdp_crypto::fingerprint::fingerprint_for_key_id`] the consumer
1591/// cross-check uses, so mint-time and verify-time fingerprints cannot
1592/// drift. Callers MUST invoke this only after
1593/// `verify_publish_request_signature` succeeded, so the fingerprinted
1594/// key is the one that actually verified (the resolver's cache makes a
1595/// second resolution — receipt minting and/or the §5 step 2 check on
1596/// the same request — cheap, and `publish_verified_in_tenant` computes
1597/// it at most once per publish either way).
1598#[cfg(feature = "client")]
1599async fn producer_key_fingerprint(
1600    req: &PublishRequest,
1601    resolver: &acdp_did::WebResolver,
1602) -> Result<String, AcdpError> {
1603    acdp_crypto::fingerprint::fingerprint_for_key_id(
1604        &req.signature.key_id,
1605        &req.signature.algorithm,
1606        resolver,
1607    )
1608    .await
1609}
1610
1611/// Fingerprint a base64 public key the caller has already verified a
1612/// signature against (an operator-pinned key, not a resolved DID
1613/// document) — no resolution involved, just decode + dispatch by
1614/// algorithm. Used by [`RegistryServer::publish_pinned_verified_in_tenant`].
1615fn fingerprint_pinned_key(public_key_b64: &str, algorithm: &str) -> Result<String, AcdpError> {
1616    use base64::{engine::general_purpose::STANDARD, Engine};
1617
1618    let raw = STANDARD
1619        .decode(public_key_b64)
1620        .map_err(|e| AcdpError::KeyResolution(format!("pinned key is not valid base64: {e}")))?;
1621    match algorithm {
1622        "ed25519" => {
1623            let arr: [u8; 32] = raw.as_slice().try_into().map_err(|_| {
1624                AcdpError::KeyResolution(format!(
1625                    "pinned ed25519 key must be 32 bytes, got {}",
1626                    raw.len()
1627                ))
1628            })?;
1629            Ok(acdp_crypto::fingerprint::fingerprint_ed25519(&arr))
1630        }
1631        "ecdsa-p256" => acdp_crypto::fingerprint::fingerprint_p256_sec1(&raw),
1632        other => Err(AcdpError::UnsupportedAlgorithm(format!(
1633            "cannot fingerprint a pinned key for algorithm '{other}'"
1634        ))),
1635    }
1636}
1637
1638#[cfg(test)]
1639mod tests {
1640    use super::*;
1641    use crate::registry::store::{InMemoryStore, PublishCommitOutcome};
1642    use acdp_crypto::SigningKey;
1643    use acdp_producer::Producer;
1644    use acdp_types::capabilities::Limits;
1645    use acdp_types::primitives::{AgentDid, ContextType, Visibility};
1646
1647    fn caps() -> CapabilitiesDocument {
1648        CapabilitiesDocument {
1649            acdp_version: "0.1.0".into(),
1650            registry_did: "did:web:registry.example.com".into(),
1651            supported_signature_algorithms: vec!["ed25519".into()],
1652            supported_did_methods: vec!["did:web".into()],
1653            profiles: vec!["acdp-registry-core".into()],
1654            limits: Limits {
1655                max_payload_bytes: 1_048_576,
1656                max_embedded_bytes: 65_536,
1657                idempotency_key_ttl_seconds: None,
1658                max_publish_per_minute: None,
1659            },
1660            read_authentication_methods: vec![],
1661            anonymous_public_reads: true,
1662            supports_idempotency_key: false,
1663            extensions: Default::default(),
1664        }
1665    }
1666
1667    fn producer() -> Producer {
1668        Producer::new(
1669            SigningKey::from_bytes(&[1u8; 32]),
1670            AgentDid::new("did:web:agents.example.com:test"),
1671            "did:web:agents.example.com:test#key-1",
1672        )
1673    }
1674
1675    #[test]
1676    fn publish_v1_then_retrieve() {
1677        let server = RegistryServer::new(InMemoryStore::new(), caps(), "registry.example.com");
1678        let p = producer();
1679        let req = p
1680            .publish_request()
1681            .title("v1")
1682            .context_type(ContextType::DataSnapshot)
1683            .visibility(Visibility::Public)
1684            .build()
1685            .unwrap();
1686        let resp = server.publish_unverified_for_tests(&req).unwrap();
1687        assert_eq!(resp.version, 1);
1688        let ctx = server.retrieve(&resp.ctx_id, None).unwrap().unwrap();
1689        assert_eq!(ctx.body.title, "v1");
1690        // Lineage round-trip
1691        let lineage = server.lineage(&resp.lineage_id, None).unwrap();
1692        assert_eq!(lineage.len(), 1);
1693        // Current points at the same record
1694        let cur = server.current(&resp.lineage_id, None).unwrap().unwrap();
1695        assert_eq!(cur.body.ctx_id, resp.ctx_id);
1696    }
1697
1698    #[test]
1699    fn supersession_marks_predecessor_and_returns_v2() {
1700        let server = RegistryServer::new(InMemoryStore::new(), caps(), "registry.example.com");
1701        let p = producer();
1702        let v1_req = p
1703            .publish_request()
1704            .title("v1")
1705            .context_type(ContextType::DataSnapshot)
1706            .visibility(Visibility::Public)
1707            .build()
1708            .unwrap();
1709        let v1 = server.publish_unverified_for_tests(&v1_req).unwrap();
1710
1711        let v2_req = p
1712            .supersede(v1.ctx_id.clone())
1713            .version(2)
1714            .title("v2")
1715            .context_type(ContextType::DataSnapshot)
1716            .visibility(Visibility::Public)
1717            .build()
1718            .unwrap();
1719        let v2 = server.publish_unverified_for_tests(&v2_req).unwrap();
1720        assert_eq!(v2.version, 2);
1721        // v1 was marked superseded
1722        let v1_ctx = server.retrieve(&v1.ctx_id, None).unwrap().unwrap();
1723        assert!(matches!(
1724            v1_ctx.registry_state.status,
1725            acdp_types::Status::Superseded
1726        ));
1727        // Same lineage
1728        assert_eq!(v1.lineage_id, v2.lineage_id);
1729        // Current resolves to v2
1730        let cur = server.current(&v1.lineage_id, None).unwrap().unwrap();
1731        assert_eq!(cur.body.ctx_id, v2.ctx_id);
1732    }
1733
1734    /// FEAT-01: two concurrent publishes that both supersede the same
1735    /// v1 MUST resolve to exactly one success + one
1736    /// `SupersededTarget { AlreadySuperseded }`. The race was possible
1737    /// when the supersedes check, body insert, and predecessor mark
1738    /// lived in separate mutex acquisitions; `commit_publish` puts
1739    /// them under one critical section so only one of two contenders
1740    /// wins (RFC-ACDP-0003 §6).
1741    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
1742    async fn concurrent_supersession_exactly_one_succeeds() {
1743        use std::sync::Arc;
1744        let server = Arc::new(RegistryServer::new(
1745            InMemoryStore::new(),
1746            caps(),
1747            "registry.example.com",
1748        ));
1749        let p = producer();
1750        let v1_req = p
1751            .publish_request()
1752            .title("v1")
1753            .context_type(ContextType::DataSnapshot)
1754            .visibility(Visibility::Public)
1755            .build()
1756            .unwrap();
1757        let v1 = server.publish_unverified_for_tests(&v1_req).unwrap();
1758
1759        // Pre-build BOTH v2 requests up front, then fire them in
1760        // parallel on a multi-threaded runtime. With the prior
1761        // non-atomic sequence the test would fail intermittently;
1762        // with `commit_publish` it's deterministic.
1763        let v2a_req = p
1764            .supersede(v1.ctx_id.clone())
1765            .version(2)
1766            .title("v2-A")
1767            .context_type(ContextType::DataSnapshot)
1768            .visibility(Visibility::Public)
1769            .build()
1770            .unwrap();
1771        let v2b_req = p
1772            .supersede(v1.ctx_id.clone())
1773            .version(2)
1774            .title("v2-B")
1775            .context_type(ContextType::DataSnapshot)
1776            .visibility(Visibility::Public)
1777            .build()
1778            .unwrap();
1779
1780        let s1 = Arc::clone(&server);
1781        let s2 = Arc::clone(&server);
1782        let h1 = tokio::task::spawn_blocking(move || s1.publish_unverified_for_tests(&v2a_req));
1783        let h2 = tokio::task::spawn_blocking(move || s2.publish_unverified_for_tests(&v2b_req));
1784        let (r1, r2) = (h1.await.unwrap(), h2.await.unwrap());
1785
1786        let outcomes = [r1, r2];
1787        let successes = outcomes.iter().filter(|r| r.is_ok()).count();
1788        let failures = outcomes.iter().filter(|r| r.is_err()).count();
1789        assert_eq!(
1790            successes, 1,
1791            "exactly one concurrent supersession MUST succeed; got {successes} successes / {failures} failures"
1792        );
1793        assert_eq!(failures, 1);
1794        // The loser MUST get AlreadySuperseded — the predecessor was
1795        // marked under the same lock the winner used.
1796        for r in &outcomes {
1797            if let Err(e) = r {
1798                match e {
1799                    AcdpError::SupersededTarget { reason, .. } => assert_eq!(
1800                        *reason,
1801                        acdp_primitives::error::SupersessionReason::AlreadySuperseded,
1802                        "concurrent loser MUST be AlreadySuperseded"
1803                    ),
1804                    other => panic!("concurrent loser had wrong error: {other:?}"),
1805                }
1806            }
1807        }
1808    }
1809
1810    #[test]
1811    fn hostile_supersession_by_non_owner_rejected_predecessor_unchanged() {
1812        // P0-2: an attacker controlling their own DID must not be able to
1813        // supersede a victim's context. Without the producer-continuity
1814        // check this marks the victim's context `Superseded` and re-points
1815        // `current(lineage)` at the attacker's body — a lineage takeover.
1816        let server = RegistryServer::new(InMemoryStore::new(), caps(), "registry.example.com");
1817        let victim = producer_for(7, "did:web:agents.example.com:victim");
1818        let v1_req = victim
1819            .publish_request()
1820            .title("v1")
1821            .context_type(ContextType::DataSnapshot)
1822            .visibility(Visibility::Public)
1823            .build()
1824            .unwrap();
1825        let v1 = server.publish_unverified_for_tests(&v1_req).unwrap();
1826
1827        // Attacker signs their own valid v2, omitting lineage_id (the only
1828        // self-declared coherence arm), supersedes = victim's v1.
1829        let attacker = producer_for(9, "did:web:evil.example.com:attacker");
1830        let v2_req = attacker
1831            .supersede(v1.ctx_id.clone())
1832            .version(2)
1833            .title("hijacked")
1834            .context_type(ContextType::DataSnapshot)
1835            .visibility(Visibility::Public)
1836            .build()
1837            .unwrap();
1838        let err = server.publish_unverified_for_tests(&v2_req).unwrap_err();
1839        // Uniform with not-found: no existence / version / status oracle.
1840        match err {
1841            AcdpError::SupersededTarget { reason, .. } => {
1842                assert_eq!(reason, acdp_primitives::error::SupersessionReason::NotFound);
1843            }
1844            other => panic!("expected uniform SupersededTarget::NotFound, got {other:?}"),
1845        }
1846        // Predecessor MUST be untouched: still current, not superseded.
1847        let cur = server.current(&v1.lineage_id, None).unwrap().unwrap();
1848        assert_eq!(cur.body.ctx_id, v1.ctx_id);
1849        assert_eq!(cur.body.title, "v1");
1850        assert_eq!(
1851            cur.registry_state.status,
1852            acdp_types::primitives::Status::Active
1853        );
1854    }
1855
1856    #[test]
1857    fn owner_supersession_still_succeeds_after_ownership_check() {
1858        let server = RegistryServer::new(InMemoryStore::new(), caps(), "registry.example.com");
1859        let p = producer();
1860        let v1_req = p
1861            .publish_request()
1862            .title("v1")
1863            .context_type(ContextType::DataSnapshot)
1864            .visibility(Visibility::Public)
1865            .build()
1866            .unwrap();
1867        let v1 = server.publish_unverified_for_tests(&v1_req).unwrap();
1868        let v2_req = p
1869            .supersede(v1.ctx_id.clone())
1870            .version(2)
1871            .title("v2")
1872            .context_type(ContextType::DataSnapshot)
1873            .visibility(Visibility::Public)
1874            .build()
1875            .unwrap();
1876        let v2 = server.publish_unverified_for_tests(&v2_req).unwrap();
1877        assert_eq!(v2.version, 2);
1878        let cur = server.current(&v1.lineage_id, None).unwrap().unwrap();
1879        assert_eq!(cur.body.ctx_id, v2.ctx_id);
1880    }
1881
1882    #[test]
1883    fn supersession_with_unknown_target_rejected_as_not_found() {
1884        let server = RegistryServer::new(InMemoryStore::new(), caps(), "registry.example.com");
1885        let p = producer();
1886        let phantom =
1887            CtxId("acdp://registry.example.com/12345678-1234-4321-8123-deadbeefcafe".into());
1888        let req = p
1889            .supersede(phantom)
1890            .version(2)
1891            .title("v2-orphan")
1892            .context_type(ContextType::DataSnapshot)
1893            .visibility(Visibility::Public)
1894            .build()
1895            .unwrap();
1896        let err = server.publish_unverified_for_tests(&req).unwrap_err();
1897        match err {
1898            AcdpError::SupersededTarget { reason, .. } => {
1899                assert_eq!(reason, acdp_primitives::error::SupersessionReason::NotFound);
1900            }
1901            other => panic!("expected SupersededTarget::NotFound, got {other:?}"),
1902        }
1903    }
1904
1905    #[test]
1906    fn version_mismatch_rejected() {
1907        let server = RegistryServer::new(InMemoryStore::new(), caps(), "registry.example.com");
1908        let p = producer();
1909        let v1_req = p
1910            .publish_request()
1911            .title("v1")
1912            .context_type(ContextType::DataSnapshot)
1913            .visibility(Visibility::Public)
1914            .build()
1915            .unwrap();
1916        let v1 = server.publish_unverified_for_tests(&v1_req).unwrap();
1917        // Build a v3 (wrong) supersession
1918        let v3_req = p
1919            .supersede(v1.ctx_id.clone())
1920            .version(3)
1921            .title("v3-skipped")
1922            .context_type(ContextType::DataSnapshot)
1923            .visibility(Visibility::Public)
1924            .build()
1925            .unwrap();
1926        let err = server.publish_unverified_for_tests(&v3_req).unwrap_err();
1927        match err {
1928            AcdpError::SupersededTarget { reason, .. } => {
1929                assert_eq!(
1930                    reason,
1931                    acdp_primitives::error::SupersessionReason::VersionMismatch
1932                );
1933            }
1934            other => panic!("expected VersionMismatch, got {other:?}"),
1935        }
1936    }
1937
1938    #[test]
1939    fn search_finds_published_context() {
1940        let server = RegistryServer::new(InMemoryStore::new(), caps(), "registry.example.com");
1941        let p = producer();
1942        let req = p
1943            .publish_request()
1944            .title("Q1 portfolio risk")
1945            .context_type(ContextType::DataSnapshot)
1946            .visibility(Visibility::Public)
1947            .build()
1948            .unwrap();
1949        server.publish_unverified_for_tests(&req).unwrap();
1950        let resp = server
1951            .search(
1952                &SearchParams {
1953                    q: Some("portfolio".into()),
1954                    ..Default::default()
1955                },
1956                None,
1957            )
1958            .unwrap();
1959        assert_eq!(resp.matches.len(), 1);
1960        assert_eq!(resp.matches[0].title, "Q1 portfolio risk");
1961    }
1962
1963    // ── BUG-03 — lineage/current visibility filtering ──────────────────
1964
1965    /// BUG-03: a stranger calling `lineage()` MUST NOT see restricted
1966    /// bodies they aren't on the audience for. The retrieval predicate
1967    /// is now mirrored here.
1968    #[test]
1969    fn lineage_filters_restricted_for_stranger() {
1970        let server = RegistryServer::new(InMemoryStore::new(), caps(), "registry.example.com");
1971        let p = producer();
1972        let audience = AgentDid::new("did:web:audience.example.com:reader");
1973        let req = p
1974            .publish_request()
1975            .title("restricted v1")
1976            .context_type(ContextType::DataSnapshot)
1977            .visibility(Visibility::Restricted)
1978            .audience(vec![audience.clone()])
1979            .build()
1980            .unwrap();
1981        let resp = server.publish_unverified_for_tests(&req).unwrap();
1982
1983        let stranger = AgentDid::new("did:web:other.example.com:reader");
1984        let stranger_view = server.lineage(&resp.lineage_id, Some(&stranger)).unwrap();
1985        assert!(
1986            stranger_view.is_empty(),
1987            "stranger MUST NOT see restricted bodies via lineage(); got {} entries",
1988            stranger_view.len()
1989        );
1990
1991        let audience_view = server.lineage(&resp.lineage_id, Some(&audience)).unwrap();
1992        assert_eq!(
1993            audience_view.len(),
1994            1,
1995            "audience member MUST see the restricted body via lineage()"
1996        );
1997    }
1998
1999    /// BUG-03: `current()` also filters by requester visibility.
2000    /// A stranger gets `None` for a private lineage.
2001    #[test]
2002    fn current_filters_private_for_stranger() {
2003        let server = RegistryServer::new(InMemoryStore::new(), caps(), "registry.example.com");
2004        let p = producer();
2005        let req = p
2006            .publish_request()
2007            .title("private v1")
2008            .context_type(ContextType::DataSnapshot)
2009            .visibility(Visibility::Private)
2010            .build()
2011            .unwrap();
2012        let resp = server.publish_unverified_for_tests(&req).unwrap();
2013
2014        let stranger = AgentDid::new("did:web:other.example.com:reader");
2015        assert!(
2016            server
2017                .current(&resp.lineage_id, Some(&stranger))
2018                .unwrap()
2019                .is_none(),
2020            "stranger MUST NOT see private contexts via current()"
2021        );
2022
2023        let producer_did = AgentDid::new("did:web:agents.example.com:test");
2024        assert!(
2025            server
2026                .current(&resp.lineage_id, Some(&producer_did))
2027                .unwrap()
2028                .is_some(),
2029            "producer MUST see private contexts via current()"
2030        );
2031    }
2032
2033    // ── BUG-04 — current() superseded fallback ─────────────────────────
2034
2035    /// BUG-04: when every version of a lineage is `Superseded`,
2036    /// `current()` MUST return `None`. Previously the fallback returned
2037    /// the last entry projected, which is a protocol violation
2038    /// (RFC-ACDP-0004 §5: "If no such version exists, returns not_found").
2039    ///
2040    /// Constructing an all-superseded lineage requires a direct store
2041    /// mark — there's no publish path that produces this state today,
2042    /// but the registry's `current()` MUST not implicitly fall through.
2043    #[test]
2044    fn current_returns_none_when_all_superseded() {
2045        use crate::registry::store::RegistryStore;
2046        let server = RegistryServer::new(InMemoryStore::new(), caps(), "registry.example.com");
2047        let p = producer();
2048        let req = p
2049            .publish_request()
2050            .title("v1")
2051            .context_type(ContextType::DataSnapshot)
2052            .visibility(Visibility::Public)
2053            .build()
2054            .unwrap();
2055        let resp = server.publish_unverified_for_tests(&req).unwrap();
2056        // Force the only version into Superseded directly.
2057        server.store().mark_superseded(&resp.ctx_id).unwrap();
2058
2059        let cur = server.current(&resp.lineage_id, None).unwrap();
2060        assert!(
2061            cur.is_none(),
2062            "all-superseded lineage MUST resolve to None per RFC-ACDP-0004 §5; got {cur:?}"
2063        );
2064    }
2065
2066    // ── BUG-01 / vis-009 — anonymous search honors anonymous_public_reads ──
2067
2068    /// BUG-01 + vis-009: a registry advertising `anonymous_public_reads:
2069    /// false` MUST reject an anonymous search with `not_authorized`
2070    /// (HTTP 403) — not an empty `200`, which would still leak the
2071    /// registry's existence. The same context surfaces with a `200`
2072    /// once the requester authenticates.
2073    #[test]
2074    fn search_suppresses_public_when_anonymous_public_reads_false() {
2075        let mut c = caps();
2076        c.anonymous_public_reads = false;
2077        let server = RegistryServer::new(InMemoryStore::new(), c, "registry.example.com");
2078        let p = producer();
2079        let req = p
2080            .publish_request()
2081            .title("public-but-flag-off")
2082            .context_type(ContextType::DataSnapshot)
2083            .visibility(Visibility::Public)
2084            .build()
2085            .unwrap();
2086        server.publish_unverified_for_tests(&req).unwrap();
2087
2088        // Anonymous: MUST be rejected with NotAuthorized (vis-009 s1).
2089        let err = server
2090            .search(
2091                &SearchParams {
2092                    q: Some("public-but-flag-off".into()),
2093                    ..Default::default()
2094                },
2095                None,
2096            )
2097            .unwrap_err();
2098        assert!(
2099            matches!(err, AcdpError::NotAuthorized(_)),
2100            "vis-009: anonymous search MUST be NotAuthorized when \
2101             anonymous_public_reads=false; got {err:?}"
2102        );
2103
2104        // Authenticated requester (any DID — public is universally visible
2105        // once authenticated): MUST see the context.
2106        let stranger = AgentDid::new("did:web:other.example.com:reader");
2107        let authed = server
2108            .search(
2109                &SearchParams {
2110                    q: Some("public-but-flag-off".into()),
2111                    ..Default::default()
2112                },
2113                Some(&stranger),
2114            )
2115            .unwrap();
2116        assert_eq!(
2117            authed.matches.len(),
2118            1,
2119            "authenticated search MUST see public contexts regardless of anonymous_public_reads"
2120        );
2121    }
2122
2123    // ── try_new validation tests ────────────────────────────────────────
2124
2125    #[test]
2126    fn try_new_rejects_did_authority_mismatch() {
2127        let mut c = caps();
2128        c.registry_did = "did:web:other.example.com".into(); // wrong authority
2129        let res = RegistryServer::try_new(InMemoryStore::new(), c, "registry.example.com");
2130        match res {
2131            Err(AcdpError::SchemaViolation(msg)) => {
2132                assert!(msg.contains("does not match expected"))
2133            }
2134            Err(other) => panic!("expected SchemaViolation, got {other:?}"),
2135            Ok(_) => panic!("expected Err"),
2136        }
2137    }
2138
2139    #[test]
2140    fn try_new_rejects_caps_missing_ed25519() {
2141        let mut c = caps();
2142        c.supported_signature_algorithms = vec!["ecdsa-p256".into()]; // missing ed25519
2143        let res = RegistryServer::try_new(InMemoryStore::new(), c, "registry.example.com");
2144        assert!(matches!(res, Err(AcdpError::SchemaViolation(_))));
2145    }
2146
2147    #[test]
2148    fn try_new_accepts_valid_caps() {
2149        RegistryServer::try_new(InMemoryStore::new(), caps(), "registry.example.com").unwrap();
2150    }
2151
2152    // ── WIRE-04 — try_new authority-format validation ───────────────────
2153
2154    #[test]
2155    fn try_new_accepts_valid_dns_authority() {
2156        RegistryServer::try_new(InMemoryStore::new(), caps(), "registry.example.com").unwrap();
2157    }
2158
2159    #[test]
2160    fn try_new_rejects_host_port_authority() {
2161        // A `host:port` authority would mint `acdp://localhost:8443/<uuid>`
2162        // ctx_ids — a colon violates the acdp:// authority rule.
2163        let res = RegistryServer::try_new(InMemoryStore::new(), caps(), "localhost:8443");
2164        assert!(matches!(res, Err(AcdpError::SchemaViolation(_))));
2165    }
2166
2167    #[test]
2168    fn try_new_rejects_uppercase_authority() {
2169        let res = RegistryServer::try_new(InMemoryStore::new(), caps(), "Registry.Example.Com");
2170        assert!(matches!(res, Err(AcdpError::SchemaViolation(_))));
2171    }
2172
2173    #[test]
2174    fn try_new_rejects_url_form_authority() {
2175        let res =
2176            RegistryServer::try_new(InMemoryStore::new(), caps(), "https://registry.example.com");
2177        assert!(matches!(res, Err(AcdpError::SchemaViolation(_))));
2178    }
2179
2180    #[test]
2181    fn try_new_for_test_accepts_host_port() {
2182        // The test constructor skips the DNS-authority check; it still
2183        // enforces the DID binding, so the caps DID must match.
2184        let mut c = caps();
2185        c.registry_did = acdp_did::authority_to_did_web("localhost:8443");
2186        RegistryServer::try_new_for_test_authority(InMemoryStore::new(), c, "localhost:8443")
2187            .unwrap();
2188    }
2189
2190    // ── Visibility-enforcement tests (RFC-ACDP-0008 §4.5) ───────────────
2191
2192    fn producer_for(seed: u8, did: &str) -> Producer {
2193        Producer::new(
2194            SigningKey::from_bytes(&[seed; 32]),
2195            AgentDid::new(did),
2196            format!("{did}#key-1"),
2197        )
2198    }
2199
2200    #[test]
2201    fn retrieve_restricted_blocks_stranger_returns_none() {
2202        let server = RegistryServer::new(InMemoryStore::new(), caps(), "registry.example.com");
2203        let owner = AgentDid::new("did:web:agents.example.com:owner");
2204        let audience_member = AgentDid::new("did:web:agents.example.com:friend");
2205        let p = producer_for(2, owner.as_str());
2206        let req = p
2207            .publish_request()
2208            .title("restricted")
2209            .context_type(ContextType::DataSnapshot)
2210            .visibility(Visibility::Restricted)
2211            .audience(vec![audience_member.clone()])
2212            .build()
2213            .unwrap();
2214        let resp = server.publish_unverified_for_tests(&req).unwrap();
2215        let stranger = AgentDid::new("did:web:agents.example.com:stranger");
2216
2217        assert!(server.retrieve(&resp.ctx_id, None).unwrap().is_none());
2218        assert!(server
2219            .retrieve(&resp.ctx_id, Some(&stranger))
2220            .unwrap()
2221            .is_none());
2222        assert!(server
2223            .retrieve(&resp.ctx_id, Some(&owner))
2224            .unwrap()
2225            .is_some());
2226        assert!(server
2227            .retrieve(&resp.ctx_id, Some(&audience_member))
2228            .unwrap()
2229            .is_some());
2230    }
2231
2232    #[test]
2233    fn search_restricted_filters_strangers() {
2234        let server = RegistryServer::new(InMemoryStore::new(), caps(), "registry.example.com");
2235        let owner = AgentDid::new("did:web:agents.example.com:owner");
2236        let p = producer_for(3, owner.as_str());
2237        let req = p
2238            .publish_request()
2239            .title("hush hush")
2240            .context_type(ContextType::DataSnapshot)
2241            .visibility(Visibility::Restricted)
2242            .audience(vec![AgentDid::new("did:web:agents.example.com:friend")])
2243            .build()
2244            .unwrap();
2245        server.publish_unverified_for_tests(&req).unwrap();
2246
2247        let stranger = AgentDid::new("did:web:agents.example.com:stranger");
2248        let r_anon = server.search(&SearchParams::default(), None).unwrap();
2249        assert!(
2250            r_anon.matches.is_empty(),
2251            "anonymous must not see restricted"
2252        );
2253        let r_stranger = server
2254            .search(&SearchParams::default(), Some(&stranger))
2255            .unwrap();
2256        assert!(r_stranger.matches.is_empty());
2257        let r_owner = server
2258            .search(&SearchParams::default(), Some(&owner))
2259            .unwrap();
2260        assert_eq!(r_owner.matches.len(), 1);
2261    }
2262
2263    /// RFC-ACDP-0008 §4.5 asymmetry: a private context surfaces in search
2264    /// only to its producer — audience members can retrieve by id but can't
2265    /// discover via search.
2266    #[test]
2267    fn search_private_visible_only_to_producer() {
2268        let server = RegistryServer::new(InMemoryStore::new(), caps(), "registry.example.com");
2269        let owner = AgentDid::new("did:web:agents.example.com:owner");
2270        let audience_member = AgentDid::new("did:web:agents.example.com:friend");
2271        let p = producer_for(4, owner.as_str());
2272        let req = p
2273            .publish_request()
2274            .title("private note")
2275            .context_type(ContextType::DataSnapshot)
2276            .visibility(Visibility::Private)
2277            .audience(vec![audience_member.clone()])
2278            .build()
2279            .unwrap();
2280        let resp = server.publish_unverified_for_tests(&req).unwrap();
2281
2282        let r_audience = server
2283            .search(&SearchParams::default(), Some(&audience_member))
2284            .unwrap();
2285        assert!(
2286            r_audience.matches.is_empty(),
2287            "audience must NOT see private in search"
2288        );
2289        let r_owner = server
2290            .search(&SearchParams::default(), Some(&owner))
2291            .unwrap();
2292        assert_eq!(
2293            r_owner.matches.len(),
2294            1,
2295            "owner sees their own private context"
2296        );
2297
2298        // Audience CAN retrieve directly by id.
2299        assert!(server
2300            .retrieve(&resp.ctx_id, Some(&audience_member))
2301            .unwrap()
2302            .is_some());
2303    }
2304
2305    // ── publish_verified offline-rejection tests ────────────────────────
2306    //
2307    // Full end-to-end `publish_verified` requires a TLS-mocked DID
2308    // document (because `WebResolver` is HTTPS-only). These tests cover
2309    // the rejection paths that fire BEFORE the resolver call so they
2310    // don't need a network: malformed key_id, non-did:web key_id,
2311    // agent_id ≠ key_id DID portion. Together with the existing
2312    // `verify_signature_envelope` algorithm-downgrade unit test, they
2313    // pin the entry checks of RFC-ACDP-0003 §2.1 steps 7–8 without
2314    // requiring a TLS mock harness.
2315
2316    #[cfg(feature = "client")]
2317    #[tokio::test]
2318    async fn publish_verified_rejects_non_did_web_key_id() {
2319        let server = RegistryServer::new(InMemoryStore::new(), caps(), "registry.example.com");
2320        let p = producer();
2321        let mut req = p
2322            .publish_request()
2323            .title("v1")
2324            .context_type(ContextType::DataSnapshot)
2325            .visibility(Visibility::Public)
2326            .build()
2327            .unwrap();
2328        // Mutate post-build — validation already ran and accepted did:web.
2329        // Re-sign isn't necessary: the verifier rejects before signature
2330        // check. Use a *well-formed* did:key URL (a malformed one is
2331        // caught earlier by schema validation as of ACDP 0.2): the
2332        // key_id DID portion no longer matches the did:web agent_id, so
2333        // the binding check refuses it.
2334        let did_key = acdp_did::key::did_key_from_ed25519(
2335            &SigningKey::from_bytes(&[9u8; 32]).verifying_key_bytes(),
2336        );
2337        req.signature.key_id = acdp_did::key::did_key_url(&did_key).unwrap();
2338        let resolver = acdp_did::WebResolver::new();
2339        let err = server
2340            .publish_verified(&req, None, &resolver)
2341            .await
2342            .unwrap_err();
2343        match err {
2344            AcdpError::KeyNotAuthorized(msg) => assert!(msg.contains("did:web")),
2345            other => panic!("expected KeyNotAuthorized for non-did:web, got {other:?}"),
2346        }
2347    }
2348
2349    #[cfg(feature = "client")]
2350    #[tokio::test]
2351    async fn publish_verified_rejects_agent_id_keyid_mismatch() {
2352        let server = RegistryServer::new(InMemoryStore::new(), caps(), "registry.example.com");
2353        let p = producer();
2354        let mut req = p
2355            .publish_request()
2356            .title("v1")
2357            .context_type(ContextType::DataSnapshot)
2358            .visibility(Visibility::Public)
2359            .build()
2360            .unwrap();
2361        req.signature.key_id = "did:web:other.example.com:agent#key-1".into();
2362        let resolver = acdp_did::WebResolver::new();
2363        let err = server
2364            .publish_verified(&req, None, &resolver)
2365            .await
2366            .unwrap_err();
2367        match err {
2368            AcdpError::KeyNotAuthorized(msg) => assert!(msg.contains("agent_id")),
2369            other => panic!("expected KeyNotAuthorized for agent_id mismatch, got {other:?}"),
2370        }
2371    }
2372
2373    #[cfg(feature = "client")]
2374    #[tokio::test]
2375    async fn publish_verified_rejects_keyid_without_fragment() {
2376        let server = RegistryServer::new(InMemoryStore::new(), caps(), "registry.example.com");
2377        let p = producer();
2378        let mut req = p
2379            .publish_request()
2380            .title("v1")
2381            .context_type(ContextType::DataSnapshot)
2382            .visibility(Visibility::Public)
2383            .build()
2384            .unwrap();
2385        req.signature.key_id = "did:web:agents.example.com:test".into(); // no '#'
2386        let resolver = acdp_did::WebResolver::new();
2387        let err = server
2388            .publish_verified(&req, None, &resolver)
2389            .await
2390            .unwrap_err();
2391        // Schema validation (step 1) catches missing-fragment before
2392        // step 7 fires, so the surface error is SchemaViolation.
2393        assert!(
2394            matches!(
2395                err,
2396                AcdpError::SchemaViolation(_) | AcdpError::KeyResolution(_)
2397            ),
2398            "expected fragment-rejection error, got {err:?}"
2399        );
2400    }
2401
2402    // ── FEAT-04 idempotency tests ──────────────────────────────────────
2403
2404    fn caps_with_idempotency() -> CapabilitiesDocument {
2405        let mut c = caps();
2406        c.supports_idempotency_key = true;
2407        c.limits.idempotency_key_ttl_seconds = Some(86_400);
2408        c
2409    }
2410
2411    #[test]
2412    fn idempotency_same_hash_returns_original_response() {
2413        let server = RegistryServer::new(
2414            InMemoryStore::new(),
2415            caps_with_idempotency(),
2416            "registry.example.com",
2417        );
2418        let p = producer();
2419        let req = p
2420            .publish_request()
2421            .title("once")
2422            .context_type(ContextType::DataSnapshot)
2423            .visibility(Visibility::Public)
2424            .build()
2425            .unwrap();
2426        // Publish twice through the same idempotency key via the real
2427        // path — `publish_unverified_in_tenant_for_tests` can pass an
2428        // idempotency key straight through to `commit_via_store`, so
2429        // there is no more need to fake the store-level entry.
2430        let first = server
2431            .publish_unverified_in_tenant_for_tests(&req, Some("k-001"), None)
2432            .unwrap();
2433        let replayed = server
2434            .publish_unverified_in_tenant_for_tests(&req, Some("k-001"), None)
2435            .unwrap();
2436        assert_eq!(replayed.ctx_id, first.ctx_id);
2437        assert_eq!(replayed.lineage_id, first.lineage_id);
2438        assert_eq!(replayed.created_at, first.created_at);
2439        // And only one context was actually persisted.
2440        let resp = server.search(&SearchParams::default(), None).unwrap();
2441        assert_eq!(
2442            resp.matches.len(),
2443            1,
2444            "idempotent replay must not persist a second context"
2445        );
2446    }
2447
2448    #[test]
2449    fn idempotency_evicts_after_ttl() {
2450        let store = InMemoryStore::new();
2451        let agent = AgentDid::new("did:web:agents.example.com:test");
2452        let resp = PublishResponse {
2453            registry_receipt: None,
2454            ctx_id: acdp_types::CtxId("acdp://r/12345678-1234-4321-8123-000000000099".into()),
2455            lineage_id: acdp_types::LineageId(
2456                "lin:sha256:9999999999999999999999999999999999999999999999999999999999999999"
2457                    .into(),
2458            ),
2459            version: 1,
2460            created_at: chrono::Utc::now(),
2461            status: Status::Active,
2462        };
2463        // Already-past expiration.
2464        let past = chrono::Utc::now() - chrono::Duration::seconds(1);
2465        store
2466            .idempotency_record(
2467                &agent,
2468                "expired",
2469                &acdp_types::ContentHash("sha256:0".into()),
2470                &resp,
2471                past,
2472            )
2473            .unwrap();
2474        // Lookup runs lazy eviction; the expired record MUST be gone.
2475        let prior = store.idempotency_lookup(&agent, "expired").unwrap();
2476        assert!(
2477            prior.is_none(),
2478            "lazy TTL eviction should drop expired record"
2479        );
2480    }
2481
2482    /// A receipts-advertising registry must refuse
2483    /// `publish_unverified_in_tenant_for_tests` identically to
2484    /// `publish_unverified_for_tests` (RFC-ACDP-0010 §7: no degraded
2485    /// mode) — the refusal is inherited by construction since the old
2486    /// method's body moved wholesale into the new one, but this proves
2487    /// it from the new name specifically.
2488    #[test]
2489    fn publish_unverified_in_tenant_for_tests_refuses_receipts_registry() {
2490        let mut c = caps();
2491        c.acdp_version = "0.2.0".into();
2492        let server = RegistryServer::new(InMemoryStore::new(), c, "registry.example.com")
2493            .with_receipt_signer(
2494                acdp_types::receipt::ReceiptSigner::new(
2495                    SigningKey::from_bytes(&[0x33u8; 32]),
2496                    "did:web:registry.example.com",
2497                    "did:web:registry.example.com#receipt-key-1",
2498                )
2499                .unwrap(),
2500            )
2501            .unwrap();
2502        let p = producer();
2503        let req = p
2504            .publish_request()
2505            .title("should be refused")
2506            .context_type(ContextType::DataSnapshot)
2507            .visibility(Visibility::Public)
2508            .build()
2509            .unwrap();
2510        let err = server
2511            .publish_unverified_in_tenant_for_tests(&req, None, None)
2512            .unwrap_err();
2513        assert!(
2514            matches!(err, AcdpError::SchemaViolation(_)),
2515            "expected SchemaViolation refusal on a receipts-advertising registry, got {err:?}"
2516        );
2517    }
2518
2519    // ── Tenancy-recording test store ────────────────────────────────────
2520    //
2521    // `InMemoryStore::commit_publish` deliberately discards `tenant`
2522    // (store.rs:676-678: "InMemoryStore does not model tenancy") since
2523    // it is a single-tenant reference/test backend — so testing tenancy
2524    // plumbing against it directly would prove nothing. `RecordingStore`
2525    // wraps an `InMemoryStore` for all real behavior and additionally
2526    // captures the `tenant` argument each `commit_publish` call receives.
2527
2528    /// Delegates every [`RegistryStore`] method to an inner
2529    /// [`InMemoryStore`], additionally recording `commit.tenant` from
2530    /// each [`RegistryStore::commit_publish`] call.
2531    struct RecordingStore {
2532        inner: InMemoryStore,
2533        tenants: std::sync::Mutex<Vec<Option<String>>>,
2534    }
2535
2536    impl RecordingStore {
2537        fn new() -> Self {
2538            Self {
2539                inner: InMemoryStore::new(),
2540                tenants: std::sync::Mutex::new(Vec::new()),
2541            }
2542        }
2543    }
2544
2545    impl RegistryStore for RecordingStore {
2546        fn put(&self, body: Body) -> Result<(), AcdpError> {
2547            self.inner.put(body)
2548        }
2549
2550        fn get(&self, ctx_id: &CtxId) -> Result<Option<FullContext>, AcdpError> {
2551            self.inner.get(ctx_id)
2552        }
2553
2554        fn lineage(&self, lineage_id: &LineageId) -> Result<Vec<FullContext>, AcdpError> {
2555            self.inner.lineage(lineage_id)
2556        }
2557
2558        fn current(&self, lineage_id: &LineageId) -> Result<Option<FullContext>, AcdpError> {
2559            self.inner.current(lineage_id)
2560        }
2561
2562        fn mark_superseded(&self, ctx_id: &CtxId) -> Result<(), AcdpError> {
2563            self.inner.mark_superseded(ctx_id)
2564        }
2565
2566        fn first_version_ctx_id(&self, lineage_id: &LineageId) -> Result<Option<CtxId>, AcdpError> {
2567            self.inner.first_version_ctx_id(lineage_id)
2568        }
2569
2570        fn search(
2571            &self,
2572            params: &SearchParams,
2573            requester: Option<&AgentDid>,
2574            anonymous_public_reads: bool,
2575        ) -> Result<SearchResponse, AcdpError> {
2576            self.inner.search(params, requester, anonymous_public_reads)
2577        }
2578
2579        fn idempotency_lookup(
2580            &self,
2581            agent_id: &AgentDid,
2582            key: &str,
2583        ) -> Result<Option<crate::registry::store::IdempotencyRecord>, AcdpError> {
2584            self.inner.idempotency_lookup(agent_id, key)
2585        }
2586
2587        fn idempotency_record(
2588            &self,
2589            agent_id: &AgentDid,
2590            key: &str,
2591            hash: &acdp_types::primitives::ContentHash,
2592            response: &PublishResponse,
2593            expires_at: chrono::DateTime<chrono::Utc>,
2594        ) -> Result<(), AcdpError> {
2595            self.inner
2596                .idempotency_record(agent_id, key, hash, response, expires_at)
2597        }
2598
2599        fn idempotency_evict_expired(
2600            &self,
2601            now: chrono::DateTime<chrono::Utc>,
2602        ) -> Result<(), AcdpError> {
2603            self.inner.idempotency_evict_expired(now)
2604        }
2605
2606        fn commit_publish(
2607            &self,
2608            commit: crate::registry::store::PublishCommit<'_>,
2609        ) -> Result<crate::registry::store::PublishCommitOutcome, AcdpError> {
2610            self.tenants
2611                .lock()
2612                .unwrap()
2613                .push(commit.tenant.map(String::from));
2614            self.inner.commit_publish(commit)
2615        }
2616
2617        fn commit_lifecycle_event(
2618            &self,
2619            event: &acdp_types::lifecycle::LifecycleEvent,
2620        ) -> Result<crate::registry::store::LifecycleCommitOutcome, AcdpError> {
2621            self.inner.commit_lifecycle_event(event)
2622        }
2623    }
2624
2625    /// Proves `tenant` reaches `PublishCommit.tenant` verbatim from
2626    /// `publish_unverified_in_tenant_for_tests`, in call order.
2627    ///
2628    /// What this does NOT prove: tenant *isolation* (that two tenants'
2629    /// data cannot leak into each other's reads) — that is the durable
2630    /// backends' contract (`store.rs:274-279`), entirely out of scope
2631    /// for `InMemoryStore`/`RecordingStore`, which is why this test only
2632    /// asserts on the recorded argument, not on any read-side behavior.
2633    #[test]
2634    fn tenant_reaches_publish_commit_verbatim() {
2635        let server = RegistryServer::new(RecordingStore::new(), caps(), "registry.example.com");
2636        let p = producer();
2637
2638        let req_a = p
2639            .publish_request()
2640            .title("tenant a")
2641            .context_type(ContextType::DataSnapshot)
2642            .visibility(Visibility::Public)
2643            .build()
2644            .unwrap();
2645        server
2646            .publish_unverified_in_tenant_for_tests(&req_a, None, Some("tenant-a"))
2647            .unwrap();
2648
2649        let req_b = p
2650            .publish_request()
2651            .title("tenant none")
2652            .context_type(ContextType::DataSnapshot)
2653            .visibility(Visibility::Public)
2654            .build()
2655            .unwrap();
2656        server
2657            .publish_unverified_in_tenant_for_tests(&req_b, None, None)
2658            .unwrap();
2659
2660        let recorded = server.store().tenants.lock().unwrap().clone();
2661        assert_eq!(
2662            recorded,
2663            vec![Some("tenant-a".to_string()), None],
2664            "tenant must reach PublishCommit.tenant verbatim, in call order"
2665        );
2666    }
2667
2668    // ── FEAT-05 rate limiter tests ─────────────────────────────────────
2669
2670    struct AlwaysDeny;
2671    impl crate::registry::RateLimiter for AlwaysDeny {
2672        fn check_publish(&self, agent_id: &AgentDid) -> Result<(), AcdpError> {
2673            Err(AcdpError::RateLimited(format!("blocked: {agent_id}")))
2674        }
2675    }
2676
2677    #[test]
2678    fn rate_limiter_blocks_publish_before_persist() {
2679        let server = RegistryServer::new(InMemoryStore::new(), caps(), "registry.example.com")
2680            .with_rate_limiter(AlwaysDeny);
2681        let p = producer();
2682        let req = p
2683            .publish_request()
2684            .title("blocked")
2685            .context_type(ContextType::DataSnapshot)
2686            .visibility(Visibility::Public)
2687            .build()
2688            .unwrap();
2689        let err = server.publish_unverified_for_tests(&req).unwrap_err();
2690        assert!(matches!(err, AcdpError::RateLimited(_)));
2691        // And the store is empty — the limiter MUST short-circuit before persist.
2692        let resp = server.search(&SearchParams::default(), None).unwrap();
2693        assert!(
2694            resp.matches.is_empty(),
2695            "rate-limited publish must not persist"
2696        );
2697    }
2698
2699    #[test]
2700    fn created_at_is_ms_truncated() {
2701        let server = RegistryServer::new(InMemoryStore::new(), caps(), "registry.example.com");
2702        let p = producer();
2703        let req = p
2704            .publish_request()
2705            .title("ms")
2706            .context_type(ContextType::DataSnapshot)
2707            .visibility(Visibility::Public)
2708            .build()
2709            .unwrap();
2710        let resp = server.publish_unverified_for_tests(&req).unwrap();
2711        // Nanosecond component of a ms-truncated timestamp is always a multiple of 1_000_000.
2712        assert_eq!(
2713            resp.created_at.timestamp_subsec_nanos() % 1_000_000,
2714            0,
2715            "created_at must be millisecond-truncated per RFC-ACDP-0001 §5.3"
2716        );
2717    }
2718
2719    // ── did:key publish (ACDP 0.2) ───────────────────────────────────────
2720
2721    fn did_key_request() -> acdp_types::publish::PublishRequest {
2722        let p = Producer::new_did_key(SigningKey::from_bytes(&[7u8; 32]));
2723        p.publish_request()
2724            .title("did:key publish")
2725            .context_type(ContextType::DataSnapshot)
2726            .visibility(Visibility::Public)
2727            .build()
2728            .unwrap()
2729    }
2730
2731    /// A registry that does NOT advertise `did:key` in
2732    /// `supported_did_methods` refuses a did:key publish with
2733    /// `key_resolution_failed` (permanent) — the anchor-plan decision.
2734    #[test]
2735    fn did_key_publish_rejected_when_not_advertised() {
2736        let server = RegistryServer::new(InMemoryStore::new(), caps(), "registry.example.com");
2737        let err = server
2738            .publish_verified_did_key(&did_key_request(), None)
2739            .unwrap_err();
2740        assert!(
2741            matches!(err, AcdpError::KeyResolution(ref m) if m.contains("supported_did_methods")),
2742            "got {err:?}"
2743        );
2744    }
2745
2746    /// With `did:key` advertised, the offline pipeline runs end-to-end:
2747    /// schema → hash → pure key resolution → signature → persistence.
2748    /// No resolver, no network — works in a `server`-only build.
2749    #[test]
2750    fn did_key_publish_verified_end_to_end() {
2751        let mut c = caps();
2752        c.supported_did_methods.push("did:key".into());
2753        let server = RegistryServer::new(InMemoryStore::new(), c, "registry.example.com");
2754        let req = did_key_request();
2755        let resp = server.publish_verified_did_key(&req, None).unwrap();
2756        assert_eq!(resp.ctx_id.authority(), "registry.example.com");
2757
2758        // Tampered title → hash mismatch caught before signature.
2759        let mut tampered = did_key_request();
2760        tampered.title = "tampered".into();
2761        let err = server
2762            .publish_verified_did_key(&tampered, None)
2763            .unwrap_err();
2764        assert!(matches!(err, AcdpError::HashMismatch { .. }), "got {err:?}");
2765    }
2766
2767    /// Upgrade boundary: a registry that enables receipts must still
2768    /// honor idempotent replays of records minted BEFORE the signer
2769    /// existed. The §7 no-degraded-mode check applies to newly inserted
2770    /// contexts only — a replayed pre-receipts response (no
2771    /// `registry_receipt`) is returned verbatim, not failed as a 500.
2772    #[test]
2773    fn receiptless_idempotent_replay_survives_enabling_receipts() {
2774        let mut c = caps();
2775        c.acdp_version = "0.2.0".into();
2776        c.supported_did_methods.push("did:key".into());
2777        c.supports_idempotency_key = true;
2778        c.limits.idempotency_key_ttl_seconds = Some(86_400);
2779        let server = RegistryServer::new(InMemoryStore::new(), c, "registry.example.com")
2780            .with_receipt_signer(
2781                acdp_types::receipt::ReceiptSigner::new(
2782                    SigningKey::from_bytes(&[0x11u8; 32]),
2783                    "did:web:registry.example.com",
2784                    "did:web:registry.example.com#receipt-key-1",
2785                )
2786                .unwrap(),
2787            )
2788            .unwrap();
2789
2790        // Simulate a record persisted before receipts were enabled: the
2791        // stored response carries no `registry_receipt`.
2792        let req = did_key_request();
2793        let pre_receipts_response = acdp_types::publish::PublishResponse {
2794            ctx_id: CtxId(format!(
2795                "acdp://registry.example.com/{}",
2796                uuid::Uuid::new_v4()
2797            )),
2798            lineage_id: acdp_crypto::derive_lineage_id(&CtxId(
2799                "acdp://registry.example.com/v1".into(),
2800            )),
2801            version: 1,
2802            created_at: acdp_primitives::time::trunc_ms(chrono::Utc::now()),
2803            status: Status::Active,
2804            registry_receipt: None,
2805        };
2806        server
2807            .store()
2808            .idempotency_record(
2809                &req.agent_id,
2810                "pre-receipts-key",
2811                &req.content_hash,
2812                &pre_receipts_response,
2813                chrono::Utc::now() + chrono::Duration::hours(1),
2814            )
2815            .unwrap();
2816
2817        // Same agent + key + content_hash → the replay must return the
2818        // original receipt-less response, not RegistryInternal.
2819        let resp = server
2820            .publish_verified_did_key(&req, Some("pre-receipts-key"))
2821            .expect("replay of a pre-receipts record must succeed");
2822        assert_eq!(resp.ctx_id, pre_receipts_response.ctx_id);
2823        assert!(
2824            resp.registry_receipt.is_none(),
2825            "replay returns the original response verbatim"
2826        );
2827
2828        // A FRESH publish on the same server still enforces minting.
2829        let p2 = Producer::new_did_key(SigningKey::from_bytes(&[8u8; 32]));
2830        let fresh = p2
2831            .publish_request()
2832            .title("fresh after enabling receipts")
2833            .context_type(ContextType::DataSnapshot)
2834            .visibility(Visibility::Public)
2835            .build()
2836            .unwrap();
2837        let fresh_resp = server.publish_verified_did_key(&fresh, None).unwrap();
2838        assert!(
2839            fresh_resp.registry_receipt.is_some(),
2840            "new inserts on a receipts registry must mint"
2841        );
2842    }
2843
2844    /// A pinned-key publish (the caller already verified the signature
2845    /// against an operator-pinned key, e.g. a demo registry's
2846    /// `playground.pinned_keys` allowlist) mints a receipt whose
2847    /// `key_fingerprint` matches the pinned key — proving
2848    /// `publish_pinned_verified_in_tenant` is safe on a
2849    /// receipts-advertising registry, unlike `publish_unverified_for_tests`.
2850    #[test]
2851    fn pinned_verified_publish_mints_receipt_with_correct_fingerprint() {
2852        use base64::{engine::general_purpose::STANDARD, Engine};
2853
2854        let key = SigningKey::from_bytes(&[3u8; 32]);
2855        let verifying_key_bytes = key.verifying_key_bytes();
2856        let pub_b64 = STANDARD.encode(verifying_key_bytes);
2857        let did = "did:web:agents.example.com:pinned-agent";
2858        let p = Producer::new(key, AgentDid::new(did), format!("{did}#key-1"));
2859        let req = p
2860            .publish_request()
2861            .title("pinned publish")
2862            .context_type(ContextType::DataSnapshot)
2863            .visibility(Visibility::Public)
2864            .build()
2865            .unwrap();
2866
2867        let mut c = caps();
2868        c.acdp_version = "0.2.0".into();
2869        let server = RegistryServer::new(InMemoryStore::new(), c, "registry.example.com")
2870            .with_receipt_signer(
2871                acdp_types::receipt::ReceiptSigner::new(
2872                    SigningKey::from_bytes(&[0x22u8; 32]),
2873                    "did:web:registry.example.com",
2874                    "did:web:registry.example.com#receipt-key-1",
2875                )
2876                .unwrap(),
2877            )
2878            .unwrap();
2879
2880        let resp = server
2881            .publish_pinned_verified_in_tenant(&req, None, None, &pub_b64, "ed25519")
2882            .expect("pinned-verified publish must succeed on a receipts registry");
2883        let receipt = resp
2884            .registry_receipt
2885            .expect("a receipts-advertising registry must mint a receipt");
2886        assert_eq!(
2887            receipt["key_fingerprint"].as_str().unwrap(),
2888            acdp_crypto::fingerprint::fingerprint_ed25519(&verifying_key_bytes)
2889        );
2890    }
2891
2892    /// Without a receipt signer configured, `publish_pinned_verified_in_tenant`
2893    /// still succeeds — it just mints no receipt (the fingerprint is only
2894    /// ever needed for the receipt binding).
2895    #[test]
2896    fn pinned_verified_publish_without_receipt_signer_succeeds_with_no_receipt() {
2897        use base64::{engine::general_purpose::STANDARD, Engine};
2898
2899        let key = SigningKey::from_bytes(&[4u8; 32]);
2900        let pub_b64 = STANDARD.encode(key.verifying_key_bytes());
2901        let did = "did:web:agents.example.com:pinned-agent-2";
2902        let p = Producer::new(key, AgentDid::new(did), format!("{did}#key-1"));
2903        let req = p
2904            .publish_request()
2905            .title("pinned publish, no receipts")
2906            .context_type(ContextType::DataSnapshot)
2907            .visibility(Visibility::Public)
2908            .build()
2909            .unwrap();
2910
2911        let server = RegistryServer::new(InMemoryStore::new(), caps(), "registry.example.com");
2912        let resp = server
2913            .publish_pinned_verified_in_tenant(&req, None, None, &pub_b64, "ed25519")
2914            .unwrap();
2915        assert!(resp.registry_receipt.is_none());
2916    }
2917
2918    /// `publish_verified_did_key` refuses did:web producers — they need
2919    /// the resolver-backed `publish_verified`.
2920    #[test]
2921    fn did_key_publish_path_refuses_did_web() {
2922        let server = RegistryServer::new(InMemoryStore::new(), caps(), "registry.example.com");
2923        let p = producer();
2924        let req = p
2925            .publish_request()
2926            .title("did:web on the offline path")
2927            .context_type(ContextType::DataSnapshot)
2928            .visibility(Visibility::Public)
2929            .build()
2930            .unwrap();
2931        let err = server.publish_verified_did_key(&req, None).unwrap_err();
2932        assert!(
2933            matches!(err, AcdpError::KeyResolution(_)),
2934            "did:web on the offline path must be refused, got {err:?}"
2935        );
2936    }
2937
2938    // ── Phase 8: prove/commit split (#273) ────────────────────────────
2939
2940    /// `prove_publish_identity_did_key` + `commit_proven` must succeed and
2941    /// persist exactly like the composed
2942    /// `publish_verified_did_key_in_tenant_with_outcome` they replace the
2943    /// body of — proving the split is a genuine decomposition of the
2944    /// existing pipeline, not a different one.
2945    #[test]
2946    fn prove_then_commit_did_key_round_trip_matches_direct_publish() {
2947        let mut c = caps();
2948        c.supported_did_methods.push("did:key".into());
2949        let server = RegistryServer::new(InMemoryStore::new(), c, "registry.example.com");
2950        let req = did_key_request();
2951
2952        let proven = server
2953            .prove_publish_identity_did_key(&req)
2954            .expect("prove must succeed for a validly signed did:key request");
2955        assert_eq!(proven.agent_id(), &req.agent_id);
2956        assert_eq!(proven.request().content_hash, req.content_hash);
2957
2958        // `commit_proven` below debug_asserts recomputed_hash == request().content_hash
2959        // internally — this round trip is what exercises that invariant.
2960        let outcome = server
2961            .commit_proven(proven, None, None)
2962            .expect("commit_proven must persist a proven publish");
2963        let resp = outcome.into_response();
2964        assert_eq!(resp.ctx_id.authority(), "registry.example.com");
2965        assert_eq!(resp.version, 1);
2966
2967        let ctx = server.retrieve(&resp.ctx_id, None).unwrap().unwrap();
2968        assert_eq!(ctx.body.content_hash, req.content_hash);
2969    }
2970
2971    /// The pinned-key `prove`/`commit` split must still thread the
2972    /// fingerprint through to receipt minting exactly like
2973    /// `publish_pinned_verified_in_tenant_with_outcome` does directly.
2974    #[test]
2975    fn prove_then_commit_pinned_round_trip_mints_receipt_with_correct_fingerprint() {
2976        use base64::{engine::general_purpose::STANDARD, Engine};
2977
2978        let key = SigningKey::from_bytes(&[5u8; 32]);
2979        let verifying_key_bytes = key.verifying_key_bytes();
2980        let pub_b64 = STANDARD.encode(verifying_key_bytes);
2981        let did = "did:web:agents.example.com:pinned-proven-agent";
2982        let p = Producer::new(key, AgentDid::new(did), format!("{did}#key-1"));
2983        let req = p
2984            .publish_request()
2985            .title("pinned publish via prove/commit")
2986            .context_type(ContextType::DataSnapshot)
2987            .visibility(Visibility::Public)
2988            .build()
2989            .unwrap();
2990
2991        let mut c = caps();
2992        c.acdp_version = "0.2.0".into();
2993        let server = RegistryServer::new(InMemoryStore::new(), c, "registry.example.com")
2994            .with_receipt_signer(
2995                acdp_types::receipt::ReceiptSigner::new(
2996                    SigningKey::from_bytes(&[0x33u8; 32]),
2997                    "did:web:registry.example.com",
2998                    "did:web:registry.example.com#receipt-key-1",
2999                )
3000                .unwrap(),
3001            )
3002            .unwrap();
3003
3004        let proven = server
3005            .prove_publish_identity_pinned(&req, &pub_b64, "ed25519")
3006            .expect("prove must succeed for a validly pinned request");
3007        let expected_fp = acdp_crypto::fingerprint::fingerprint_ed25519(&verifying_key_bytes);
3008        assert_eq!(proven.key_fingerprint(), Some(expected_fp.as_str()));
3009
3010        let outcome = server
3011            .commit_proven(proven, None, None)
3012            .expect("commit_proven must persist and mint a receipt");
3013        let resp = outcome.into_response();
3014        let receipt = resp
3015            .registry_receipt
3016            .expect("a receipts-advertising registry must mint a receipt");
3017        assert_eq!(receipt["key_fingerprint"].as_str().unwrap(), expected_fp);
3018    }
3019
3020    /// `prove_publish_identity` (the did:web variant) runs the same
3021    /// pre-resolution rejections as `publish_verified` — proving the
3022    /// async prove entry point exists and is wired into the same
3023    /// validation pipeline, without needing a live/mocked resolver.
3024    #[cfg(feature = "client")]
3025    #[tokio::test]
3026    async fn prove_publish_identity_rejects_non_did_web_key_id_before_producing_proven() {
3027        let server = RegistryServer::new(InMemoryStore::new(), caps(), "registry.example.com");
3028        let p = producer();
3029        let mut req = p
3030            .publish_request()
3031            .title("v1")
3032            .context_type(ContextType::DataSnapshot)
3033            .visibility(Visibility::Public)
3034            .build()
3035            .unwrap();
3036        let did_key = acdp_did::key::did_key_from_ed25519(
3037            &SigningKey::from_bytes(&[10u8; 32]).verifying_key_bytes(),
3038        );
3039        req.signature.key_id = acdp_did::key::did_key_url(&did_key).unwrap();
3040        let resolver = acdp_did::WebResolver::new();
3041        let err = server
3042            .prove_publish_identity(&req, &resolver)
3043            .await
3044            .unwrap_err();
3045        match err {
3046            AcdpError::KeyNotAuthorized(msg) => assert!(msg.contains("did:web")),
3047            other => panic!("expected KeyNotAuthorized for non-did:web, got {other:?}"),
3048        }
3049    }
3050
3051    /// `commit_proven` must refuse a `Proven` established against a
3052    /// different registry authority rather than silently persisting it —
3053    /// the "prove against server A, commit on server B" footgun the
3054    /// authority check exists to close.
3055    #[test]
3056    fn commit_proven_rejects_proven_from_different_authority() {
3057        let mut c1 = caps();
3058        c1.supported_did_methods.push("did:key".into());
3059        let mut c2 = caps();
3060        c2.supported_did_methods.push("did:key".into());
3061        let server_a = RegistryServer::new(InMemoryStore::new(), c1, "registry-a.example.com");
3062        let server_b = RegistryServer::new(InMemoryStore::new(), c2, "registry-b.example.com");
3063
3064        let req = did_key_request();
3065        let proven = server_a
3066            .prove_publish_identity_did_key(&req)
3067            .expect("prove must succeed against server A");
3068
3069        let err = server_b
3070            .commit_proven(proven, None, None)
3071            .expect_err("commit_proven must refuse a Proven minted for a different authority");
3072        match err {
3073            AcdpError::RegistryInternal(msg) => {
3074                assert!(
3075                    msg.contains("registry-a.example.com")
3076                        && msg.contains("registry-b.example.com"),
3077                    "error should name both authorities, got: {msg}"
3078                );
3079            }
3080            other => panic!("expected RegistryInternal authority-mismatch, got {other:?}"),
3081        }
3082    }
3083
3084    /// The `authority` string alone is not a full registry-instance
3085    /// identity check: two `RegistryServer`s can share an `authority`
3086    /// while genuinely differing in configuration. `commit_proven` must
3087    /// refuse — not silently persist a receipt-less context — when a
3088    /// `Proven` minted on a signer-less instance is committed on a
3089    /// receipts-advertising instance that merely happens to share the
3090    /// first one's authority (RFC-ACDP-0010 §7: no degraded mode). Before
3091    /// the fix this reproduces, the commit succeeded and the persisted
3092    /// context carried `registry_receipt: None` on a registry whose own
3093    /// capabilities advertise receipts.
3094    #[test]
3095    fn commit_proven_refuses_cross_instance_same_authority_signer_mismatch() {
3096        let mut c = caps();
3097        c.supported_did_methods.push("did:key".into());
3098        c.registry_did = "did:web:shared.example.com".into();
3099        c.acdp_version = "0.2.0".into();
3100        let signer_less =
3101            RegistryServer::new(InMemoryStore::new(), c.clone(), "shared.example.com");
3102        let receipts_enabled = RegistryServer::new(InMemoryStore::new(), c, "shared.example.com")
3103            .with_receipt_signer(
3104                acdp_types::receipt::ReceiptSigner::new(
3105                    SigningKey::from_bytes(&[0x44u8; 32]),
3106                    "did:web:shared.example.com",
3107                    "did:web:shared.example.com#receipt-key-1",
3108                )
3109                .unwrap(),
3110            )
3111            .unwrap();
3112
3113        let req = did_key_request();
3114        let proven = signer_less
3115            .prove_publish_identity_did_key(&req)
3116            .expect("prove must succeed against the signer-less instance");
3117        assert!(
3118            proven.key_fingerprint().is_none(),
3119            "a signer-less instance must not compute a fingerprint"
3120        );
3121
3122        let err = receipts_enabled
3123            .commit_proven(proven, None, None)
3124            .expect_err(
3125                "commit_proven must refuse a fingerprint-less Proven on a receipts-advertising \
3126                 registry, even though the authority string matches",
3127            );
3128        match err {
3129            AcdpError::RegistryInternal(msg) => {
3130                assert!(
3131                    msg.contains("no producer key fingerprint"),
3132                    "error should name the actual mistake, got: {msg}"
3133                );
3134            }
3135            other => panic!("expected RegistryInternal fingerprint-mismatch, got {other:?}"),
3136        }
3137    }
3138
3139    /// The `prove → commit` split's core invariant: `commit_proven` is
3140    /// only reachable via a `Proven`, and the only way to mint one is a
3141    /// successful `prove_publish_identity*` call — a request that fails
3142    /// RFC-ACDP-0003 §2.1 verification (here: a tampered body, caught by
3143    /// the hash-mismatch check) produces no `Proven` at all, so there is
3144    /// no path from a bare `PublishRequest` to `commit_proven` for it.
3145    #[test]
3146    fn prove_publish_identity_did_key_produces_no_proven_for_a_tampered_request() {
3147        let mut c = caps();
3148        c.supported_did_methods.push("did:key".into());
3149        let server = RegistryServer::new(InMemoryStore::new(), c, "registry.example.com");
3150
3151        let mut tampered = did_key_request();
3152        tampered.title = "tampered".into();
3153        let err = server
3154            .prove_publish_identity_did_key(&tampered)
3155            .expect_err("prove must fail for a request whose hash no longer matches its body");
3156        assert!(matches!(err, AcdpError::HashMismatch { .. }), "got {err:?}");
3157        // No `Proven` was produced for `tampered` — structurally, nothing
3158        // else in this crate's public API could have manufactured one
3159        // either, since `Proven` has no public constructor.
3160    }
3161
3162    // ── the insert/replay distinction, per entry point ───────────────────
3163    //
3164    // These are the tests that did not exist anywhere before U-564. The
3165    // consuming registry's own idem-001..004 chain looks like it covers this
3166    // and does not: it builds its harness with the playground enabled and no
3167    // pinned keys, so every publish in that chain takes the one branch that
3168    // re-queries `idempotency_lookup` by hand.
3169    //
3170    // Stated precisely, because a looser earlier version of this comment was
3171    // simply false: what was missing on the three branches that go through
3172    // `commit_via_store` is coverage of the insert/replay DISTINCTION, not
3173    // replay coverage as such. `receiptless_idempotent_replay_survives_enabling_receipts`
3174    // predates this work and does drive a did:key replay — and it, not
3175    // anything added here, is what first caught a delegate that dropped the
3176    // receipt. What nothing asserted was WHICH of the two a publish was, which
3177    // is the only thing a front-end can use to choose 201 over 200, and that is
3178    // why flattening the outcome went unnoticed.
3179
3180    /// Caps that advertise `did:key` AND idempotency. `supports_idempotency_key`
3181    /// is the gate `commit_via_store` reads before it passes a key to the store
3182    /// at all — with the default `false` from [`caps`], a second publish with
3183    /// the same key is a second INSERT and no replay is reachable.
3184    ///
3185    /// Measured, because the first version of this note claimed the opposite
3186    /// and was wrong: dropping `supports_idempotency_key = true` — from here
3187    /// and from the inline `caps()` in the pinned test — makes these tests
3188    /// FAIL (117 passed, 3 failed), it does not make them pass vacuously.
3189    /// Three distinct tests fail with three distinct messages, not one
3190    /// assertion three times. The cap is load-bearing for reachability, and
3191    /// its absence is loud rather than silent.
3192    fn caps_idempotent_did_key() -> CapabilitiesDocument {
3193        let mut c = caps();
3194        c.supported_did_methods.push("did:key".into());
3195        c.supports_idempotency_key = true;
3196        c.limits.idempotency_key_ttl_seconds = Some(86_400);
3197        c
3198    }
3199
3200    /// did:key branch: first publish inserts, the same request with the same
3201    /// `Idempotency-Key` replays.
3202    ///
3203    /// A registry front-end reads exactly this to choose `201 Created` +
3204    /// `Location` vs `200 OK`; RFC-ACDP-0003's idem-002 requires 200 on the
3205    /// second call and says explicitly NOT 201.
3206    #[test]
3207    fn did_key_publish_reports_inserted_then_idempotent_replay() {
3208        let server = RegistryServer::new(
3209            InMemoryStore::new(),
3210            caps_idempotent_did_key(),
3211            "registry.example.com",
3212        );
3213        let req = did_key_request();
3214
3215        let first = server
3216            .publish_verified_did_key_in_tenant_with_outcome(&req, Some("k-did-key"), None)
3217            .expect("first publish must succeed");
3218        assert!(
3219            !first.is_replay(),
3220            "a first publish is an insert, not a replay"
3221        );
3222        assert!(matches!(first, PublishCommitOutcome::Inserted(_)));
3223
3224        let second = server
3225            .publish_verified_did_key_in_tenant_with_outcome(&req, Some("k-did-key"), None)
3226            .expect("same-hash retry with the same key must succeed");
3227        assert!(
3228            second.is_replay(),
3229            "a same-key same-hash retry is a replay — answering 201 here violates idem-002"
3230        );
3231        assert!(matches!(second, PublishCommitOutcome::IdempotentReplay(_)));
3232
3233        // idem-002 also requires the replay to return the ORIGINAL response,
3234        // so assert identity rather than merely "it replayed".
3235        assert_eq!(
3236            first.response().ctx_id,
3237            second.response().ctx_id,
3238            "a replay must return the original response verbatim"
3239        );
3240    }
3241
3242    /// Pinned branch: same property, reached through a different entry point.
3243    ///
3244    /// Worth its own test rather than trusting that it shares
3245    /// `commit_via_store` with the did:key path: what is under test is each
3246    /// PUBLIC entry point's contract, and a delegate that dropped the outcome
3247    /// would be invisible to a test of the other one.
3248    #[test]
3249    fn pinned_publish_reports_inserted_then_idempotent_replay() {
3250        use base64::{engine::general_purpose::STANDARD, Engine};
3251
3252        let key = SigningKey::from_bytes(&[4u8; 32]);
3253        let pub_b64 = STANDARD.encode(key.verifying_key_bytes());
3254        let did = "did:web:agents.example.com:pinned-idem";
3255        let p = Producer::new(key, AgentDid::new(did), format!("{did}#key-1"));
3256        let req = p
3257            .publish_request()
3258            .title("pinned publish, idempotent retry")
3259            .context_type(ContextType::DataSnapshot)
3260            .visibility(Visibility::Public)
3261            .build()
3262            .unwrap();
3263
3264        let mut c = caps();
3265        c.supports_idempotency_key = true;
3266        c.limits.idempotency_key_ttl_seconds = Some(86_400);
3267        let server = RegistryServer::new(InMemoryStore::new(), c, "registry.example.com");
3268
3269        let first = server
3270            .publish_pinned_verified_in_tenant_with_outcome(
3271                &req,
3272                Some("k-pinned"),
3273                None,
3274                &pub_b64,
3275                "ed25519",
3276            )
3277            .expect("first pinned publish must succeed");
3278        assert!(!first.is_replay(), "a first publish is an insert");
3279
3280        let second = server
3281            .publish_pinned_verified_in_tenant_with_outcome(
3282                &req,
3283                Some("k-pinned"),
3284                None,
3285                &pub_b64,
3286                "ed25519",
3287            )
3288            .expect("pinned same-hash retry must succeed");
3289        assert!(
3290            second.is_replay(),
3291            "a same-key same-hash pinned retry is a replay"
3292        );
3293        assert_eq!(first.response().ctx_id, second.response().ctx_id);
3294    }
3295
3296    /// The bare-response entry points must keep returning exactly what they
3297    /// returned before U-564 — they are now one-line delegates, and this pins
3298    /// that the delegation is lossless rather than assuming it.
3299    ///
3300    /// Compared across a REPLAY, on one server, deliberately. Two independent
3301    /// inserts can never be compared field-for-field: the store assigns a
3302    /// fresh `ctx_id` per insert and `lineage_id` is derived from it, so an
3303    /// insert-vs-insert test can only assert the handful of fields the request
3304    /// determines — which is exactly the kind of weakened assertion that
3305    /// passes while the interesting field differs. Replaying the first publish
3306    /// through the bare entry point makes the two responses the SAME record,
3307    /// so full equality is meaningful.
3308    #[test]
3309    fn bare_entry_point_matches_its_outcome_twin() {
3310        // A receipt signer is attached DELIBERATELY. Without one,
3311        // `registry_receipt` is `None` on both sides and the "receipt
3312        // included" half of the assertion below is unbacked — a delegate that
3313        // dropped the receipt would sail through. With one, `minted_expected`
3314        // is true (it is `minter.is_some()`, and the minter needs both a
3315        // signer and a producer fingerprint), so the insert carries a real
3316        // receipt and the replay must return it verbatim.
3317        let mut c = caps_idempotent_did_key();
3318        c.acdp_version = "0.2.0".into();
3319        let server = RegistryServer::new(InMemoryStore::new(), c, "registry.example.com")
3320            .with_receipt_signer(
3321                acdp_types::receipt::ReceiptSigner::new(
3322                    SigningKey::from_bytes(&[0x21u8; 32]),
3323                    "did:web:registry.example.com",
3324                    "did:web:registry.example.com#receipt-key-1",
3325                )
3326                .unwrap(),
3327            )
3328            .unwrap();
3329        let req = did_key_request();
3330
3331        let inserted = server
3332            .publish_verified_did_key_in_tenant_with_outcome(&req, Some("k-a"), None)
3333            .unwrap();
3334        assert!(
3335            inserted.response().registry_receipt.is_some(),
3336            "fixture precondition: the insert must actually mint a receipt, or \
3337             the receipt half of this test proves nothing"
3338        );
3339        assert!(!inserted.is_replay());
3340        let via_twin = inserted.into_response();
3341
3342        let via_bare = server
3343            .publish_verified_did_key_in_tenant(&req, Some("k-a"), None)
3344            .unwrap();
3345
3346        // `PublishResponse` has no `PartialEq`, and comparing a chosen subset
3347        // of fields is how a delegate that drops one goes unnoticed. Compare
3348        // the serialized form instead: it is the whole wire surface, which is
3349        // also the surface this contract is actually about.
3350        assert_eq!(
3351            serde_json::to_value(&via_twin).unwrap(),
3352            serde_json::to_value(&via_bare).unwrap(),
3353            "the bare entry point must return the replayed record verbatim — \
3354             it is a delegate to the twin and must lose nothing, receipt included"
3355        );
3356    }
3357}