Skip to main content

hyprstream_core/services/oauth/
xrpc.rs

1//! `com.atproto.*` XRPC server surface — MVP public-read slice (#1112).
2//!
3//! HTTP XRPC endpoints served from the same Axum surface that hosts OAuth and
4//! `/.well-known/atproto-did` (see `super::did_document`). `hyprstream-pds`
5//! remains deliberately no-networking: this module is the serving layer that
6//! calls its data functions (`Commit`/`MST`/`car::build_record_proof_car`).
7//!
8//! # Endpoints
9//!
10//! | Method | Path (under `/xrpc/`) | Notes |
11//! |--------|-----------------------|-------|
12//! | GET    | `com.atproto.identity.resolveHandle` | handle→DID |
13//! | GET    | `com.atproto.repo.describeRepo`     | DID/handle + commit head + didDoc |
14//! | GET    | `com.atproto.repo.getRecord`        | record JSON (optional `cid` pinning) |
15//! | GET    | `com.atproto.sync.getRepo`          | full-repo CARv1 export (lazy stream) |
16//! | GET    | `com.atproto.server.describeServer` | server DID and account-domain policy |
17//! | GET    | `com.atproto.server.getServiceAuth` | protected hosted-account service JWT |
18//!
19//! **`createSession` remains out of scope.** Password / app-password
20//! verification and credential minting require the account authority contract.
21//! `getSession` is available only when an explicit native session resolver is
22//! installed and is protected by the existing bearer/DPoP middleware.
23//!
24//! # Feature gate
25//!
26//! Routes are mounted only when `OAuthConfig::xrpc_read_slice` is `true`
27//! (defaults to `false`). The in-process [`XrpcRepoStore`] starts empty; the
28//! write path (#910) populates it with [`RepoSnapshot`]s whose [`public`]
29//! flag is `true`. Only `public` snapshots are served by these endpoints.
30//!
31//! # Out of scope
32//!
33//! - `com.atproto.sync.subscribeRepos` (firehose) — issue #1112 defers it.
34//! - Write path (`repo.createRecord` etc.) — sequenced with #910.
35//! - `createSession` — sequenced with the account credential contract (#1113/#948).
36
37mod durable_reads;
38mod record_validation;
39
40use std::collections::BTreeMap;
41use std::sync::Arc;
42
43use axum::{
44    extract::{Extension, RawQuery, State},
45    http::{header, HeaderMap, StatusCode},
46    response::{IntoResponse, Response},
47};
48use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
49use bytes::Bytes;
50use futures::{stream, Stream};
51use p256::ecdsa::VerifyingKey;
52use rand::RngCore as _;
53use serde_json::{json, Value};
54use tokio::sync::{OwnedSemaphorePermit, RwLock, Semaphore};
55
56use hyprstream_pds::atproto_cbor::AtprotoRecordKey;
57use hyprstream_pds::car::{
58    build_record_proof_car, car_block_bytes, car_header_bytes, parse_car_v1,
59};
60use hyprstream_pds::commit::{Commit, PublishedAtprotoKeys};
61use hyprstream_pds::dag_cbor::DagCbor;
62use hyprstream_pds::mst::{Node, NodeData};
63use hyprstream_pds::record::{ModelRecord, COLLECTION_NSID};
64use hyprstream_pds::repo_authority::accept_repo_authority;
65use hyprstream_pds::tid::Tid;
66use hyprstream_pds::Cid;
67
68use super::did_document::{build_did_document, AtprotoIdentity};
69use super::state::OAuthState;
70use super::{
71    auth::{self, AuthenticatedUser},
72    token_exchange::{ATPROTO_SESSION_EXCHANGE_NSID, MAX_ATPROTO_SERVICE_TOKEN_LIFETIME},
73};
74
75/// `ai.hyprstream.model` is the only collection this PDS hosts today.
76pub const HOSTED_COLLECTION: &str = COLLECTION_NSID;
77
78/// Protected hosted-PDS service-auth endpoint from the ATProto server lexicon.
79pub const GET_SERVICE_AUTH_PATH: &str = "/xrpc/com.atproto.server.getServiceAuth";
80
81const DEFAULT_SERVICE_AUTH_TTL_SECONDS: i64 = 60;
82const MAX_SERVICE_AUTH_PARAMETER_BYTES: usize = 2_048;
83
84/// Maximum number of concurrent `sync.getRepo` (full-CAR export) requests.
85/// Each request streams the entire repo; bounding concurrency prevents
86/// memory/CPU exhaustion from parallel full-repo exports.
87pub const GET_REPO_CONCURRENCY: usize = 4;
88/// Snapshot/encoding work has its own bound; slow CAR bodies cannot hold it.
89const DURABLE_SNAPSHOT_CONCURRENCY: usize = 4;
90
91// ─────────────────────────────────────────────────────────────────────────────
92// RepoSnapshot + XrpcRepoStore
93// ─────────────────────────────────────────────────────────────────────────────
94
95/// The five XRPC read-slice route declarations, as a sub-`Router` parameterised
96/// over `Arc<OAuthState>`. This is the single source of truth for the XRPC route
97/// table — `oauth::create_app` merges it conditionally on `xrpc_read_slice`,
98/// and tests mount it directly. Changing the URI or handler here changes both.
99pub fn xrpc_routes() -> axum::Router<Arc<OAuthState>> {
100    use axum::routing::get;
101    axum::Router::new()
102        .route(
103            "/xrpc/com.atproto.identity.resolveHandle",
104            get(resolve_handle),
105        )
106        .route(
107            "/xrpc/com.atproto.server.describeServer",
108            get(describe_server),
109        )
110        .route("/xrpc/com.atproto.repo.describeRepo", get(describe_repo))
111        .route("/xrpc/com.atproto.repo.getRecord", get(get_record))
112        .route("/xrpc/com.atproto.sync.getRepo", get(get_repo))
113}
114
115/// The one-record public read when the broader hosted-account XRPC slice is
116/// disabled. No other XRPC route or hosted-account record becomes reachable.
117pub fn public_canary_routes() -> axum::Router<Arc<OAuthState>> {
118    use axum::routing::get;
119    axum::Router::new().route(
120        "/xrpc/com.atproto.repo.getRecord",
121        get(public_canary_get_record),
122    )
123}
124
125/// Protected standard repository write routes. These are mounted only when a
126/// public writer is explicitly installed in OAuthState; the default remains
127/// read-only until account/session authorization is configured.
128pub fn xrpc_write_routes() -> axum::Router<Arc<OAuthState>> {
129    use axum::routing::post;
130    axum::Router::new().route("/xrpc/com.atproto.repo.createRecord", post(create_record))
131}
132
133/// Native account authority's answer for an authenticated `getSession` query.
134/// The resolver owns handle, DID-document and account lifecycle truth; this
135/// adapter never derives a handle from an unverified DID string.
136#[derive(Clone, Debug, Default)]
137pub struct AtprotoSessionInfo {
138    pub handle: String,
139    pub did_doc: Option<Value>,
140    pub email: Option<String>,
141    pub email_confirmed: Option<bool>,
142    pub email_auth_factor: Option<bool>,
143    pub active: bool,
144    pub status: Option<String>,
145}
146
147/// Explicit native authority seam for standard `getSession`.
148///
149/// Implementations must bind the returned handle and lifecycle state to the
150/// requested DID using the authoritative account records. Returning `None`
151/// means the DID is not a locally hosted account. No default implementation is
152/// installed, so adding this interface cannot expose account state by itself.
153#[async_trait::async_trait]
154pub trait AtprotoSessionResolver: Send + Sync {
155    async fn resolve_session(&self, did: &str) -> anyhow::Result<Option<AtprotoSessionInfo>>;
156}
157
158/// Protected standard session read route. It is mounted only when an
159/// authority-provided [`AtprotoSessionResolver`] is installed.
160pub fn xrpc_session_routes() -> axum::Router<Arc<OAuthState>> {
161    use axum::routing::get;
162    axum::Router::new().route("/xrpc/com.atproto.server.getSession", get(get_session))
163}
164
165/// An in-memory snapshot of one repo's signed state — enough to answer the
166/// public read slice (`describeRepo` / `getRecord` / `sync.getRepo`).
167#[derive(Clone, Debug)]
168pub struct RepoSnapshot {
169    pub did: String,
170    pub handle: String,
171    pub commit: Commit,
172    pub node_blocks: Vec<(Cid, NodeData)>,
173    pub records: BTreeMap<Tid, ModelRecord>,
174    pub atproto_vk: VerifyingKey,
175    /// **Publication boundary.** When `true`, this snapshot is anonymously
176    /// readable via the public XRPC read endpoints. When `false`, the public
177    /// read handlers act as though the repo does not exist.
178    pub public: bool,
179}
180
181impl RepoSnapshot {
182    pub fn root_cid(&self) -> Cid {
183        self.commit.data
184    }
185
186    pub fn record_by_rkey(&self, rkey: &str) -> Option<(&ModelRecord, Cid)> {
187        let tid = Tid::parse(rkey).ok()?;
188        let rec = self.records.get(&tid)?;
189        Some((rec, rec.cid()))
190    }
191
192    pub fn record_proof_car(&self, rkey: &str) -> Option<Vec<u8>> {
193        let tid = Tid::parse(rkey).ok()?;
194        let rec = self.records.get(&tid)?;
195        let cids: BTreeMap<Tid, Cid> = self.records.iter().map(|(t, r)| (*t, r.cid())).collect();
196        let tree = Node::from_records(HOSTED_COLLECTION, &cids);
197        let proof = tree.proof(HOSTED_COLLECTION, &tid)?;
198        Some(build_record_proof_car(
199            &self.commit,
200            &proof,
201            &self.node_blocks,
202            rec,
203        ))
204    }
205
206    pub fn record_json(&self, rkey: &str, rec: &ModelRecord) -> Value {
207        let uri = format!("at://{}/{HOSTED_COLLECTION}/{rkey}", self.did);
208        json!({
209            "uri": uri,
210            "cid": rec.cid().to_string(),
211            "value": {
212                "$type": HOSTED_COLLECTION,
213                "repo": rec.repo,
214                "currentOid": rec.current_oid,
215                "createdAt": rec.created_at,
216            }
217        })
218    }
219
220    fn did_doc(&self, issuer_url: &str) -> Value {
221        let atproto = AtprotoIdentity {
222            p256_vk: &self.atproto_vk,
223            handle: &self.handle,
224            drain: None,
225            lead: None,
226        };
227        build_did_document(&self.did, issuer_url, &[], Some(&atproto), &[], None, None)
228    }
229}
230
231/// In-process registry of hosted repos, keyed by DID.
232#[derive(Debug)]
233pub struct XrpcRepoStore {
234    by_did: RwLock<BTreeMap<String, Arc<RepoSnapshot>>>,
235    get_repo_sema: Arc<Semaphore>,
236    snapshot_work_sema: Arc<Semaphore>,
237}
238
239impl Default for XrpcRepoStore {
240    fn default() -> Self {
241        Self {
242            by_did: RwLock::new(BTreeMap::new()),
243            get_repo_sema: Arc::new(Semaphore::new(GET_REPO_CONCURRENCY)),
244            snapshot_work_sema: Arc::new(Semaphore::new(DURABLE_SNAPSHOT_CONCURRENCY)),
245        }
246    }
247}
248
249impl XrpcRepoStore {
250    pub fn new() -> Self {
251        Self::default()
252    }
253
254    /// Insert or replace a snapshot for an atproto-valid repo authority.
255    pub async fn put(&self, snap: RepoSnapshot) -> anyhow::Result<()> {
256        accept_repo_authority(&snap.did)?;
257        self.by_did
258            .write()
259            .await
260            .insert(snap.did.clone(), Arc::new(snap));
261        Ok(())
262    }
263
264    /// Look up a snapshot by DID (any visibility — for internal/admin use).
265    pub async fn get(&self, did: &str) -> Option<Arc<RepoSnapshot>> {
266        self.by_did.read().await.get(did).cloned()
267    }
268
269    /// Look up a **public** snapshot by DID. Non-public repos are invisible
270    /// to the public read endpoints (publication boundary).
271    pub async fn get_public(&self, did: &str) -> Option<Arc<RepoSnapshot>> {
272        self.get(did).await.filter(|s| s.public)
273    }
274
275    /// Resolve a handle (bare hostname) to a **public** snapshot.
276    pub async fn by_handle_public(&self, handle: &str) -> Option<Arc<RepoSnapshot>> {
277        let guard = self.by_did.read().await;
278        let mut hits = guard.values().filter(|s| s.public && s.handle == handle);
279        let first = hits.next()?;
280        if hits.next().is_some() {
281            return None; // ambiguous — refuse
282        }
283        Some(Arc::clone(first))
284    }
285
286    /// Bound durable snapshot/encoding work independently of response bodies.
287    /// Move ownership into the blocking task so cancellation cannot release
288    /// admission while that work is still running.
289    async fn acquire_snapshot_work_owned(
290        &self,
291    ) -> Result<OwnedSemaphorePermit, tokio::sync::AcquireError> {
292        self.snapshot_work_sema.clone().acquire_owned().await
293    }
294
295    /// Acquire an **owned** concurrency permit for full-CAR export. The permit
296    /// lives until the body stream is consumed or dropped — not just until the
297    /// handler returns. Bounded by [`GET_REPO_CONCURRENCY`].
298    pub async fn acquire_get_repo_owned(
299        &self,
300    ) -> Result<OwnedSemaphorePermit, tokio::sync::AcquireError> {
301        self.get_repo_sema.clone().acquire_owned().await
302    }
303}
304
305// ─────────────────────────────────────────────────────────────────────────────
306// Lazy CAR section stream (owned-permit held until EOF/drop)
307// ─────────────────────────────────────────────────────────────────────────────
308
309/// Phase of the lazy CAR section stream.
310#[derive(Clone, Debug)]
311enum CarPhase {
312    Header,
313    Commit,
314    Nodes(usize),
315    Records(Arc<Vec<Tid>>, usize),
316    Done,
317}
318
319/// Produce a lazy CAR section stream. Each section is encoded on-demand when
320/// polled — no full-repo materialization. The `OwnedSemaphorePermit` is held
321/// inside the stream's state and released when the stream is dropped (body
322/// consumed or client disconnected).
323fn lazy_car_stream(
324    snap: Arc<RepoSnapshot>,
325    permit: OwnedSemaphorePermit,
326) -> impl Stream<Item = std::io::Result<Bytes>> {
327    let record_tids: Arc<Vec<Tid>> = Arc::new(snap.records.keys().copied().collect());
328
329    struct StreamState {
330        phase: CarPhase,
331        _permit: OwnedSemaphorePermit,
332    }
333
334    let init = StreamState {
335        phase: CarPhase::Header,
336        _permit: permit,
337    };
338
339    stream::unfold(init, move |mut state| {
340        let snap = Arc::clone(&snap);
341        let record_tids = Arc::clone(&record_tids);
342        async move {
343            loop {
344                match &mut state.phase {
345                    CarPhase::Header => {
346                        state.phase = CarPhase::Commit;
347                        return Some((
348                            Ok(Bytes::from(car_header_bytes(&[snap.commit.cid()]))),
349                            state,
350                        ));
351                    }
352                    CarPhase::Commit => {
353                        state.phase = CarPhase::Nodes(0);
354                        return Some((
355                            Ok(Bytes::from(car_block_bytes(
356                                snap.commit.cid(),
357                                &snap.commit.to_dag_cbor(),
358                            ))),
359                            state,
360                        ));
361                    }
362                    CarPhase::Nodes(idx) => {
363                        if *idx < snap.node_blocks.len() {
364                            let (cid, data) = &snap.node_blocks[*idx];
365                            *idx += 1;
366                            return Some((
367                                Ok(Bytes::from(car_block_bytes(*cid, &data.encode()))),
368                                state,
369                            ));
370                        }
371                        state.phase = CarPhase::Records(Arc::clone(&record_tids), 0);
372                        // continue loop → Records
373                    }
374                    CarPhase::Records(tids, ridx) => {
375                        if *ridx < tids.len() {
376                            let tid = tids[*ridx];
377                            *ridx += 1;
378                            let rec = &snap.records[&tid];
379                            return Some((
380                                Ok(Bytes::from(car_block_bytes(rec.cid(), &rec.to_dag_cbor()))),
381                                state,
382                            ));
383                        }
384                        state.phase = CarPhase::Done;
385                        // continue loop → Done
386                    }
387                    CarPhase::Done => return None,
388                }
389            }
390        }
391    })
392}
393
394// ─────────────────────────────────────────────────────────────────────────────
395// XRPC error helpers
396// ─────────────────────────────────────────────────────────────────────────────
397
398pub fn xrpc_error_body(error: &str, message: impl Into<String>) -> Value {
399    json!({ "error": error, "message": message.into() })
400}
401
402pub fn xrpc_error(status: StatusCode, error: &str, message: impl Into<String>) -> Response {
403    (status, axum::Json(xrpc_error_body(error, message))).into_response()
404}
405
406pub mod errors {
407    pub const INVALID_REQUEST: &str = "InvalidRequest";
408    pub const BAD_EXPIRATION: &str = "BadExpiration";
409    pub const ACCOUNT_NOT_FOUND: &str = "AccountNotFound";
410    pub const HANDLE_NOT_FOUND: &str = "HandleNotFound";
411    pub const RECORD_NOT_FOUND: &str = "RecordNotFound";
412    pub const REPO_NOT_FOUND: &str = "RepoNotFound";
413    pub const INTERNAL_SERVER_ERROR: &str = "InternalServerError";
414}
415
416// ─────────────────────────────────────────────────────────────────────────────
417// Protected hosted-account service auth
418// ─────────────────────────────────────────────────────────────────────────────
419
420#[derive(Debug, PartialEq, Eq)]
421struct GetServiceAuthParams {
422    aud: String,
423    exp: Option<i64>,
424    lxm: String,
425}
426
427fn parse_get_service_auth_query(raw: Option<&str>) -> Result<GetServiceAuthParams, &'static str> {
428    let mut aud = None;
429    let mut exp = None;
430    let mut lxm = None;
431    for (key, value) in url::form_urlencoded::parse(raw.unwrap_or_default().as_bytes()) {
432        if key.len() > MAX_SERVICE_AUTH_PARAMETER_BYTES
433            || value.len() > MAX_SERVICE_AUTH_PARAMETER_BYTES
434        {
435            return Err("service-auth query parameter is too long");
436        }
437        match key.as_ref() {
438            "aud" if aud.is_none() && !value.is_empty() => aud = Some(value.into_owned()),
439            "exp" if exp.is_none() && !value.is_empty() => {
440                exp = Some(
441                    value
442                        .parse()
443                        .map_err(|_| "exp must be an integer Unix timestamp")?,
444                );
445            }
446            "lxm" if lxm.is_none() && !value.is_empty() => lxm = Some(value.into_owned()),
447            "aud" | "exp" | "lxm" => {
448                return Err("service-auth query parameters must be non-empty and unique");
449            }
450            _ => return Err("unknown service-auth query parameter"),
451        }
452    }
453    Ok(GetServiceAuthParams {
454        aud: aud.ok_or("aud is required")?,
455        exp,
456        // The upstream lexicon permits an unbound token, but this hosted-PDS
457        // surface only mints the one method-bound assertion consumed by #1354.
458        lxm: lxm.ok_or("lxm is required")?,
459    })
460}
461
462fn service_auth_response(status: StatusCode, body: Value) -> Response {
463    (
464        status,
465        [
466            (header::CACHE_CONTROL, "no-store"),
467            (header::PRAGMA, "no-cache"),
468        ],
469        axum::Json(body),
470    )
471        .into_response()
472}
473
474fn service_auth_error(status: StatusCode, error: &str, message: impl Into<String>) -> Response {
475    service_auth_response(status, xrpc_error_body(error, message))
476}
477
478/// Mint a short-lived, method-bound ATProto service JWT using the hosted
479/// account's persisted `#atproto` key.
480///
481/// Authentication and DPoP proof verification happen in the protected-router
482/// middleware. This handler independently re-verifies the signed OAuth grant
483/// before deriving scope, subject, or tenant authority from it.
484pub async fn get_service_auth(
485    State(state): State<Arc<OAuthState>>,
486    Extension(user): Extension<AuthenticatedUser>,
487    RawQuery(raw): RawQuery,
488) -> Response {
489    let params = match parse_get_service_auth_query(raw.as_deref()) {
490        Ok(params) => params,
491        Err(message) => {
492            return service_auth_error(StatusCode::BAD_REQUEST, errors::INVALID_REQUEST, message);
493        }
494    };
495    let expected_aud = match state.atproto_service_did() {
496        Some(did) => did,
497        None => {
498            return service_auth_error(
499                StatusCode::SERVICE_UNAVAILABLE,
500                errors::INTERNAL_SERVER_ERROR,
501                "host service DID is unavailable",
502            );
503        }
504    };
505    if params.aud != expected_aud {
506        return service_auth_error(
507            StatusCode::BAD_REQUEST,
508            errors::INVALID_REQUEST,
509            "aud must equal this PDS host DID",
510        );
511    }
512    if params.lxm != ATPROTO_SESSION_EXCHANGE_NSID {
513        return service_auth_error(
514            StatusCode::BAD_REQUEST,
515            errors::INVALID_REQUEST,
516            format!("lxm must equal {ATPROTO_SESSION_EXCHANGE_NSID}"),
517        );
518    }
519
520    let now = chrono::Utc::now().timestamp();
521    let exp = match params
522        .exp
523        .unwrap_or_else(|| now.saturating_add(DEFAULT_SERVICE_AUTH_TTL_SECONDS))
524        .checked_sub(now)
525    {
526        Some(ttl) if ttl > 0 && ttl <= MAX_ATPROTO_SERVICE_TOKEN_LIFETIME => now + ttl,
527        _ => {
528            return service_auth_error(
529                StatusCode::BAD_REQUEST,
530                errors::BAD_EXPIRATION,
531                "exp must be in the future and no more than one hour from now",
532            );
533        }
534    };
535
536    let token = match user.token.as_deref() {
537        Some(token) => token,
538        None => {
539            return service_auth_error(
540                StatusCode::UNAUTHORIZED,
541                errors::INVALID_REQUEST,
542                "verified OAuth access token is required",
543            );
544        }
545    };
546    let claims = match auth::validate_oauth_access_token(&state, token).await {
547        Ok(claims) => claims,
548        Err(_) => {
549            return service_auth_error(
550                StatusCode::UNAUTHORIZED,
551                errors::INVALID_REQUEST,
552                "OAuth access token is invalid or expired",
553            );
554        }
555    };
556    if claims.sub != user.user || claims.tenant != user.verified_tenant {
557        tracing::error!("service-auth middleware and handler identity claims disagree");
558        return service_auth_error(
559            StatusCode::UNAUTHORIZED,
560            errors::INVALID_REQUEST,
561            "OAuth identity binding is invalid",
562        );
563    }
564    if !claims.has_scope("atproto") {
565        return service_auth_error(
566            StatusCode::FORBIDDEN,
567            "InsufficientScope",
568            "the atproto scope is required",
569        );
570    }
571    if claims.cnf_jkt().is_none() {
572        return service_auth_error(
573            StatusCode::UNAUTHORIZED,
574            errors::INVALID_REQUEST,
575            "a DPoP-bound OAuth access token is required",
576        );
577    }
578    if super::token::hosted_account_tenant_from_did(&claims.sub, state.hosted_account_zone.as_ref())
579        .is_err()
580    {
581        return service_auth_error(
582            StatusCode::BAD_REQUEST,
583            errors::ACCOUNT_NOT_FOUND,
584            "OAuth subject is not a hosted account on this PDS",
585        );
586    }
587    let record_tenant = match state.hosted_account_tenant(&claims.sub).await {
588        Ok(Some(tenant)) => tenant,
589        Ok(None) => {
590            return service_auth_error(
591                StatusCode::BAD_REQUEST,
592                errors::ACCOUNT_NOT_FOUND,
593                "OAuth subject has no hosted account record",
594            );
595        }
596        Err(error) => {
597            tracing::error!(
598                subject = %claims.sub,
599                error = %error,
600                "hosted account tenant verification failed"
601            );
602            return service_auth_error(
603                StatusCode::INTERNAL_SERVER_ERROR,
604                errors::INTERNAL_SERVER_ERROR,
605                "hosted account verification failed",
606            );
607        }
608    };
609    if claims.tenant.as_deref() != Some(record_tenant.as_str()) {
610        tracing::error!(
611            subject = %claims.sub,
612            "OAuth tenant does not match the authority-owned hosted account record"
613        );
614        return service_auth_error(
615            StatusCode::UNAUTHORIZED,
616            errors::INVALID_REQUEST,
617            "OAuth hosted-account tenant binding is invalid",
618        );
619    }
620
621    let mut jti_bytes = [0_u8; 16];
622    rand::rngs::OsRng.fill_bytes(&mut jti_bytes);
623    let header_segment = match serde_json::to_vec(&json!({
624        "alg": "ES256",
625        "typ": "JWT",
626        "kid": "#atproto",
627    })) {
628        Ok(bytes) => URL_SAFE_NO_PAD.encode(bytes),
629        Err(_) => {
630            return service_auth_error(
631                StatusCode::INTERNAL_SERVER_ERROR,
632                errors::INTERNAL_SERVER_ERROR,
633                "failed to encode service JWT",
634            );
635        }
636    };
637    let claims_segment = match serde_json::to_vec(&json!({
638        "iss": claims.sub,
639        "aud": expected_aud,
640        "iat": now,
641        "exp": exp,
642        "lxm": ATPROTO_SESSION_EXCHANGE_NSID,
643        "jti": URL_SAFE_NO_PAD.encode(jti_bytes),
644    })) {
645        Ok(bytes) => URL_SAFE_NO_PAD.encode(bytes),
646        Err(_) => {
647            return service_auth_error(
648                StatusCode::INTERNAL_SERVER_ERROR,
649                errors::INTERNAL_SERVER_ERROR,
650                "failed to encode service JWT",
651            );
652        }
653    };
654    let signing_input = format!("{header_segment}.{claims_segment}");
655    let Some(store) = state.hosted_account_store.as_ref() else {
656        return service_auth_error(
657            StatusCode::SERVICE_UNAVAILABLE,
658            errors::INTERNAL_SERVER_ERROR,
659            "hosted account signer is unavailable",
660        );
661    };
662    let authority =
663        hyprstream_rpc::Subject::new(hyprstream_pds_service::OAUTH_ACCOUNT_RESOLVER_SUBJECT);
664    let signature = match store
665        .sign_for_hosted_did(&authority, &user.user, signing_input.as_bytes())
666        .await
667    {
668        Ok(Some(signature)) => signature,
669        Ok(None) => {
670            return service_auth_error(
671                StatusCode::BAD_REQUEST,
672                errors::ACCOUNT_NOT_FOUND,
673                "OAuth subject has no hosted account signing record",
674            );
675        }
676        Err(error) => {
677            tracing::error!(
678                subject = %user.user,
679                error = %error,
680                "hosted account service JWT signing failed"
681            );
682            return service_auth_error(
683                StatusCode::INTERNAL_SERVER_ERROR,
684                errors::INTERNAL_SERVER_ERROR,
685                "hosted account signing failed",
686            );
687        }
688    };
689
690    service_auth_response(
691        StatusCode::OK,
692        json!({
693            "token": format!("{signing_input}.{}", URL_SAFE_NO_PAD.encode(signature)),
694        }),
695    )
696}
697
698// ─────────────────────────────────────────────────────────────────────────────
699// Query parsing (manual — no axum Query rejection bypasses XRPC envelope)
700// ─────────────────────────────────────────────────────────────────────────────
701
702/// Parse a raw query string `key=value&key=value` into a map.
703///
704/// - **Bare keys** (no `=`) are inserted with an empty value — so `?since`
705///   is treated as present, matching form/urlencoded semantics.
706/// - **Percent-decoding**: `%XX` sequences are decoded and `+` becomes a
707///   space (form semantics), so encoded DIDs/handles/rkeys resolve.
708fn parse_query(raw: Option<&str>) -> std::collections::HashMap<String, String> {
709    let mut map = std::collections::HashMap::new();
710    if let Some(q) = raw {
711        for pair in q.split('&') {
712            let (key, val) = match pair.split_once('=') {
713                Some((k, v)) => (k, v),
714                None => (pair, ""), // bare key → present with empty value
715            };
716            map.insert(percent_decode(key), percent_decode(val));
717        }
718    }
719    map
720}
721
722/// Minimal percent-decoder: `%XX` → byte, `+` → space.
723fn percent_decode(s: &str) -> String {
724    let bytes = s.as_bytes();
725    let mut out = Vec::with_capacity(bytes.len());
726    let mut i = 0;
727    while i < bytes.len() {
728        match bytes[i] {
729            b'+' => out.push(b' '),
730            b'%' if i + 2 < bytes.len() => {
731                if let (Some(hi), Some(lo)) = (hex_val(bytes[i + 1]), hex_val(bytes[i + 2])) {
732                    out.push(hi * 16 + lo);
733                    i += 2;
734                } else {
735                    out.push(b'%');
736                }
737            }
738            b => out.push(b),
739        }
740        i += 1;
741    }
742    String::from_utf8_lossy(&out).into_owned()
743}
744
745fn hex_val(b: u8) -> Option<u8> {
746    match b {
747        b'0'..=b'9' => Some(b - b'0'),
748        b'a'..=b'f' => Some(b - b'a' + 10),
749        b'A'..=b'F' => Some(b - b'A' + 10),
750        _ => None,
751    }
752}
753
754// ─────────────────────────────────────────────────────────────────────────────
755// Core handler logic (testable without OAuthState)
756// ─────────────────────────────────────────────────────────────────────────────
757
758/// Trusted public registry/issuer resolution, shared by reads and owned writes.
759async fn resolve_handle_did(
760    store: &XrpcRepoStore,
761    issuer_url: &str,
762    handle: &str,
763) -> Option<String> {
764    let handle = handle.to_ascii_lowercase();
765    if !record_validation::valid_handle(&handle) {
766        return None;
767    }
768    if let Some(snap) = store.by_handle_public(&handle).await {
769        return Some(snap.did.clone());
770    }
771    if let Ok(origin) = url::Url::parse(issuer_url) {
772        if origin.host_str() == Some(handle.as_str()) {
773            return super::state::atproto_service_did_for_origin(issuer_url);
774        }
775    }
776    None
777}
778
779// The configured zone is authoritative for hosted handles. Do not synthesize
780// identities from arbitrary DNS names or from the independent snapshot cache.
781fn hosted_repo_did(state: &OAuthState, repo: &str) -> Option<String> {
782    state.hosted_public_repo_writer.as_ref()?;
783    let zone = state.hosted_account_zone.as_ref()?;
784    let did = if repo.starts_with("did:") {
785        repo.to_owned()
786    } else {
787        format!("did:web:{repo}")
788    };
789    super::atproto_session::hosted_label_for_did(zone, &did)
790        .ok()
791        .flatten()?;
792    Some(did)
793}
794
795async fn owned_public_writer(
796    state: &OAuthState,
797    repo: &str,
798) -> Option<crate::services::public_repo::PublicRepoReader> {
799    use crate::services::public_repo::PublicRepoReader;
800    // An existing alias is only a locator. Resolve its target before choosing
801    // storage so an alias to an owned DID cannot revive a legacy snapshot.
802    let did = if let Some(did) = hosted_repo_did(state, repo) {
803        did
804    } else if repo.starts_with("did:") {
805        repo.to_owned()
806    } else {
807        resolve_handle_did(&state.xrpc_repos, &state.issuer_url, repo).await?
808    };
809    if let (Some(did), Some(writer)) = (
810        hosted_repo_did(state, &did),
811        &state.hosted_public_repo_writer,
812    ) {
813        return Some(PublicRepoReader::Hosted {
814            writer: Arc::clone(writer),
815            did,
816        });
817    }
818    let writer = state.public_repo_writer.as_ref()?;
819    (did == writer.did()).then(|| PublicRepoReader::Local(Arc::clone(writer)))
820}
821
822async fn resolve_handle_core(store: &XrpcRepoStore, issuer_url: &str, handle: &str) -> Response {
823    if let Some(did) = resolve_handle_did(store, issuer_url, handle).await {
824        return axum::Json(json!({ "did": did })).into_response();
825    }
826    xrpc_error(
827        StatusCode::BAD_REQUEST,
828        errors::HANDLE_NOT_FOUND,
829        format!("handle {handle:?} not found"),
830    )
831}
832
833async fn describe_repo_core(store: &XrpcRepoStore, issuer_url: &str, repo: &str) -> Response {
834    let snap = match lookup_public_snapshot(store, repo).await {
835        Some(s) => s,
836        None => {
837            return xrpc_error(
838                StatusCode::BAD_REQUEST,
839                errors::REPO_NOT_FOUND,
840                format!("repo {repo:?} is not hosted by this PDS"),
841            );
842        }
843    };
844    let collections: Vec<&str> = if snap.records.is_empty() {
845        Vec::new()
846    } else {
847        vec![HOSTED_COLLECTION]
848    };
849    let did_doc = snap.did_doc(issuer_url);
850    axum::Json(json!({
851        "handle": snap.handle,
852        "did": snap.did,
853        "didDoc": did_doc,
854        "collections": collections,
855        "handleIsCorrect": true,
856    }))
857    .into_response()
858}
859
860async fn get_record_core(
861    store: &XrpcRepoStore,
862    repo: &str,
863    collection: &str,
864    rkey: &str,
865    cid: Option<&str>,
866) -> Response {
867    if collection != HOSTED_COLLECTION {
868        return xrpc_error(
869            StatusCode::BAD_REQUEST,
870            errors::RECORD_NOT_FOUND,
871            format!("collection {collection:?} is not hosted"),
872        );
873    }
874    if rkey.is_empty() {
875        return xrpc_error(
876            StatusCode::BAD_REQUEST,
877            errors::INVALID_REQUEST,
878            "rkey is required",
879        );
880    }
881    let snap = match lookup_public_snapshot(store, repo).await {
882        Some(s) => s,
883        None => {
884            return xrpc_error(
885                StatusCode::BAD_REQUEST,
886                errors::REPO_NOT_FOUND,
887                format!("repo {repo:?} is not hosted by this PDS"),
888            );
889        }
890    };
891    let Some((rec, record_cid)) = snap.record_by_rkey(rkey) else {
892        return xrpc_error(
893            StatusCode::BAD_REQUEST,
894            errors::RECORD_NOT_FOUND,
895            format!("record {collection}/{rkey} not found"),
896        );
897    };
898    if let Some(requested_cid) = cid {
899        if requested_cid != record_cid.to_string() {
900            return xrpc_error(
901                StatusCode::BAD_REQUEST,
902                errors::RECORD_NOT_FOUND,
903                format!("record {collection}/{rkey} does not match cid {requested_cid:?}"),
904            );
905        }
906    }
907    axum::Json(snap.record_json(rkey, rec)).into_response()
908}
909
910async fn get_repo_core(store: &XrpcRepoStore, did: &str, since_present: bool) -> Response {
911    if since_present {
912        return xrpc_error(
913            StatusCode::BAD_REQUEST,
914            errors::INVALID_REQUEST,
915            "since (revision delta) is not yet supported; omit for full export",
916        );
917    }
918    let snap = match store.get_public(did).await {
919        Some(s) => s,
920        None => {
921            return xrpc_error(
922                StatusCode::BAD_REQUEST,
923                errors::REPO_NOT_FOUND,
924                format!("repo {did:?} is not hosted by this PDS"),
925            );
926        }
927    };
928    // Acquire owned permit — held inside the body stream until EOF/drop.
929    let permit = match store.acquire_get_repo_owned().await {
930        Ok(p) => p,
931        Err(_) => {
932            return xrpc_error(
933                StatusCode::INTERNAL_SERVER_ERROR,
934                errors::INTERNAL_SERVER_ERROR,
935                "concurrency limiter closed",
936            );
937        }
938    };
939    let body_stream = lazy_car_stream(snap, permit);
940    let body = axum::body::Body::from_stream(body_stream);
941    (
942        StatusCode::OK,
943        [(header::CONTENT_TYPE, "application/vnd.ipld.car")],
944        body,
945    )
946        .into_response()
947}
948
949async fn lookup_public_snapshot(store: &XrpcRepoStore, key: &str) -> Option<Arc<RepoSnapshot>> {
950    if key.starts_with("did:") {
951        store.get_public(key).await
952    } else {
953        store.by_handle_public(key).await
954    }
955}
956
957// ─────────────────────────────────────────────────────────────────────────────
958// Axum handler wrappers
959// ─────────────────────────────────────────────────────────────────────────────
960
961/// Return the standard server capability and account-domain description.
962///
963/// The service DID is derived from the configured issuer origin. Account
964/// domains are advertised only when an authority-owned [`AccountZone`] is
965/// installed; an unconfigured zone yields an empty list rather than a guessed
966/// or operator-wide wildcard. Account creation remains unavailable until its
967/// provisioning contract is installed, so invite-code requirement is kept
968/// fail-closed.
969pub async fn describe_server(State(state): State<Arc<OAuthState>>) -> Response {
970    let Some(did) = state.atproto_service_did() else {
971        return xrpc_error(
972            StatusCode::SERVICE_UNAVAILABLE,
973            errors::INTERNAL_SERVER_ERROR,
974            "server DID is unavailable",
975        );
976    };
977    let available_user_domains = state
978        .hosted_account_zone
979        .as_ref()
980        .map(|zone| format!(".{}", zone.apex()))
981        .into_iter()
982        .collect::<Vec<_>>();
983    (
984        StatusCode::OK,
985        axum::Json(json!({
986            "did": did,
987            "availableUserDomains": available_user_domains,
988            "inviteCodeRequired": true,
989            "phoneVerificationRequired": false,
990        })),
991    )
992        .into_response()
993}
994
995/// Return the current authenticated ATProto session from the native account
996/// authority. The bearer/DPoP middleware authenticates the request; this
997/// handler revalidates the token and scope before consulting the resolver.
998pub async fn get_session(
999    State(state): State<Arc<OAuthState>>,
1000    Extension(user): Extension<AuthenticatedUser>,
1001) -> Response {
1002    let Some(token) = user.token.as_deref() else {
1003        return xrpc_error(
1004            StatusCode::UNAUTHORIZED,
1005            errors::INVALID_REQUEST,
1006            "verified OAuth access token is required",
1007        );
1008    };
1009    let claims = match auth::validate_oauth_access_token(&state, token).await {
1010        Ok(claims) => claims,
1011        Err(_) => {
1012            return xrpc_error(
1013                StatusCode::UNAUTHORIZED,
1014                errors::INVALID_REQUEST,
1015                "OAuth access token is invalid or expired",
1016            );
1017        }
1018    };
1019    if !claims.has_scope("atproto") {
1020        return xrpc_error(
1021            StatusCode::FORBIDDEN,
1022            "InsufficientScope",
1023            "the atproto scope is required",
1024        );
1025    }
1026    if claims.sub != user.user || claims.tenant != user.verified_tenant {
1027        return xrpc_error(
1028            StatusCode::UNAUTHORIZED,
1029            errors::INVALID_REQUEST,
1030            "OAuth identity binding is invalid",
1031        );
1032    }
1033    let Some(resolver) = state.atproto_session_resolver.as_ref() else {
1034        return xrpc_error(
1035            StatusCode::SERVICE_UNAVAILABLE,
1036            errors::INTERNAL_SERVER_ERROR,
1037            "native ATProto session resolver is not configured",
1038        );
1039    };
1040    let info = match resolver.resolve_session(&claims.sub).await {
1041        Ok(Some(info)) => info,
1042        Ok(None) => {
1043            return xrpc_error(
1044                StatusCode::BAD_REQUEST,
1045                errors::ACCOUNT_NOT_FOUND,
1046                "account is not hosted by this PDS",
1047            );
1048        }
1049        Err(error) => {
1050            tracing::error!(%error, did = %claims.sub, "ATProto session resolver failed");
1051            return xrpc_error(
1052                StatusCode::SERVICE_UNAVAILABLE,
1053                errors::INTERNAL_SERVER_ERROR,
1054                "native account state is unavailable",
1055            );
1056        }
1057    };
1058    // Reuse the canonical Lexicon handle grammar. Reserved-domain admission
1059    // belongs to the native authority; handle.invalid is a valid API sentinel.
1060    let handle = info.handle.to_ascii_lowercase();
1061    if !record_validation::valid_handle(&handle) {
1062        tracing::error!(did = %claims.sub, "ATProto session resolver returned invalid handle");
1063        return xrpc_error(
1064            StatusCode::INTERNAL_SERVER_ERROR,
1065            errors::INTERNAL_SERVER_ERROR,
1066            "native account returned an invalid handle",
1067        );
1068    }
1069    // The getSession lexicon's status knownValues are an open string set.
1070    // Preserve the trusted native authority's lifecycle reason verbatim.
1071    let mut body = json!({
1072        "handle": handle,
1073        "did": claims.sub,
1074        "active": info.active,
1075    });
1076    let Some(object) = body.as_object_mut() else {
1077        return xrpc_error(
1078            StatusCode::INTERNAL_SERVER_ERROR,
1079            errors::INTERNAL_SERVER_ERROR,
1080            "session response construction failed",
1081        );
1082    };
1083    if let Some(value) = info.did_doc {
1084        object.insert("didDoc".to_owned(), value);
1085    }
1086    if let Some(value) = info.email {
1087        object.insert("email".to_owned(), Value::String(value));
1088    }
1089    if let Some(value) = info.email_confirmed {
1090        object.insert("emailConfirmed".to_owned(), Value::Bool(value));
1091    }
1092    if let Some(value) = info.email_auth_factor {
1093        object.insert("emailAuthFactor".to_owned(), Value::Bool(value));
1094    }
1095    if let Some(value) = info.status {
1096        object.insert("status".to_owned(), Value::String(value));
1097    }
1098    (StatusCode::OK, axum::Json(body)).into_response()
1099}
1100
1101pub async fn resolve_handle(
1102    State(state): State<Arc<OAuthState>>,
1103    RawQuery(raw): RawQuery,
1104) -> Response {
1105    let params = parse_query(raw.as_deref());
1106    let handle = match params.get("handle") {
1107        Some(h) if !h.is_empty() => h.trim(),
1108        _ => {
1109            return xrpc_error(
1110                StatusCode::BAD_REQUEST,
1111                errors::INVALID_REQUEST,
1112                "handle query parameter is required",
1113            );
1114        }
1115    };
1116    if let (Some(did), Some(writer)) = (
1117        hosted_repo_did(&state, handle),
1118        &state.hosted_public_repo_writer,
1119    ) {
1120        let Ok(_permit) = state.xrpc_repos.acquire_snapshot_work_owned().await else {
1121            return xrpc_error(
1122                StatusCode::SERVICE_UNAVAILABLE,
1123                errors::INTERNAL_SERVER_ERROR,
1124                "public identity lookup unavailable",
1125            );
1126        };
1127        return match writer.has_account(&did).await {
1128            Ok(true) => axum::Json(json!({"did":did})).into_response(),
1129            Ok(false) => xrpc_error(
1130                StatusCode::BAD_REQUEST,
1131                errors::HANDLE_NOT_FOUND,
1132                "hosted handle not found",
1133            ),
1134            Err(_) => xrpc_error(
1135                StatusCode::SERVICE_UNAVAILABLE,
1136                errors::INTERNAL_SERVER_ERROR,
1137                "public identity lookup unavailable",
1138            ),
1139        };
1140    }
1141    resolve_handle_core(&state.xrpc_repos, &state.issuer_url, handle).await
1142}
1143
1144pub async fn describe_repo(
1145    State(state): State<Arc<OAuthState>>,
1146    RawQuery(raw): RawQuery,
1147) -> Response {
1148    let params = parse_query(raw.as_deref());
1149    let key = match params.get("repo") {
1150        Some(r) if !r.is_empty() => r.trim(),
1151        _ => {
1152            return xrpc_error(
1153                StatusCode::BAD_REQUEST,
1154                errors::INVALID_REQUEST,
1155                "repo query parameter is required",
1156            );
1157        }
1158    };
1159    if let Some(writer) = owned_public_writer(&state, key).await {
1160        return durable_reads::describe_repo(&state, writer).await;
1161    }
1162    describe_repo_core(&state.xrpc_repos, &state.issuer_url, key).await
1163}
1164
1165pub async fn get_record(State(state): State<Arc<OAuthState>>, RawQuery(raw): RawQuery) -> Response {
1166    let params = parse_query(raw.as_deref());
1167    let collection = params
1168        .get("collection")
1169        .map(std::string::String::as_str)
1170        .unwrap_or("");
1171    let rkey = params
1172        .get("rkey")
1173        .map(std::string::String::as_str)
1174        .unwrap_or("");
1175    let repo = match params.get("repo") {
1176        Some(r) if !r.is_empty() => r.trim(),
1177        _ => {
1178            return xrpc_error(
1179                StatusCode::BAD_REQUEST,
1180                errors::INVALID_REQUEST,
1181                "repo query parameter is required",
1182            );
1183        }
1184    };
1185    let cid = params.get("cid").map(|c| c.trim());
1186    if let Some(canary) = &state.public_git_canary_record {
1187        if repo == canary.did {
1188            return match canary_request(canary, raw.as_deref(), &params) {
1189                Some(cid) => get_public_canary_record(&state, canary, cid).await,
1190                None => canary_not_found(),
1191            };
1192        }
1193    }
1194    if let Some(writer) = owned_public_writer(&state, repo).await {
1195        return durable_reads::get_record(&state.xrpc_repos, writer, collection, rkey, cid).await;
1196    }
1197    get_record_core(&state.xrpc_repos, repo, collection, rkey, cid).await
1198}
1199
1200fn canary_not_found() -> Response {
1201    xrpc_error(
1202        StatusCode::BAD_REQUEST,
1203        errors::RECORD_NOT_FOUND,
1204        "public record not found",
1205    )
1206}
1207
1208fn internal_error() -> Response {
1209    xrpc_error(
1210        StatusCode::INTERNAL_SERVER_ERROR,
1211        errors::INTERNAL_SERVER_ERROR,
1212        "public record unavailable",
1213    )
1214}
1215
1216fn canary_request<'a>(
1217    canary: &super::state::PublicGitCanaryRecord,
1218    raw: Option<&str>,
1219    params: &'a std::collections::HashMap<String, String>,
1220) -> Option<Option<&'a str>> {
1221    let raw = raw?;
1222    if raw.len() > 2_048 || raw.split('&').count() != params.len() {
1223        return None;
1224    }
1225    if params.get("repo").map(String::as_str) != Some(canary.did.as_str())
1226        || params.get("collection").map(String::as_str) != Some(COLLECTION_NSID)
1227        || params.get("rkey").map(String::as_str) != Some(canary.rkey.as_str())
1228        || params
1229            .keys()
1230            .any(|key| !matches!(key.as_str(), "repo" | "collection" | "rkey" | "cid"))
1231    {
1232        return None;
1233    }
1234    let cid = params.get("cid").map(String::as_str);
1235    if cid.is_some_and(|value| value.len() > 100) {
1236        return None;
1237    }
1238    Some(cid)
1239}
1240
1241pub async fn public_canary_get_record(
1242    State(state): State<Arc<OAuthState>>,
1243    RawQuery(raw): RawQuery,
1244) -> Response {
1245    let Some(canary) = &state.public_git_canary_record else {
1246        return canary_not_found();
1247    };
1248    let params = parse_query(raw.as_deref());
1249    match canary_request(canary, raw.as_deref(), &params) {
1250        Some(cid) => get_public_canary_record(&state, canary, cid).await,
1251        None => canary_not_found(),
1252    }
1253}
1254
1255/// Only the exact configured tuple reaches Discovery. Discovery applies its
1256/// existing service identity and per-target policy before returning a CAR.
1257async fn get_public_canary_record(
1258    state: &OAuthState,
1259    canary: &super::state::PublicGitCanaryRecord,
1260    requested_cid: Option<&str>,
1261) -> Response {
1262    const MAX_CAR_BYTES: usize = 2 * 1024 * 1024;
1263    let uri = format!("at://{}/{COLLECTION_NSID}/{}", canary.did, canary.rkey);
1264    let result = tokio::time::timeout(
1265        std::time::Duration::from_secs(10),
1266        state.discovery_client.get_record(
1267            &hyprstream_rpc_std::discovery_client::GetRecordRequest {
1268                uri: uri.clone(),
1269                did: canary.did.clone(),
1270                collection: COLLECTION_NSID.to_owned(),
1271                rkey: canary.rkey.clone(),
1272            },
1273        ),
1274    )
1275    .await;
1276    let Ok(Ok(proof)) = result else {
1277        return internal_error();
1278    };
1279    if proof.uri != uri || proof.car.len() > MAX_CAR_BYTES {
1280        return internal_error();
1281    }
1282    let Some(store) = &state.es256_key_store else {
1283        return internal_error();
1284    };
1285    let slots = store.slots_snapshot();
1286    let Some(active) = slots.active else {
1287        return internal_error();
1288    };
1289    let keys = PublishedAtprotoKeys::from_published_slots(
1290        *active.key.verifying_key(),
1291        slots
1292            .drain
1293            .map(|slot| (*slot.key.verifying_key(), slot.nbf, slot.exp)),
1294        slots
1295            .lead
1296            .map(|slot| (*slot.key.verifying_key(), slot.nbf, slot.exp)),
1297    );
1298    let Ok(keys) = keys else {
1299        return internal_error();
1300    };
1301    let Some((record, record_cid)) =
1302        canary_record_from_car(&proof.car, canary, &keys, chrono::Utc::now().timestamp())
1303    else {
1304        return internal_error();
1305    };
1306    canary_record_response(&uri, record, record_cid, requested_cid)
1307}
1308
1309fn canary_record_response(
1310    uri: &str,
1311    record: ModelRecord,
1312    record_cid: Cid,
1313    requested_cid: Option<&str>,
1314) -> Response {
1315    let record_cid = record_cid.encode();
1316    if requested_cid.is_some_and(|cid| cid != record_cid) {
1317        return canary_not_found();
1318    }
1319    axum::Json(json!({
1320        "uri": uri,
1321        "cid": record_cid,
1322        "value": {
1323            "$type": COLLECTION_NSID,
1324            "repo": record.repo,
1325            "currentOid": record.current_oid,
1326            "createdAt": record.created_at,
1327        },
1328    }))
1329    .into_response()
1330}
1331
1332/// The authenticated Discovery reply is still treated as untrusted bytes.
1333/// Bind its CAR root and sole model record to the configured publisher before
1334/// turning it into public JSON; no arbitrary CAR content is reflected.
1335fn canary_record_from_car(
1336    car: &[u8],
1337    canary: &super::state::PublicGitCanaryRecord,
1338    published_keys: &PublishedAtprotoKeys,
1339    now: i64,
1340) -> Option<(ModelRecord, Cid)> {
1341    let (roots, blocks) = parse_car_v1(car).ok()?;
1342    if roots.len() != 1 || blocks.len() > 64 {
1343        return None;
1344    }
1345    let root = roots.first().copied()?;
1346    let (_, commit_bytes) = blocks.iter().find(|(cid, _)| *cid == root)?;
1347    let commit = Commit::from_dag_cbor(commit_bytes).ok()?;
1348    if commit.did != canary.did
1349        || commit.cid() != root
1350        || commit
1351            .verify_against_published_keys(published_keys, now)
1352            .is_err()
1353    {
1354        return None;
1355    }
1356    let mut selected = None;
1357    for (cid, bytes) in &blocks {
1358        if *cid == root {
1359            continue;
1360        }
1361        if let Ok(record) = ModelRecord::from_dag_cbor(bytes) {
1362            if record.repo != format!("at://{}", canary.did)
1363                || record.cid() != *cid
1364                || selected.is_some()
1365            {
1366                return None;
1367            }
1368            selected = Some((record, *cid));
1369        }
1370    }
1371    let (record, record_cid) = selected?;
1372    let target = format!("{COLLECTION_NSID}/{}", canary.rkey);
1373    let mut next = commit.data;
1374    for _ in 0..blocks.len() {
1375        let (_, bytes) = blocks.iter().find(|(cid, _)| *cid == next)?;
1376        if Cid::from_dag_cbor(bytes) != next {
1377            return None;
1378        }
1379        let value = DagCbor::decode(bytes).ok()?;
1380        let node = NodeData::from_value(&value).ok()?;
1381        if node.encode() != *bytes {
1382            return None;
1383        }
1384        let mut prior = String::new();
1385        let mut entries = Vec::with_capacity(node.e.len());
1386        for entry in &node.e {
1387            if entry.p > prior.len() || !prior.is_char_boundary(entry.p) {
1388                return None;
1389            }
1390            let suffix = std::str::from_utf8(&entry.k).ok()?;
1391            let key = format!("{}{suffix}", &prior[..entry.p]);
1392            if !prior.is_empty() && key <= prior {
1393                return None;
1394            }
1395            prior = key.clone();
1396            entries.push(key);
1397        }
1398        if entries.first().is_none_or(|first| target < *first) {
1399            next = node.l?;
1400            continue;
1401        }
1402        let mut descent = None;
1403        for (index, key) in entries.iter().enumerate() {
1404            if key == &target {
1405                return (node.e[index].v == record_cid).then_some((record, record_cid));
1406            }
1407            if key < &target && entries.get(index + 1).is_none_or(|next| &target < next) {
1408                descent = node.e[index].t;
1409                break;
1410            }
1411        }
1412        next = descent?;
1413    }
1414    None
1415}
1416
1417pub async fn get_repo(State(state): State<Arc<OAuthState>>, RawQuery(raw): RawQuery) -> Response {
1418    let params = parse_query(raw.as_deref());
1419    let did = match params.get("did") {
1420        Some(d) if !d.is_empty() => d.trim(),
1421        _ => {
1422            return xrpc_error(
1423                StatusCode::BAD_REQUEST,
1424                errors::INVALID_REQUEST,
1425                "did query parameter is required",
1426            );
1427        }
1428    };
1429    // Reject since by PRESENCE (not just non-empty) — ?since= and ?since=x both 400.
1430    let since_present = params.contains_key("since");
1431    if let Some(writer) = owned_public_writer(&state, did).await {
1432        return durable_reads::get_repo(&state.xrpc_repos, writer, since_present).await;
1433    }
1434    get_repo_core(&state.xrpc_repos, did, since_present).await
1435}
1436
1437/// `com.atproto.repo.createRecord` for the first native-authorized public
1438/// posting slice. The route is deliberately opt-in: OAuthState must carry a
1439/// PublicRepoWriter, and the normal bearer/DPoP middleware must have inserted
1440/// AuthenticatedUser before this handler runs.
1441pub async fn create_record(
1442    State(state): State<Arc<OAuthState>>,
1443    Extension(user): Extension<AuthenticatedUser>,
1444    headers: HeaderMap,
1445    body: Bytes,
1446) -> Response {
1447    const MAX_BODY_BYTES: usize = 1_048_576;
1448    if body.len() > MAX_BODY_BYTES {
1449        return xrpc_error(
1450            StatusCode::PAYLOAD_TOO_LARGE,
1451            errors::INVALID_REQUEST,
1452            "record body exceeds 1 MiB",
1453        );
1454    }
1455    if state.public_repo_writer.is_none() && state.hosted_public_repo_writer.is_none() {
1456        return xrpc_error(
1457            StatusCode::SERVICE_UNAVAILABLE,
1458            errors::INTERNAL_SERVER_ERROR,
1459            "public repository writer is not configured",
1460        );
1461    }
1462    let Some(token) = user.token.as_deref() else {
1463        return xrpc_error(
1464            StatusCode::UNAUTHORIZED,
1465            errors::INVALID_REQUEST,
1466            "verified OAuth access token is required",
1467        );
1468    };
1469    let claims = match auth::validate_oauth_access_token(&state, token).await {
1470        Ok(claims) => claims,
1471        Err(_) => {
1472            return xrpc_error(
1473                StatusCode::UNAUTHORIZED,
1474                errors::INVALID_REQUEST,
1475                "OAuth access token is invalid or expired",
1476            )
1477        }
1478    };
1479    if !claims.has_scope("atproto") {
1480        return xrpc_error(
1481            StatusCode::FORBIDDEN,
1482            "InsufficientScope",
1483            "the atproto scope is required",
1484        );
1485    }
1486    if claims.sub != user.user || claims.tenant != user.verified_tenant {
1487        return xrpc_error(
1488            StatusCode::UNAUTHORIZED,
1489            errors::INVALID_REQUEST,
1490            "OAuth identity binding is invalid",
1491        );
1492    }
1493    // The protected router has verified the matching proof, ath, nonce, and
1494    // replay state for bound tokens. Unbound Bearer tokens remain valid for
1495    // other OAuth routes, but cannot authorize this atproto write endpoint.
1496    if claims.cnf_jkt().is_none() {
1497        return xrpc_error(
1498            StatusCode::UNAUTHORIZED,
1499            errors::INVALID_REQUEST,
1500            "a DPoP-bound OAuth access token is required",
1501        );
1502    }
1503    let input: Value = match serde_json::from_slice(&body) {
1504        Ok(value) => value,
1505        Err(_) => {
1506            return xrpc_error(
1507                StatusCode::BAD_REQUEST,
1508                errors::INVALID_REQUEST,
1509                "request body must be valid JSON",
1510            )
1511        }
1512    };
1513    let object = match input.as_object() {
1514        Some(object) => object,
1515        None => {
1516            return xrpc_error(
1517                StatusCode::BAD_REQUEST,
1518                errors::INVALID_REQUEST,
1519                "request body must be an object",
1520            )
1521        }
1522    };
1523    let expected_prev = match parse_swap_commit(object.get("swapCommit")) {
1524        Ok(value) => value,
1525        Err(message) => {
1526            return xrpc_error(StatusCode::BAD_REQUEST, errors::INVALID_REQUEST, message)
1527        }
1528    };
1529    let validate = match object.get("validate") {
1530        None => true, // Both collections in this posting slice have known schemas.
1531        Some(Value::Bool(value)) => *value,
1532        Some(_) => {
1533            return xrpc_error(
1534                StatusCode::BAD_REQUEST,
1535                errors::INVALID_REQUEST,
1536                "validate must be a boolean when present",
1537            )
1538        }
1539    };
1540    let return_record = match parse_return_record(object.get("returnRecord")) {
1541        Ok(value) => value,
1542        Err(message) => {
1543            return xrpc_error(StatusCode::BAD_REQUEST, errors::INVALID_REQUEST, message)
1544        }
1545    };
1546    let mut idempotency_keys = headers.get_all("Idempotency-Key").iter();
1547    let request_id = match idempotency_keys.next() {
1548        None => None,
1549        Some(value) => {
1550            let value = match value.to_str() {
1551                Ok(value) if !value.is_empty() => value,
1552                _ => {
1553                    return xrpc_error(
1554                        StatusCode::BAD_REQUEST,
1555                        errors::INVALID_REQUEST,
1556                        "Idempotency-Key must be a non-empty ASCII string",
1557                    )
1558                }
1559            };
1560            if idempotency_keys.next().is_some() {
1561                return xrpc_error(
1562                    StatusCode::BAD_REQUEST,
1563                    errors::INVALID_REQUEST,
1564                    "only one Idempotency-Key may be supplied",
1565                );
1566            }
1567            // The native writer validates the publication request ID's length
1568            // and alphabet before authorization or any repository access.
1569            Some(value.to_owned())
1570        }
1571    };
1572    let repo = match object.get("repo").and_then(Value::as_str) {
1573        Some(repo) if !repo.is_empty() => repo,
1574        _ => {
1575            return xrpc_error(
1576                StatusCode::BAD_REQUEST,
1577                errors::INVALID_REQUEST,
1578                "repo is required",
1579            )
1580        }
1581    };
1582    let repo = if let Some(did) = hosted_repo_did(&state, repo) {
1583        Some(did)
1584    } else if repo.starts_with("did:") {
1585        Some(repo.to_owned())
1586    } else {
1587        resolve_handle_did(&state.xrpc_repos, &state.issuer_url, repo).await
1588    };
1589    let hosted_target = repo
1590        .as_deref()
1591        .and_then(|did| hosted_repo_did(&state, did))
1592        .is_some();
1593    if !hosted_target
1594        && !state
1595            .public_repo_writer
1596            .as_ref()
1597            .is_some_and(|writer| repo.as_deref() == Some(writer.did()))
1598    {
1599        return xrpc_error(
1600            StatusCode::FORBIDDEN,
1601            "AuthRequired",
1602            "the request repo is not owned by this writer",
1603        );
1604    }
1605    let collection = match object.get("collection").and_then(Value::as_str) {
1606        Some(collection)
1607            if matches!(collection, "app.bsky.feed.post" | "app.bsky.actor.profile") =>
1608        {
1609            collection
1610        }
1611        Some(_) => {
1612            return xrpc_error(
1613                StatusCode::BAD_REQUEST,
1614                errors::INVALID_REQUEST,
1615                "collection is outside the enabled posting slice",
1616            )
1617        }
1618        None => {
1619            return xrpc_error(
1620                StatusCode::BAD_REQUEST,
1621                errors::INVALID_REQUEST,
1622                "collection is required",
1623            )
1624        }
1625    };
1626    let rkey = match (collection, object.get("rkey")) {
1627        ("app.bsky.actor.profile", None) => AtprotoRecordKey::new("self").map(Some),
1628        ("app.bsky.actor.profile", Some(Value::String(value))) if value == "self" => {
1629            AtprotoRecordKey::new(value.clone()).map(Some)
1630        }
1631        ("app.bsky.actor.profile", _) => Err(anyhow::anyhow!("profile rkey must be self")),
1632        (_, None) => Ok(None),
1633        (_, Some(Value::String(value)))
1634            if Tid::parse(value).is_ok_and(|tid| tid.encode() == *value) =>
1635        {
1636            // Reject alternate encodings instead of changing the record path.
1637            AtprotoRecordKey::new(value.clone()).map(Some)
1638        }
1639        _ => Err(anyhow::anyhow!("a valid TID rkey is required when present")),
1640    };
1641    let rkey = match rkey {
1642        Ok(rkey) => rkey,
1643        Err(error) => {
1644            return xrpc_error(
1645                StatusCode::BAD_REQUEST,
1646                errors::INVALID_REQUEST,
1647                error.to_string(),
1648            )
1649        }
1650    };
1651    let record_value = match object.get("record") {
1652        Some(record) => record,
1653        None => {
1654            return xrpc_error(
1655                StatusCode::BAD_REQUEST,
1656                errors::INVALID_REQUEST,
1657                "record is required",
1658            )
1659        }
1660    };
1661    if validate {
1662        if let Err(error) = record_validation::validate(collection, record_value) {
1663            let (status, code, message) = match error {
1664                record_validation::Error::Invalid => (
1665                    StatusCode::BAD_REQUEST,
1666                    errors::INVALID_REQUEST,
1667                    "record does not match its known schema",
1668                ),
1669                record_validation::Error::SchemaUnavailable => (
1670                    StatusCode::INTERNAL_SERVER_ERROR,
1671                    errors::INTERNAL_SERVER_ERROR,
1672                    "record schema validation is unavailable",
1673                ),
1674            };
1675            return xrpc_error(status, code, message);
1676        }
1677    }
1678    let record = match crate::services::public_repo::json_to_dag_cbor(record_value) {
1679        Ok(record) => record,
1680        Err(_) => {
1681            return xrpc_error(
1682                StatusCode::BAD_REQUEST,
1683                errors::INVALID_REQUEST,
1684                "record contains unsupported data",
1685            )
1686        }
1687    };
1688    if crate::services::public_repo::reject_unverified_blobs(&record).is_err() {
1689        return xrpc_error(
1690            StatusCode::BAD_REQUEST,
1691            errors::INVALID_REQUEST,
1692            "blob storage verification is unavailable",
1693        );
1694    }
1695    let request_id = request_id.unwrap_or_else(|| match rkey.as_ref() {
1696        Some(rkey) => format!("create-{}-{}", collection.replace('.', "_"), rkey.as_str()),
1697        // Without a client idempotency key, distinct omitted-key requests
1698        // create distinct records. Key allocation itself stays in the writer.
1699        None => format!("create-{}", uuid::Uuid::new_v4()),
1700    });
1701    let expected_prev = expected_prev.map(str::to_owned);
1702    let request = crate::services::public_repo::PublicCreateRequest {
1703        request_id,
1704        principal: user.user,
1705        did: repo.clone().unwrap_or_default(),
1706        collection: collection.to_owned(),
1707        rkey,
1708        value: record,
1709        expected_prev: None,
1710    };
1711    // Authorization remains inside the transaction before any store access.
1712    // Native locks, RocksDB, signing and sync writes must not occupy Tokio workers.
1713    let result = if let Some(writer) = state
1714        .hosted_public_repo_writer
1715        .as_ref()
1716        .filter(|_| hosted_target)
1717    {
1718        writer
1719            .create_record(request, expected_prev.as_deref())
1720            .await
1721    } else {
1722        let Some(writer) = state.public_repo_writer.as_ref() else {
1723            return xrpc_error(
1724                StatusCode::SERVICE_UNAVAILABLE,
1725                errors::INTERNAL_SERVER_ERROR,
1726                "public repository writer is not configured",
1727            );
1728        };
1729        let writer = Arc::clone(writer);
1730        tokio::task::spawn_blocking(move || {
1731            writer.create_record_with_expected_prev_text(request, expected_prev.as_deref())
1732        })
1733        .await
1734        .unwrap_or_else(|error| {
1735            Err(crate::services::public_repo::PublicRepoWriteError::Internal(error.into()))
1736        })
1737    };
1738    use crate::services::public_repo::PublicRepoWriteError;
1739    let result = match result {
1740        Ok(result) => result,
1741        Err(error) => {
1742            let (status, code, message) = match error {
1743                PublicRepoWriteError::InvalidRequest(_) => (
1744                    StatusCode::BAD_REQUEST,
1745                    errors::INVALID_REQUEST,
1746                    "record or request parameters are invalid",
1747                ),
1748                PublicRepoWriteError::Authorization(_) => (
1749                    StatusCode::FORBIDDEN,
1750                    "AuthRequired",
1751                    "public repository publication is not authorized",
1752                ),
1753                PublicRepoWriteError::RecordAlreadyExists => (
1754                    StatusCode::CONFLICT,
1755                    "RecordAlreadyExists",
1756                    "record key already exists",
1757                ),
1758                PublicRepoWriteError::InvalidSwap => (
1759                    StatusCode::CONFLICT,
1760                    "InvalidSwap",
1761                    "swapCommit does not match the repository head",
1762                ),
1763                PublicRepoWriteError::Internal(_) => (
1764                    StatusCode::INTERNAL_SERVER_ERROR,
1765                    "InternalServerError",
1766                    "public repository operation failed",
1767                ),
1768            };
1769            return xrpc_error(status, code, message);
1770        }
1771    };
1772    let mut response = json!({"uri": result.uri, "cid": result.cid.to_string()});
1773    if return_record {
1774        response["value"] = record_value.clone();
1775    }
1776    (StatusCode::OK, axum::Json(response)).into_response()
1777}
1778
1779fn parse_swap_commit(value: Option<&Value>) -> Result<Option<&str>, &'static str> {
1780    match value {
1781        None => Ok(None),
1782        Some(Value::String(value)) if !value.is_empty() => Ok(Some(value.as_str())),
1783        Some(Value::String(_)) => Err("swapCommit must be a non-empty CID"),
1784        Some(_) => Err("swapCommit must be a string"),
1785    }
1786}
1787
1788fn parse_return_record(value: Option<&Value>) -> Result<bool, &'static str> {
1789    match value {
1790        None => Ok(false),
1791        Some(Value::Bool(value)) => Ok(*value),
1792        Some(_) => Err("returnRecord must be a boolean"),
1793    }
1794}
1795
1796// ─────────────────────────────────────────────────────────────────────────────
1797// Tests
1798// ─────────────────────────────────────────────────────────────────────────────
1799
1800#[cfg(test)]
1801#[allow(clippy::unwrap_used, clippy::expect_used)]
1802mod tests {
1803    use super::*;
1804    use p256::ecdsa::SigningKey;
1805    use rand::rngs::OsRng;
1806
1807    fn sample_snapshot(did: &str, handle: &str, public: bool) -> RepoSnapshot {
1808        let signing = SigningKey::random(&mut OsRng);
1809        let vk = VerifyingKey::from(&signing);
1810        let repo_at_uri = format!("at://{did}");
1811        let rec = ModelRecord::new(
1812            &repo_at_uri,
1813            "bafyreiexamplecurrentoid000000000000000000000000000a",
1814            "2026-07-19T00:00:00.000Z",
1815        )
1816        .expect("valid record");
1817        let tid = Tid::now();
1818        let mut record_cids: BTreeMap<Tid, Cid> = BTreeMap::new();
1819        record_cids.insert(tid, rec.cid());
1820        let mut records: BTreeMap<Tid, ModelRecord> = BTreeMap::new();
1821        records.insert(tid, rec);
1822        let tree = Node::from_records(HOSTED_COLLECTION, &record_cids);
1823        let (_root_data, node_blocks) = tree.to_node_data_with_blocks();
1824        let root_cid = tree.root_cid();
1825        use hyprstream_pds::commit::UnsignedCommit;
1826        let unsigned = UnsignedCommit::new(did.to_owned(), root_cid, Tid::now(), None);
1827        let commit = Commit::sign(&unsigned, &signing);
1828        commit.verify(&vk).expect("self-signed commit verifies");
1829        RepoSnapshot {
1830            did: did.to_owned(),
1831            handle: handle.to_owned(),
1832            commit,
1833            node_blocks,
1834            records,
1835            atproto_vk: vk,
1836            public,
1837        }
1838    }
1839
1840    /// Read a response body as a JSON Value.
1841    async fn body_json(resp: Response) -> Value {
1842        let bytes = axum::body::to_bytes(resp.into_body(), 1024 * 1024)
1843            .await
1844            .unwrap();
1845        serde_json::from_slice(&bytes).unwrap()
1846    }
1847
1848    #[test]
1849    fn public_canary_requires_exact_tuple_and_record_path() {
1850        let did = hyprstream_rpc::did_key::ed25519_to_did_key(&[7u8; 32]);
1851        let oauth_did = hyprstream_rpc::did_key::ed25519_to_did_key(&[8u8; 32]);
1852        let snapshot = sample_snapshot(&did, "publisher.example", true);
1853        let rkey = snapshot.records.keys().next().unwrap().to_string();
1854        let canary = super::super::state::PublicGitCanaryRecord {
1855            did: did.clone(),
1856            rkey: rkey.clone(),
1857        };
1858        let params = std::collections::HashMap::from([
1859            ("repo".to_owned(), did.clone()),
1860            ("collection".to_owned(), COLLECTION_NSID.to_owned()),
1861            ("rkey".to_owned(), rkey.clone()),
1862        ]);
1863        let raw = format!("repo={did}&collection={COLLECTION_NSID}&rkey={rkey}");
1864        assert_eq!(canary_request(&canary, Some(&raw), &params), Some(None));
1865        for (key, value) in [
1866            ("repo", oauth_did.as_str()),
1867            ("collection", "app.bsky.feed.post"),
1868            ("rkey", "unrelated"),
1869        ] {
1870            let mut wrong = params.clone();
1871            wrong.insert(key.to_owned(), value.to_owned());
1872            assert!(canary_request(&canary, Some(&raw), &wrong).is_none());
1873        }
1874        let mut extra = params.clone();
1875        extra.insert("cursor".to_owned(), "private".to_owned());
1876        assert!(canary_request(&canary, Some(&raw), &extra).is_none());
1877        let duplicate = format!("{raw}&repo={did}");
1878        assert!(
1879            canary_request(&canary, Some(&duplicate), &parse_query(Some(&duplicate))).is_none()
1880        );
1881
1882        let car = snapshot.record_proof_car(&rkey).unwrap();
1883        let keys = PublishedAtprotoKeys::single(snapshot.atproto_vk);
1884        let (record, cid) = canary_record_from_car(&car, &canary, &keys, 0).unwrap();
1885        assert_eq!(record.repo, format!("at://{did}"));
1886        assert_eq!(cid, snapshot.records.values().next().unwrap().cid());
1887        let wrong_cid = canary_record_response("at://fixed", record, cid, Some("bafywrong"));
1888        assert_eq!(wrong_cid.status(), StatusCode::BAD_REQUEST);
1889        let wrong_did = super::super::state::PublicGitCanaryRecord {
1890            did: oauth_did,
1891            rkey,
1892        };
1893        assert!(canary_record_from_car(&car, &wrong_did, &keys, 0).is_none());
1894        let wrong_rkey = super::super::state::PublicGitCanaryRecord {
1895            did,
1896            rkey: "unrelated".to_owned(),
1897        };
1898        assert!(canary_record_from_car(&car, &wrong_rkey, &keys, 0).is_none());
1899        let different_es256 = SigningKey::random(&mut OsRng);
1900        let wrong_keys = PublishedAtprotoKeys::single(VerifyingKey::from(&different_es256));
1901        assert!(canary_record_from_car(&car, &canary, &wrong_keys, 0).is_none());
1902    }
1903
1904    #[cfg(feature = "rocksdb")]
1905    #[tokio::test]
1906    async fn idle_canary_recovers_after_rotation_using_sealed_head_maintenance() {
1907        use crate::auth::key_rotation::{
1908            persist_es256_slot, rotate_es256_keys, Es256KeySlot, Es256KeySlots,
1909            Es256SigningKeyStore,
1910        };
1911        use crate::auth::op_log::{
1912            publish_head_verifying_key, seal_op_log_head, SealedHeadEs256Source,
1913            SEALED_HEAD_FILENAME,
1914        };
1915        use crate::services::discovery::{PdsPublisher, PdsRecordResolver, PdsRecordStore};
1916        use hyprstream_discovery::RecordResolver;
1917        use std::sync::Arc;
1918
1919        fn published_keys(store: &Es256SigningKeyStore) -> PublishedAtprotoKeys {
1920            let slots = store.slots_snapshot();
1921            PublishedAtprotoKeys::from_published_slots(
1922                *slots.active.unwrap().key.verifying_key(),
1923                slots.drain.map(|s| (*s.key.verifying_key(), s.nbf, s.exp)),
1924                slots.lead.map(|s| (*s.key.verifying_key(), s.nbf, s.exp)),
1925            )
1926            .unwrap()
1927        }
1928        fn commit(car: &[u8]) -> Commit {
1929            let (roots, blocks) = parse_car_v1(car).unwrap();
1930            let (_, bytes) = blocks.iter().find(|(cid, _)| *cid == roots[0]).unwrap();
1931            Commit::from_dag_cbor(bytes).unwrap()
1932        }
1933
1934        let pds = tempfile::tempdir().unwrap();
1935        let secrets = tempfile::tempdir().unwrap();
1936        let state = tempfile::tempdir().unwrap();
1937        let now = chrono::Utc::now().timestamp();
1938        let a = Es256KeySlot::new(SigningKey::random(&mut OsRng), now - 100, now + 1);
1939        let b = Es256KeySlot::new(SigningKey::random(&mut OsRng), now - 1, now + 1000);
1940        persist_es256_slot(secrets.path(), "active", &a).unwrap();
1941        persist_es256_slot(secrets.path(), "lead", &b).unwrap();
1942        let rotator = Es256SigningKeyStore::new(Es256KeySlots {
1943            active: Some(a.clone()),
1944            drain: None,
1945            lead: Some(b),
1946        });
1947        // A separate process-local cache intentionally stays on A. Production
1948        // maintenance must use the authenticated shared head, not this cache.
1949        let stale_cache = Arc::new(Es256SigningKeyStore::new(Es256KeySlots {
1950            active: Some(a),
1951            drain: None,
1952            lead: None,
1953        }));
1954        let head_signer = ed25519_dalek::SigningKey::generate(&mut OsRng);
1955        publish_head_verifying_key(state.path(), &head_signer).unwrap();
1956        seal_op_log_head(state.path(), &head_signer, &rotator)
1957            .await
1958            .unwrap();
1959        let did = hyprstream_rpc::did_key::ed25519_to_did_key(&[7u8; 32]);
1960        let repo_id = "00000000-0000-4000-8000-000000000123";
1961        let store = Arc::new(PdsRecordStore::open(pds.path()).unwrap());
1962        let publisher = PdsPublisher::with_generation_source(
1963            Arc::clone(&store),
1964            did.clone(),
1965            Arc::new(SealedHeadEs256Source::new(state.path(), secrets.path())),
1966        )
1967        .with_es256_store(stale_cache);
1968        let resolver = PdsRecordResolver::new(store);
1969        // The only publish in the test: no new Git commit or pointer advance
1970        // may hide the idle-head failure after key rotation.
1971        publisher
1972            .publish(repo_id, "3f1d3a63258e132cd06314b736445a8bab13b9bd")
1973            .unwrap();
1974        let rkey = PdsRecordStore::tid_for_repo(repo_id).to_string();
1975        let canary = super::super::state::PublicGitCanaryRecord {
1976            did: did.clone(),
1977            rkey: rkey.clone(),
1978        };
1979        let original = resolver
1980            .resolve_record(&did, COLLECTION_NSID, &rkey)
1981            .await
1982            .unwrap()
1983            .unwrap();
1984        let original_commit = commit(&original.car);
1985        let config = crate::config::OAuthConfig {
1986            jwt_key_active_secs: Some(1000),
1987            jwt_key_lead_secs: Some(100),
1988            jwt_key_drain_secs: Some(120),
1989            ..Default::default()
1990        };
1991        assert!(rotate_es256_keys(&config, secrets.path(), &rotator, now).await);
1992        seal_op_log_head(state.path(), &head_signer, &rotator)
1993            .await
1994            .unwrap();
1995        let (record, record_cid) =
1996            canary_record_from_car(&original.car, &canary, &published_keys(&rotator), now + 1)
1997                .expect("original CAR verifies during A overlap");
1998        let original_json = body_json(canary_record_response(
1999            &original.uri,
2000            record,
2001            record_cid,
2002            None,
2003        ))
2004        .await;
2005
2006        let after_drain = now + 120;
2007        rotate_es256_keys(&config, secrets.path(), &rotator, after_drain).await;
2008        assert!(rotator.slots_snapshot().drain.is_none());
2009        let expired_keys = published_keys(&rotator);
2010        assert!(
2011            canary_record_from_car(&original.car, &canary, &expired_keys, after_drain).is_none()
2012        );
2013        assert_eq!(
2014            resolver
2015                .resolve_record(&did, COLLECTION_NSID, &rkey)
2016                .await
2017                .unwrap()
2018                .unwrap()
2019                .car,
2020            original.car,
2021            "key rotation alone did not rewrite the idle head"
2022        );
2023
2024        // Exercise the real production maintenance entry point. This fixture
2025        // deliberately lacks at9p ingest: that independent renewal error must
2026        // not prevent the idle model record from recovering.
2027        let error = crate::services::at9p_renewal::run_renewal_tick(
2028            &publisher,
2029            secrets.path(),
2030            600,
2031            None,
2032            chrono::DateTime::from_timestamp(after_drain, 0).unwrap(),
2033        )
2034        .expect_err("independent at9p fixture is absent");
2035        assert!(error.to_string().contains("daemon-owned state ingest"));
2036        let refreshed = resolver
2037            .resolve_record(&did, COLLECTION_NSID, &rkey)
2038            .await
2039            .unwrap()
2040            .unwrap();
2041        let (record, cid) =
2042            canary_record_from_car(&refreshed.car, &canary, &expired_keys, after_drain)
2043                .expect("sealed B generation recovers exact public record");
2044        assert_eq!(refreshed.uri, original.uri);
2045        assert_eq!(
2046            body_json(canary_record_response(&refreshed.uri, record, cid, None)).await,
2047            original_json
2048        );
2049        let refreshed_commit = commit(&refreshed.car);
2050        assert_eq!(
2051            refreshed_commit.unsigned().to_dag_cbor(),
2052            original_commit.unsigned().to_dag_cbor()
2053        );
2054        assert_ne!(refreshed_commit.sig, original_commit.sig);
2055        assert_ne!(refreshed_commit.cid(), original_commit.cid());
2056        assert!(
2057            !publisher.resign_head().unwrap(),
2058            "same generation is a no-op"
2059        );
2060        assert!(
2061            canary_record_from_car(&original.car, &canary, &expired_keys, after_drain).is_none(),
2062            "maintenance must not broaden old-key acceptance"
2063        );
2064
2065        let head = state.path().join(SEALED_HEAD_FILENAME);
2066        let signed_head = std::fs::read(&head).unwrap();
2067        std::fs::remove_file(&head).unwrap();
2068        assert!(
2069            publisher.resign_head().is_err(),
2070            "missing sealed authority cannot fall back to cache"
2071        );
2072        std::fs::write(&head, b"{}").unwrap();
2073        assert!(
2074            publisher.resign_head().is_err(),
2075            "unverifiable sealed authority cannot fall back to cache"
2076        );
2077        std::fs::write(&head, signed_head).unwrap();
2078        assert_eq!(
2079            resolver
2080                .resolve_record(&did, COLLECTION_NSID, &rkey)
2081                .await
2082                .unwrap()
2083                .unwrap()
2084                .car,
2085            refreshed.car,
2086            "failed authority checks leave retained record/head unchanged"
2087        );
2088    }
2089
2090    #[test]
2091    fn create_record_optional_fields_reject_wrong_types() {
2092        assert_eq!(parse_swap_commit(None).unwrap(), None);
2093        assert_eq!(
2094            parse_swap_commit(Some(&json!("bafyhead"))).unwrap(),
2095            Some("bafyhead")
2096        );
2097        assert_eq!(
2098            parse_swap_commit(Some(&json!(""))).unwrap_err(),
2099            "swapCommit must be a non-empty CID"
2100        );
2101        assert_eq!(
2102            parse_swap_commit(Some(&json!(42))).unwrap_err(),
2103            "swapCommit must be a string"
2104        );
2105        assert!(!parse_return_record(None).unwrap());
2106        assert!(parse_return_record(Some(&Value::Bool(true))).unwrap());
2107        assert_eq!(
2108            parse_return_record(Some(&json!("yes"))).unwrap_err(),
2109            "returnRecord must be a boolean"
2110        );
2111    }
2112
2113    // ── Finding 1: lazy CAR + owned permit held until EOF ───────────────────
2114
2115    #[tokio::test]
2116    async fn lazy_car_stream_produces_valid_car() {
2117        let snap = Arc::new(sample_snapshot(
2118            "did:web:h.example.com",
2119            "h.example.com",
2120            true,
2121        ));
2122        let store = XrpcRepoStore::new();
2123        let permit = store.acquire_get_repo_owned().await.unwrap();
2124        let strm = lazy_car_stream(Arc::clone(&snap), permit);
2125        // Collect all sections and concatenate.
2126        use futures::StreamExt;
2127        let mut collected: Vec<u8> = Vec::new();
2128        futures::pin_mut!(strm);
2129        while let Some(chunk) = strm.next().await {
2130            collected.extend_from_slice(&chunk.unwrap());
2131        }
2132        // Parse as a CARv1 and verify the commit root.
2133        let (roots, blocks) = hyprstream_pds::car::parse_car_v1(&collected).unwrap();
2134        assert_eq!(roots.len(), 1);
2135        assert_eq!(roots[0], snap.commit.cid());
2136        assert!(blocks.len() >= 3); // commit + MST + record
2137    }
2138
2139    #[tokio::test]
2140    async fn semaphore_owned_permit_held_until_stream_drop() {
2141        // With concurrency = 4, acquire 4 permits. The 5th must block.
2142        // Dropping one permit unblocks the 5th.
2143        let store = XrpcRepoStore::new();
2144        let mut permits: Vec<OwnedSemaphorePermit> = Vec::new();
2145        for _ in 0..GET_REPO_CONCURRENCY {
2146            permits.push(store.acquire_get_repo_owned().await.unwrap());
2147        }
2148        // The N+1th acquire must not complete immediately.
2149        let next = store.acquire_get_repo_owned();
2150        tokio::pin!(next);
2151        tokio::select! {
2152            _ = &mut next => panic!("N+1th permit acquired before capacity freed"),
2153            _ = tokio::time::sleep(std::time::Duration::from_millis(50)) => {}
2154        }
2155        // Drop one permit — the N+1th should now complete.
2156        permits.pop();
2157        let _extra = next.await.expect("N+1th permit resolves after drop");
2158    }
2159
2160    #[tokio::test]
2161    async fn lazy_car_stream_releases_permit_on_drop() {
2162        // The permit held inside the lazy stream must be released when the
2163        // stream is dropped (e.g. client disconnects mid-body).
2164        let store = XrpcRepoStore::new();
2165        // Exhaust all permits.
2166        let mut held: Vec<OwnedSemaphorePermit> = Vec::new();
2167        for _ in 0..GET_REPO_CONCURRENCY {
2168            held.push(store.acquire_get_repo_owned().await.unwrap());
2169        }
2170        let snap = Arc::new(sample_snapshot(
2171            "did:web:h.example.com",
2172            "h.example.com",
2173            true,
2174        ));
2175        // Acquire one more for the stream.
2176        let stream_permit = held.pop().unwrap();
2177        let strm = lazy_car_stream(snap, stream_permit);
2178        // Drop the stream without consuming it — permit must be released.
2179        drop(strm);
2180        // Now we should be able to acquire a new permit.
2181        let _new = store
2182            .acquire_get_repo_owned()
2183            .await
2184            .expect("permit available after stream dropped");
2185    }
2186
2187    // ── Finding 2: endpoint-level tests ──────────────────────────────────────
2188
2189    const ISSUER: &str = "https://h.example.com";
2190
2191    #[tokio::test]
2192    async fn endpoint_non_public_invisible_describe_repo() {
2193        let store = XrpcRepoStore::new();
2194        store
2195            .put(sample_snapshot(
2196                "did:web:priv.example.com",
2197                "priv.example.com",
2198                false,
2199            ))
2200            .await
2201            .unwrap();
2202        let resp = describe_repo_core(&store, ISSUER, "did:web:priv.example.com").await;
2203        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
2204        let body = body_json(resp).await;
2205        assert_eq!(body["error"], errors::REPO_NOT_FOUND);
2206    }
2207
2208    #[tokio::test]
2209    async fn endpoint_non_public_invisible_get_record() {
2210        let store = XrpcRepoStore::new();
2211        store
2212            .put(sample_snapshot(
2213                "did:web:priv.example.com",
2214                "priv.example.com",
2215                false,
2216            ))
2217            .await
2218            .unwrap();
2219        let resp = get_record_core(
2220            &store,
2221            "did:web:priv.example.com",
2222            HOSTED_COLLECTION,
2223            "anything",
2224            None,
2225        )
2226        .await;
2227        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
2228        let body = body_json(resp).await;
2229        assert_eq!(body["error"], errors::REPO_NOT_FOUND);
2230    }
2231
2232    #[tokio::test]
2233    async fn endpoint_non_public_invisible_get_repo() {
2234        let store = XrpcRepoStore::new();
2235        store
2236            .put(sample_snapshot(
2237                "did:web:priv.example.com",
2238                "priv.example.com",
2239                false,
2240            ))
2241            .await
2242            .unwrap();
2243        let resp = get_repo_core(&store, "did:web:priv.example.com", false).await;
2244        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
2245        let body = body_json(resp).await;
2246        assert_eq!(body["error"], errors::REPO_NOT_FOUND);
2247    }
2248
2249    #[tokio::test]
2250    async fn endpoint_non_public_invisible_resolve_handle() {
2251        let store = XrpcRepoStore::new();
2252        store
2253            .put(sample_snapshot(
2254                "did:web:priv.example.com",
2255                "priv.example.com",
2256                false,
2257            ))
2258            .await
2259            .unwrap();
2260        let resp = resolve_handle_core(&store, ISSUER, "priv.example.com").await;
2261        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
2262        let body = body_json(resp).await;
2263        assert_eq!(body["error"], errors::HANDLE_NOT_FOUND);
2264    }
2265
2266    #[tokio::test]
2267    async fn endpoint_public_snapshot_visible_describe_repo() {
2268        let store = XrpcRepoStore::new();
2269        store
2270            .put(sample_snapshot(
2271                "did:web:pub.example.com",
2272                "pub.example.com",
2273                true,
2274            ))
2275            .await
2276            .unwrap();
2277        let resp = describe_repo_core(&store, ISSUER, "did:web:pub.example.com").await;
2278        assert_eq!(resp.status(), StatusCode::OK);
2279        let body = body_json(resp).await;
2280        assert_eq!(body["did"], "did:web:pub.example.com");
2281        assert_eq!(body["handleIsCorrect"], true);
2282        assert!(!body["collections"].as_array().unwrap().is_empty());
2283    }
2284
2285    #[tokio::test]
2286    async fn store_rejects_path_form_did_web_snapshot() {
2287        let store = XrpcRepoStore::new();
2288        let did = "did:web:accounts.example:users:alice";
2289        let err = store
2290            .put(sample_snapshot(did, "alice.example", true))
2291            .await
2292            .unwrap_err();
2293        assert!(err.to_string().contains("path-form did:web"));
2294        assert!(store.get(did).await.is_none());
2295    }
2296
2297    #[tokio::test]
2298    async fn endpoint_get_record_cid_mismatch() {
2299        let store = XrpcRepoStore::new();
2300        let snap = sample_snapshot("did:web:pub.example.com", "pub.example.com", true);
2301        let rkey = snap.records.keys().next().unwrap().encode();
2302        store.put(snap).await.unwrap();
2303        let resp = get_record_core(
2304            &store,
2305            "did:web:pub.example.com",
2306            HOSTED_COLLECTION,
2307            &rkey,
2308            Some("bafyreiwrongcid000000000000000000000000000000000000"),
2309        )
2310        .await;
2311        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
2312        let body = body_json(resp).await;
2313        assert_eq!(body["error"], errors::RECORD_NOT_FOUND);
2314    }
2315
2316    #[tokio::test]
2317    async fn endpoint_get_record_cid_match_succeeds() {
2318        let store = XrpcRepoStore::new();
2319        let snap = sample_snapshot("did:web:pub.example.com", "pub.example.com", true);
2320        let rkey = snap.records.keys().next().unwrap().encode();
2321        let cid = snap.records.values().next().unwrap().cid().to_string();
2322        store.put(snap).await.unwrap();
2323        let resp = get_record_core(
2324            &store,
2325            "did:web:pub.example.com",
2326            HOSTED_COLLECTION,
2327            &rkey,
2328            Some(&cid),
2329        )
2330        .await;
2331        assert_eq!(resp.status(), StatusCode::OK);
2332    }
2333
2334    // ── Finding 3: since rejected by presence ─────────────────────────────────
2335
2336    #[tokio::test]
2337    async fn since_non_empty_rejected() {
2338        let store = XrpcRepoStore::new();
2339        store
2340            .put(sample_snapshot(
2341                "did:web:pub.example.com",
2342                "pub.example.com",
2343                true,
2344            ))
2345            .await
2346            .unwrap();
2347        let resp = get_repo_core(&store, "did:web:pub.example.com", true).await;
2348        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
2349        let body = body_json(resp).await;
2350        assert_eq!(body["error"], errors::INVALID_REQUEST);
2351    }
2352
2353    #[tokio::test]
2354    async fn get_repo_without_since_succeeds() {
2355        let store = XrpcRepoStore::new();
2356        store
2357            .put(sample_snapshot(
2358                "did:web:pub.example.com",
2359                "pub.example.com",
2360                true,
2361            ))
2362            .await
2363            .unwrap();
2364        let resp = get_repo_core(&store, "did:web:pub.example.com", false).await;
2365        assert_eq!(resp.status(), StatusCode::OK);
2366        assert_eq!(
2367            resp.headers().get(header::CONTENT_TYPE).unwrap(),
2368            "application/vnd.ipld.car",
2369        );
2370    }
2371
2372    // ── Helper / unit tests ───────────────────────────────────────────────────
2373
2374    #[test]
2375    fn error_body_shape_is_xrpc_convention() {
2376        let body = xrpc_error_body("RecordNotFound", "no such record");
2377        assert_eq!(body["error"], "RecordNotFound");
2378        assert_eq!(body["message"], "no such record");
2379        assert_eq!(body.as_object().unwrap().len(), 2);
2380    }
2381
2382    #[test]
2383    fn parse_query_empty_value_since_is_present() {
2384        // ?since= → key "since" present with value "".
2385        let q = parse_query(Some("did=did:web:x&since="));
2386        assert!(q.contains_key("since"));
2387        assert_eq!(q.get("since").map(std::string::String::as_str), Some(""));
2388    }
2389
2390    #[test]
2391    fn parse_query_bare_key_since_is_present() {
2392        // ?since (no =) → key "since" present with value "".
2393        let q = parse_query(Some("did=did:web:x&since"));
2394        assert!(q.contains_key("since"));
2395        assert_eq!(q.get("since").map(std::string::String::as_str), Some(""));
2396    }
2397
2398    #[test]
2399    fn parse_query_percent_decodes_values() {
2400        // did%3Aweb%3Ax → did:web:x (colons percent-encoded).
2401        let q = parse_query(Some("repo=did%3Aweb%3Ax&collection=ai.hyprstream.model"));
2402        assert_eq!(
2403            q.get("repo").map(std::string::String::as_str),
2404            Some("did:web:x")
2405        );
2406        assert_eq!(
2407            q.get("collection").map(std::string::String::as_str),
2408            Some("ai.hyprstream.model")
2409        );
2410    }
2411
2412    #[test]
2413    fn parse_query_plus_becomes_space() {
2414        let q = parse_query(Some("handle=foo+bar"));
2415        assert_eq!(
2416            q.get("handle").map(std::string::String::as_str),
2417            Some("foo bar")
2418        );
2419    }
2420
2421    #[test]
2422    fn parse_query_extracts_key_value_pairs() {
2423        let q = parse_query(Some(
2424            "repo=did:web:x&collection=ai.hyprstream.model&rkey=abc",
2425        ));
2426        assert_eq!(
2427            q.get("repo").map(std::string::String::as_str),
2428            Some("did:web:x")
2429        );
2430        assert_eq!(
2431            q.get("collection").map(std::string::String::as_str),
2432            Some("ai.hyprstream.model")
2433        );
2434    }
2435
2436    #[test]
2437    fn service_auth_query_is_strict_and_method_bound() {
2438        assert_eq!(
2439            parse_get_service_auth_query(Some(
2440                "aud=did%3Aweb%3Apds.example.test&lxm=ai.hyprstream.identity.exchangeSession"
2441            ))
2442            .unwrap(),
2443            GetServiceAuthParams {
2444                aud: "did:web:pds.example.test".to_owned(),
2445                exp: None,
2446                lxm: ATPROTO_SESSION_EXCHANGE_NSID.to_owned(),
2447            }
2448        );
2449        for malformed in [
2450            "",
2451            "aud=did:web:pds.example.test",
2452            "lxm=ai.hyprstream.identity.exchangeSession",
2453            "aud=did:web:pds.example.test&aud=did:web:other&lxm=ai.hyprstream.identity.exchangeSession",
2454            "aud=did:web:pds.example.test&lxm=ai.hyprstream.identity.exchangeSession&extra=1",
2455            "aud=did:web:pds.example.test&lxm=ai.hyprstream.identity.exchangeSession&exp=tomorrow",
2456        ] {
2457            assert!(
2458                parse_get_service_auth_query(Some(malformed)).is_err(),
2459                "query should fail closed: {malformed}"
2460            );
2461        }
2462    }
2463
2464    // ── Router-mounted tests (findings 1 + 2) ─────────────────────────────────
2465
2466    use crate::config::OAuthConfig;
2467    use axum::body::Body;
2468    use axum::http::Request as HttpRequest;
2469    use axum::Router;
2470    use hyprstream_rpc_std::discovery_client::DiscoveryClient;
2471    use hyprstream_rpc_std::policy_client::PolicyClient;
2472    use tower::ServiceExt; // oneshot
2473
2474    /// Build a real OAuthState with dummy PolicyClient/DiscoveryClient (LazyUdsTransport
2475    /// pointing at /dev/null — never opened). Seeds a public + private snapshot.
2476    async fn build_test_state(xrpc_enabled: bool) -> Arc<OAuthState> {
2477        use hyprstream_rpc::rpc_client::RpcClientImpl;
2478        use hyprstream_rpc::signer::LocalSigner;
2479        use hyprstream_rpc::transport::lazy_uds::LazyUdsTransport;
2480
2481        let key = ed25519_dalek::SigningKey::from_bytes(&[0x76; 32]);
2482        let vk = ed25519_dalek::SigningKey::from_bytes(&[0x73; 32]).verifying_key();
2483        let dummy = std::path::PathBuf::from("/dev/null/xrpc-test.sock");
2484
2485        let mk_client = || {
2486            let rpc = RpcClientImpl::new(
2487                LocalSigner::new(key.clone()),
2488                LazyUdsTransport::new(dummy.clone()),
2489                Some(vk),
2490            )
2491            .with_response_verify_policy(hyprstream_rpc::crypto::CryptoPolicy::Classical);
2492            Arc::new(rpc)
2493        };
2494
2495        let mut config = OAuthConfig::default();
2496        config.xrpc_read_slice = xrpc_enabled;
2497        config.external_url = Some("https://h.example.com".to_owned());
2498
2499        let state = Arc::new(OAuthState::new(
2500            &config,
2501            PolicyClient::new(mk_client()),
2502            DiscoveryClient::new(mk_client()),
2503            [0x76; 32],
2504        ));
2505
2506        state
2507            .xrpc_repos
2508            .put(sample_snapshot(
2509                "did:web:pub.example.com",
2510                "pub.example.com",
2511                true,
2512            ))
2513            .await
2514            .unwrap();
2515        state
2516            .xrpc_repos
2517            .put(sample_snapshot(
2518                "did:web:priv.example.com",
2519                "priv.example.com",
2520                false,
2521            ))
2522            .await
2523            .unwrap();
2524        state
2525    }
2526
2527    /// Build a router through the PRODUCTION `oauth::create_app` builder with
2528    /// `xrpc_read_slice=true` — exercises the real feature-gate conditional.
2529    async fn build_xrpc_router() -> Router {
2530        build_production_app(true).await
2531    }
2532
2533    /// Build the production `create_app` with the given feature-gate value.
2534    async fn build_production_app(xrpc_enabled: bool) -> Router {
2535        use crate::config::server::CorsConfig;
2536        let state = build_test_state(xrpc_enabled).await;
2537        let cors = CorsConfig {
2538            enabled: false,
2539            ..Default::default()
2540        };
2541        crate::services::oauth::create_app(state, &cors)
2542    }
2543
2544    /// Wrap a pre-built state in the production `create_app` (for tests that
2545    /// seed additional snapshots before constructing the router).
2546    async fn build_production_app_from_state(state: Arc<OAuthState>) -> Router {
2547        use crate::config::server::CorsConfig;
2548        let cors = CorsConfig {
2549            enabled: false,
2550            ..Default::default()
2551        };
2552        crate::services::oauth::create_app(state, &cors)
2553    }
2554
2555    /// Like `sample_snapshot` but with a fixed TID so the rkey/CID are deterministic.
2556    fn sample_snapshot_fixed_tid(did: &str, handle: &str, public: bool) -> RepoSnapshot {
2557        let mut snap = sample_snapshot(did, handle, public);
2558        // Rebuild with a fixed TID for deterministic rkey.
2559        let signing = p256::ecdsa::SigningKey::random(&mut OsRng);
2560        let vk = VerifyingKey::from(&signing);
2561        let repo_at_uri = format!("at://{did}");
2562        let rec = ModelRecord::new(
2563            &repo_at_uri,
2564            "bafyreiexamplecurrentoid000000000000000000000000000a",
2565            "2026-07-19T00:00:00.000Z",
2566        )
2567        .expect("valid record");
2568        let fixed_tid = Tid::from_micros(1_700_000_000_000_000, 1);
2569        let mut record_cids: BTreeMap<Tid, Cid> = BTreeMap::new();
2570        record_cids.insert(fixed_tid, rec.cid());
2571        let mut records: BTreeMap<Tid, ModelRecord> = BTreeMap::new();
2572        records.insert(fixed_tid, rec);
2573        let tree = Node::from_records(HOSTED_COLLECTION, &record_cids);
2574        let (_root_data, node_blocks) = tree.to_node_data_with_blocks();
2575        let root_cid = tree.root_cid();
2576        use hyprstream_pds::commit::UnsignedCommit;
2577        let unsigned = UnsignedCommit::new(did.to_owned(), root_cid, Tid::now(), None);
2578        let commit = Commit::sign(&unsigned, &signing);
2579        snap.commit = commit;
2580        snap.node_blocks = node_blocks;
2581        snap.records = records;
2582        snap.atproto_vk = vk;
2583        snap
2584    }
2585
2586    async fn resp_json(resp: axum::response::Response) -> Value {
2587        body_json(resp).await
2588    }
2589
2590    fn req(uri: &str) -> HttpRequest<Body> {
2591        HttpRequest::builder().uri(uri).body(Body::empty()).unwrap()
2592    }
2593
2594    #[tokio::test]
2595    async fn service_auth_is_mounted_and_protected_without_public_read_slice() {
2596        let app = build_production_app(false).await;
2597        let response = app
2598            .oneshot(req("/xrpc/com.atproto.server.getServiceAuth\
2599                 ?aud=did%3Aweb%3Ah.example.com\
2600                 &lxm=ai.hyprstream.identity.exchangeSession"))
2601            .await
2602            .unwrap();
2603        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
2604    }
2605
2606    #[tokio::test]
2607    async fn router_create_record_is_absent_without_explicit_public_writer() {
2608        // The production builder must not expose a write endpoint until a
2609        // native-authorized PublicRepoWriter is explicitly installed.
2610        let app = build_production_app(true).await;
2611        let response = app
2612            .oneshot(
2613                HttpRequest::builder()
2614                    .method("POST")
2615                    .uri("/xrpc/com.atproto.repo.createRecord")
2616                    .header(header::CONTENT_TYPE, "application/json")
2617                    .body(Body::from(
2618                        r#"{"repo":"did:web:pub.example.com","collection":"app.bsky.feed.post","rkey":"3jzfcijpj2z2a","record":{}}"#,
2619                    ))
2620                    .unwrap(),
2621            )
2622            .await
2623            .unwrap();
2624        assert_eq!(response.status(), StatusCode::NOT_FOUND);
2625    }
2626
2627    #[derive(Default)]
2628    struct WriteInputGate(
2629        std::sync::atomic::AtomicUsize,
2630        parking_lot::Mutex<Option<String>>,
2631    );
2632
2633    impl crate::services::public_repo::PublicPublicationAuthorizer for WriteInputGate {
2634        fn authorize(&self, _: &str, _: &str, _: &str) -> anyhow::Result<()> {
2635            self.0.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2636            if let Some(message) = self.1.lock().as_ref() {
2637                anyhow::bail!(message.clone());
2638            }
2639            Ok(())
2640        }
2641    }
2642
2643    #[derive(Clone)]
2644    struct WriteAccess {
2645        token: String,
2646        claims: hyprstream_rpc::auth::Claims,
2647        key: SigningKey,
2648        htu: String,
2649        nonce: String,
2650    }
2651
2652    impl WriteAccess {
2653        fn proof_payload(&self) -> Value {
2654            use sha2::{Digest as _, Sha256};
2655            json!({
2656                "jti": uuid::Uuid::new_v4().to_string(),
2657                "htm": "POST",
2658                "htu": self.htu,
2659                "iat": chrono::Utc::now().timestamp(),
2660                "ath": URL_SAFE_NO_PAD.encode(Sha256::digest(self.token.as_bytes())),
2661                "nonce": self.nonce,
2662            })
2663        }
2664    }
2665
2666    fn sign_write_proof(key: &SigningKey, payload: &Value) -> String {
2667        use p256::ecdsa::signature::Signer as _;
2668        let point = key.verifying_key().to_encoded_point(false);
2669        let header = json!({
2670            "typ": "dpop+jwt",
2671            "alg": "ES256",
2672            "jwk": {
2673                "kty": "EC", "crv": "P-256",
2674                "x": URL_SAFE_NO_PAD.encode(point.x().unwrap()),
2675                "y": URL_SAFE_NO_PAD.encode(point.y().unwrap()),
2676            }
2677        });
2678        let signing_input = format!(
2679            "{}.{}",
2680            URL_SAFE_NO_PAD.encode(serde_json::to_vec(&header).unwrap()),
2681            URL_SAFE_NO_PAD.encode(serde_json::to_vec(payload).unwrap())
2682        );
2683        let signature: p256::ecdsa::Signature = key.sign(signing_input.as_bytes());
2684        format!(
2685            "{signing_input}.{}",
2686            URL_SAFE_NO_PAD.encode(signature.to_bytes())
2687        )
2688    }
2689
2690    async fn build_write_input_fixture() -> (
2691        tempfile::TempDir,
2692        Arc<crate::services::public_repo::PublicRepoStore>,
2693        Arc<WriteInputGate>,
2694        Router,
2695        WriteAccess,
2696    ) {
2697        build_write_input_fixture_for("did:web:pub.example.com", "https://h.example.com").await
2698    }
2699
2700    async fn build_write_input_fixture_for(
2701        did: &str,
2702        issuer_url: &str,
2703    ) -> (
2704        tempfile::TempDir,
2705        Arc<crate::services::public_repo::PublicRepoStore>,
2706        Arc<WriteInputGate>,
2707        Router,
2708        WriteAccess,
2709    ) {
2710        let (dir, store, gate, app, token, _) =
2711            build_write_input_fixture_with_admission(did, issuer_url).await;
2712        (dir, store, gate, app, token)
2713    }
2714
2715    async fn build_write_input_fixture_with_admission(
2716        did: &str,
2717        issuer_url: &str,
2718    ) -> (
2719        tempfile::TempDir,
2720        Arc<crate::services::public_repo::PublicRepoStore>,
2721        Arc<WriteInputGate>,
2722        Router,
2723        WriteAccess,
2724        Arc<XrpcRepoStore>,
2725    ) {
2726        if hyprstream_rpc::auth::global_credential_revocation_store().is_none() {
2727            let _ = hyprstream_rpc::auth::set_global_credential_revocation_store(Arc::new(
2728                hyprstream_rpc::auth::InMemoryCredentialRevocationStore::new(),
2729            ));
2730        }
2731        let dir = tempfile::tempdir().unwrap();
2732        let store =
2733            Arc::new(crate::services::public_repo::PublicRepoStore::open(dir.path()).unwrap());
2734        let gate = Arc::new(WriteInputGate::default());
2735        let writer = crate::services::public_repo::PublicRepoWriter::new(
2736            store.clone(),
2737            did,
2738            SigningKey::random(&mut OsRng),
2739            gate.clone(),
2740        )
2741        .unwrap();
2742        let mut state = build_test_state(true).await;
2743        let signing_key = ed25519_dalek::SigningKey::from_bytes(&[0x19; 32]);
2744        let writable_state = Arc::get_mut(&mut state).unwrap();
2745        writable_state.issuer_url = issuer_url.to_owned();
2746        writable_state.verifying_key_bytes = signing_key.verifying_key().to_bytes();
2747        writable_state.public_repo_writer = Some(Arc::new(writer));
2748        let issuer = state.atproto_issuer_url();
2749        let now = chrono::Utc::now().timestamp();
2750        let key = SigningKey::random(&mut OsRng);
2751        let point = key.verifying_key().to_encoded_point(false);
2752        let jkt = super::super::dpop::DpopKey::Es256 {
2753            x: (*point.x().unwrap()).into(),
2754            y: (*point.y().unwrap()).into(),
2755        }
2756        .jkt();
2757        let nonce = state.issue_dpop_nonce().await;
2758        state.mark_dpop_client_nonced(&jkt).await;
2759        let htu = format!("{issuer}/xrpc/com.atproto.repo.createRecord");
2760        let claims = hyprstream_rpc::auth::Claims::new("xrpc-writer".to_owned(), now, now + 3600)
2761            .with_issuer(issuer.clone())
2762            .with_audience(Some(issuer))
2763            .with_tenant("xrpc-input-tests".to_owned())
2764            .with_client_id("xrpc-input-tests")
2765            .with_scope(Some("atproto".to_owned()))
2766            .with_cnf_jkt_thumbprint(jkt)
2767            .with_jti();
2768        let token = hyprstream_rpc::auth::jwt::encode(&claims, &signing_key);
2769        let token = WriteAccess {
2770            token,
2771            claims,
2772            key,
2773            htu,
2774            nonce,
2775        };
2776        let reads = state.xrpc_repos.clone();
2777        let app = build_production_app_from_state(state).await;
2778        (dir, store, gate, app, token, reads)
2779    }
2780
2781    #[tokio::test]
2782    async fn hosted_router_corrupt_genesis_reads_are_sanitized_without_cache_fallback() {
2783        use crate::services::public_repo::{hosted_tests, PublicRepoStore};
2784        for mode in [
2785            hosted_tests::GenesisFixture::CorruptNative,
2786            hosted_tests::GenesisFixture::InvalidNativeSignature,
2787            hosted_tests::GenesisFixture::CorruptPublic,
2788            hosted_tests::GenesisFixture::WrongKey,
2789        ] {
2790            let (accounts, _) = hosted_tests::authority_fixture_with(mode).await;
2791            let dir = tempfile::tempdir().unwrap();
2792            let store = Arc::new(PublicRepoStore::open(dir.path()).unwrap());
2793            let mut state = build_test_state(true).await;
2794            let writable = Arc::get_mut(&mut state).unwrap();
2795            writable.hosted_account_zone =
2796                Some(crate::account::AccountZone::new("accounts.example.com").unwrap());
2797            writable.hosted_public_repo_writer =
2798                Some(Arc::new(hosted_tests::hosted(store.clone(), accounts)));
2799            writable
2800                .xrpc_repos
2801                .put(sample_snapshot(
2802                    hosted_tests::DID,
2803                    "alice.accounts.example.com",
2804                    true,
2805                ))
2806                .await
2807                .unwrap();
2808            let app = build_production_app_from_state(state).await;
2809            for route in [
2810                format!(
2811                    "/xrpc/com.atproto.repo.describeRepo?repo={}",
2812                    hosted_tests::DID
2813                ),
2814                format!("/xrpc/com.atproto.sync.getRepo?did={}", hosted_tests::DID),
2815            ] {
2816                let response = app.clone().oneshot(read_request(&route)).await.unwrap();
2817                assert_eq!(
2818                    response.status(),
2819                    StatusCode::INTERNAL_SERVER_ERROR,
2820                    "{mode:?}"
2821                );
2822                assert_eq!(
2823                    body_json(response).await,
2824                    json!({"error":"InternalServerError", "message":"public repository read failed"})
2825                );
2826            }
2827            assert!(store.snapshot(hosted_tests::DID).unwrap().is_none());
2828        }
2829    }
2830
2831    #[tokio::test]
2832    async fn hosted_router_writes_reads_retries_and_fails_closed() {
2833        use crate::services::public_repo::{hosted_tests, PublicRepoStore};
2834        if hyprstream_rpc::auth::global_credential_revocation_store().is_none() {
2835            let _ = hyprstream_rpc::auth::set_global_credential_revocation_store(Arc::new(
2836                hyprstream_rpc::auth::InMemoryCredentialRevocationStore::new(),
2837            ));
2838        }
2839        let (accounts, native_reads) =
2840            hosted_tests::authority_fixture_with(hosted_tests::GenesisFixture::Legacy).await;
2841        let dir = tempfile::tempdir().unwrap();
2842        let store = Arc::new(PublicRepoStore::open(dir.path()).unwrap());
2843        let mut state = build_test_state(true).await;
2844        let signing_key = ed25519_dalek::SigningKey::from_bytes(&[0x19; 32]);
2845        let writable = Arc::get_mut(&mut state).unwrap();
2846        writable.verifying_key_bytes = signing_key.verifying_key().to_bytes();
2847        writable.hosted_account_zone =
2848            Some(crate::account::AccountZone::new("accounts.example.com").unwrap());
2849        writable.hosted_public_repo_writer = Some(Arc::new(hosted_tests::hosted(
2850            store.clone(),
2851            accounts.clone(),
2852        )));
2853        // Installing hosted support must not steal the exact local DID's writes.
2854        let local_did = "did:web:local.example.com";
2855        let local_gate = Arc::new(WriteInputGate::default());
2856        writable.public_repo_writer = Some(Arc::new(
2857            crate::services::public_repo::PublicRepoWriter::new(
2858                store.clone(),
2859                local_did,
2860                SigningKey::random(&mut OsRng),
2861                local_gate.clone(),
2862            )
2863            .unwrap(),
2864        ));
2865        let issuer = state.atproto_issuer_url();
2866        let now = chrono::Utc::now().timestamp();
2867        let key = SigningKey::random(&mut OsRng);
2868        let point = key.verifying_key().to_encoded_point(false);
2869        let jkt = super::super::dpop::DpopKey::Es256 {
2870            x: (*point.x().unwrap()).into(),
2871            y: (*point.y().unwrap()).into(),
2872        }
2873        .jkt();
2874        let nonce = state.issue_dpop_nonce().await;
2875        state.mark_dpop_client_nonced(&jkt).await;
2876        let claims =
2877            hyprstream_rpc::auth::Claims::new(hosted_tests::DID.to_owned(), now, now + 3600)
2878                .with_issuer(issuer.clone())
2879                .with_audience(Some(issuer.clone()))
2880                .with_tenant("tenant".to_owned())
2881                .with_client_id("hosted-tests")
2882                .with_scope(Some("atproto".to_owned()))
2883                .with_cnf_jkt_thumbprint(jkt)
2884                .with_jti();
2885        let token = WriteAccess {
2886            token: hyprstream_rpc::auth::jwt::encode(&claims, &signing_key),
2887            claims,
2888            key,
2889            htu: format!("{issuer}/xrpc/com.atproto.repo.createRecord"),
2890            nonce,
2891        };
2892        let snapshots = state.xrpc_repos.clone();
2893        let app = build_production_app_from_state(state).await;
2894        let mut input = write_input(1);
2895        input["repo"] = json!("did:web:bob.accounts.example.com");
2896        let response = app
2897            .clone()
2898            .oneshot(write_http_request(&token, &input, HeaderMap::new()))
2899            .await
2900            .unwrap();
2901        assert_eq!(response.status(), StatusCode::FORBIDDEN);
2902        assert_eq!(native_reads.0.load(std::sync::atomic::Ordering::SeqCst), 0);
2903        assert!(store
2904            .snapshot("did:web:bob.accounts.example.com")
2905            .unwrap()
2906            .is_none());
2907        // Foreign targets are rejected without calling either native writer.
2908        input["repo"] = json!("did:web:foreign.example.com");
2909        assert_eq!(
2910            app.clone()
2911                .oneshot(write_http_request(&token, &input, HeaderMap::new()))
2912                .await
2913                .unwrap()
2914                .status(),
2915            StatusCode::FORBIDDEN
2916        );
2917        assert_eq!(native_reads.0.load(std::sync::atomic::Ordering::SeqCst), 0);
2918        assert_eq!(local_gate.0.load(std::sync::atomic::Ordering::SeqCst), 0);
2919        let local_calls_before = local_gate.0.load(std::sync::atomic::Ordering::SeqCst);
2920        let mut local_token = token.clone();
2921        local_token.claims.sub = local_did.to_owned();
2922        local_token.token = hyprstream_rpc::auth::jwt::encode(&local_token.claims, &signing_key);
2923        input["repo"] = json!(local_did);
2924        let local_response = app
2925            .clone()
2926            .oneshot(write_http_request(&local_token, &input, HeaderMap::new()))
2927            .await
2928            .unwrap();
2929        assert_eq!(local_response.status(), StatusCode::OK);
2930        assert!(local_gate.0.load(std::sync::atomic::Ordering::SeqCst) > local_calls_before);
2931        assert_eq!(native_reads.0.load(std::sync::atomic::Ordering::SeqCst), 0);
2932        assert_eq!(store.snapshot(local_did).unwrap().unwrap().records.len(), 1);
2933        *local_gate.1.lock() = Some("private local denial".into());
2934        input["rkey"] = json!(Tid::from_raw(2).encode());
2935        let denied_local = app
2936            .clone()
2937            .oneshot(write_http_request(&local_token, &input, HeaderMap::new()))
2938            .await
2939            .unwrap();
2940        assert_eq!(denied_local.status(), StatusCode::FORBIDDEN);
2941        assert!(!body_json(denied_local)
2942            .await
2943            .to_string()
2944            .contains("private local denial"));
2945        assert_eq!(native_reads.0.load(std::sync::atomic::Ordering::SeqCst), 0);
2946        *local_gate.1.lock() = None;
2947        input["rkey"] = json!(Tid::from_raw(1).encode());
2948        let local_calls = local_gate.0.load(std::sync::atomic::Ordering::SeqCst);
2949        // The authority has published a real empty repo even before any record.
2950        let description = app
2951            .clone()
2952            .oneshot(read_request(&format!(
2953                "/xrpc/com.atproto.repo.describeRepo?repo={}",
2954                hosted_tests::DID,
2955            )))
2956            .await
2957            .unwrap();
2958        assert_eq!(description.status(), StatusCode::OK);
2959        let description = body_json(description).await;
2960        assert_eq!(description["did"], hosted_tests::DID);
2961        assert_eq!(description["collections"], json!([]));
2962        let genesis = store.snapshot(hosted_tests::DID).unwrap().unwrap().commit;
2963        let export = app
2964            .clone()
2965            .oneshot(read_request(&format!(
2966                "/xrpc/com.atproto.sync.getRepo?did={}",
2967                hosted_tests::DID,
2968            )))
2969            .await
2970            .unwrap();
2971        assert_eq!(export.status(), StatusCode::OK);
2972        assert!(!axum::body::to_bytes(export.into_body(), 2 * 1024 * 1024)
2973            .await
2974            .unwrap()
2975            .is_empty());
2976        assert_eq!(native_reads.1.load(std::sync::atomic::Ordering::SeqCst), 1);
2977        assert_eq!(
2978            local_gate.0.load(std::sync::atomic::Ordering::SeqCst),
2979            local_calls
2980        );
2981        input["swapCommit"] = json!(genesis.cid_atproto().unwrap().to_string());
2982        input["repo"] = json!("alice.accounts.example.com");
2983        let mut headers = HeaderMap::new();
2984        headers.insert("Idempotency-Key", "first".parse().unwrap());
2985        let first = app
2986            .clone()
2987            .oneshot(write_http_request(&token, &input, headers.clone()))
2988            .await
2989            .unwrap();
2990        assert_eq!(first.status(), StatusCode::OK);
2991        let first = body_json(first).await;
2992        let retry = app
2993            .clone()
2994            .oneshot(write_http_request(&token, &input, headers))
2995            .await
2996            .unwrap();
2997        assert_eq!(retry.status(), StatusCode::OK);
2998        assert_eq!(body_json(retry).await, first);
2999        input.as_object_mut().unwrap().remove("swapCommit");
3000        input["rkey"] = json!(Tid::from_raw(2).encode());
3001        assert_eq!(
3002            app.clone()
3003                .oneshot(write_http_request(&token, &input, HeaderMap::new()))
3004                .await
3005                .unwrap()
3006                .status(),
3007            StatusCode::OK
3008        );
3009        for repo in [hosted_tests::DID, "alice.accounts.example.com"] {
3010            let uri = format!(
3011                "/xrpc/com.atproto.repo.getRecord?repo={repo}&collection=app.bsky.feed.post&rkey={}",
3012                Tid::from_raw(1).encode()
3013            );
3014            let response = app
3015                .clone()
3016                .oneshot(
3017                    HttpRequest::builder()
3018                        .uri(&uri)
3019                        .body(Body::empty())
3020                        .unwrap(),
3021                )
3022                .await
3023                .unwrap();
3024            assert_eq!(response.status(), StatusCode::OK);
3025            assert_eq!(body_json(response).await["cid"], first["cid"]);
3026        }
3027        // Healthy durable data must retain native identity even when a legacy
3028        // model snapshot advertises a different handle and verification key.
3029        snapshots
3030            .put(sample_snapshot(
3031                hosted_tests::DID,
3032                "other.example.com",
3033                true,
3034            ))
3035            .await
3036            .unwrap();
3037        let resolved = app
3038            .clone()
3039            .oneshot(
3040                HttpRequest::builder()
3041                    .uri("/xrpc/com.atproto.identity.resolveHandle?handle=alice.accounts.example.com")
3042                    .body(Body::empty())
3043                    .unwrap(),
3044            )
3045            .await
3046            .unwrap();
3047        assert_eq!(resolved.status(), StatusCode::OK);
3048        assert_eq!(body_json(resolved).await["did"], hosted_tests::DID);
3049        let description = app
3050            .clone()
3051            .oneshot(
3052                HttpRequest::builder()
3053                    .uri(format!(
3054                        "/xrpc/com.atproto.repo.describeRepo?repo={}",
3055                        hosted_tests::DID
3056                    ))
3057                    .body(Body::empty())
3058                    .unwrap(),
3059            )
3060            .await
3061            .unwrap();
3062        assert_eq!(description.status(), StatusCode::OK);
3063        let description = body_json(description).await;
3064        assert_eq!(description["handle"], "alice.accounts.example.com");
3065        assert_eq!(description["did"], hosted_tests::DID);
3066        assert_eq!(description["handleIsCorrect"], true);
3067        assert_eq!(description["didDoc"]["id"], hosted_tests::DID);
3068        assert_eq!(
3069            description["didDoc"]["alsoKnownAs"],
3070            json!(["at://alice.accounts.example.com"])
3071        );
3072        let native_key = accounts
3073            .verifying_key_for_hosted_did(
3074                &hyprstream_rpc::Subject::new(
3075                    hyprstream_pds_service::OAUTH_ACCOUNT_RESOLVER_SUBJECT,
3076                ),
3077                hosted_tests::DID,
3078            )
3079            .await
3080            .unwrap()
3081            .unwrap();
3082        let native_method =
3083            super::super::did_document::atproto_verification_method(hosted_tests::DID, &native_key);
3084        assert!(description["didDoc"]["verificationMethod"]
3085            .as_array()
3086            .unwrap()
3087            .contains(&native_method));
3088        let alias_description = app
3089            .clone()
3090            .oneshot(read_request(
3091                "/xrpc/com.atproto.repo.describeRepo?repo=other.example.com",
3092            ))
3093            .await
3094            .unwrap();
3095        assert_eq!(alias_description.status(), StatusCode::OK);
3096        assert_eq!(body_json(alias_description).await, description);
3097        let alias_record = app.clone().oneshot(read_request(&format!(
3098                "/xrpc/com.atproto.repo.getRecord?repo=other.example.com&collection=app.bsky.feed.post&rkey={}",
3099                Tid::from_raw(1).encode(),
3100            ))).await.unwrap();
3101        assert_eq!(alias_record.status(), StatusCode::OK);
3102        assert_eq!(body_json(alias_record).await["cid"], first["cid"]);
3103        let export = app
3104            .clone()
3105            .oneshot(
3106                HttpRequest::builder()
3107                    .uri(format!(
3108                        "/xrpc/com.atproto.sync.getRepo?did={}",
3109                        hosted_tests::DID
3110                    ))
3111                    .body(Body::empty())
3112                    .unwrap(),
3113            )
3114            .await
3115            .unwrap();
3116        assert_eq!(export.status(), StatusCode::OK);
3117        assert!(!axum::body::to_bytes(export.into_body(), 2 * 1024 * 1024)
3118            .await
3119            .unwrap()
3120            .is_empty());
3121        store
3122            .insert_snapshot_budget_fixture_for_test(hosted_tests::DID, 257, 1)
3123            .unwrap();
3124        for uri in [hosted_tests::DID, "alice.accounts.example.com", "other.example.com"]
3125                .into_iter().flat_map(|repo| [
3126                    format!("/xrpc/com.atproto.repo.describeRepo?repo={repo}"),
3127                    format!("/xrpc/com.atproto.repo.getRecord?repo={repo}&collection=app.bsky.feed.post&rkey={}", Tid::from_raw(1).encode()),
3128                    format!("/xrpc/com.atproto.sync.getRepo?did={repo}"),
3129                ]) {
3130
3131                assert_eq!(
3132                    app.clone()
3133                        .oneshot(HttpRequest::builder().uri(uri).body(Body::empty()).unwrap())
3134                        .await
3135                        .unwrap()
3136                        .status(),
3137                    StatusCode::INTERNAL_SERVER_ERROR
3138                );
3139            }
3140    }
3141
3142    fn write_input(id: u64) -> Value {
3143        json!({
3144            "repo": "did:web:pub.example.com",
3145            "collection": "app.bsky.feed.post",
3146            "rkey": Tid::from_raw(id).encode(),
3147            "record": {
3148                "$type": "app.bsky.feed.post",
3149                "text": "input validation",
3150                "createdAt": "2026-09-10T00:00:00Z"
3151            }
3152        })
3153    }
3154
3155    fn write_http_request(
3156        token: &WriteAccess,
3157        input: &Value,
3158        headers: HeaderMap,
3159    ) -> HttpRequest<Body> {
3160        let mut request = HttpRequest::builder()
3161            .method("POST")
3162            .uri("/xrpc/com.atproto.repo.createRecord")
3163            .header(header::AUTHORIZATION, format!("DPoP {}", token.token))
3164            .header("DPoP", sign_write_proof(&token.key, &token.proof_payload()))
3165            .header(header::CONTENT_TYPE, "application/json")
3166            .body(Body::from(serde_json::to_vec(input).unwrap()))
3167            .unwrap();
3168        request.headers_mut().extend(headers);
3169        request
3170    }
3171
3172    #[tokio::test]
3173    async fn router_create_record_requires_bound_token_and_proof_before_native_calls() {
3174        let (_dir, store, gate, app, access) = build_write_input_fixture().await;
3175        let mut unbound = access.clone();
3176        unbound.claims.cnf = None;
3177        unbound.token = hyprstream_rpc::auth::jwt::encode(
3178            &unbound.claims,
3179            &ed25519_dalek::SigningKey::from_bytes(&[0x19; 32]),
3180        );
3181        for (token, scheme, include_proof, error) in [
3182            (&unbound, "Bearer", false, errors::INVALID_REQUEST),
3183            (&unbound, "DPoP", true, errors::INVALID_REQUEST),
3184            (&access, "Bearer", false, "invalid_token"),
3185            (&access, "Bearer", true, "invalid_token"),
3186            (&access, "DPoP", false, "invalid_token"),
3187        ] {
3188            let mut request = write_http_request(token, &write_input(7), HeaderMap::new());
3189            request.headers_mut().insert(
3190                header::AUTHORIZATION,
3191                format!("{scheme} {}", token.token).parse().unwrap(),
3192            );
3193            if !include_proof {
3194                request.headers_mut().remove("DPoP");
3195            }
3196            let response = app.clone().oneshot(request).await.unwrap();
3197            assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
3198            let body = body_json(response).await;
3199            assert_eq!(body["error"], error);
3200            if error == errors::INVALID_REQUEST {
3201                assert_eq!(
3202                    body["message"],
3203                    "a DPoP-bound OAuth access token is required"
3204                );
3205            }
3206            assert_eq!(gate.0.load(std::sync::atomic::Ordering::Relaxed), 0);
3207            assert!(store.snapshot("did:web:pub.example.com").unwrap().is_none());
3208        }
3209    }
3210
3211    #[tokio::test]
3212    async fn router_create_record_rejects_wrong_dpop_proofs_before_native_calls() {
3213        let (_dir, store, gate, app, access) = build_write_input_fixture().await;
3214        for case in [
3215            "key",
3216            "method",
3217            "uri",
3218            "ath",
3219            "missing_ath",
3220            "nonce",
3221            "missing_nonce",
3222        ] {
3223            let mut payload = access.proof_payload();
3224            let wrong_key = SigningKey::random(&mut OsRng);
3225            let key = if case == "key" {
3226                &wrong_key
3227            } else {
3228                &access.key
3229            };
3230            let error = match case {
3231                "key" => "invalid_token",
3232                "method" => {
3233                    payload["htm"] = json!("GET");
3234                    "invalid_dpop_proof"
3235                }
3236                "uri" => {
3237                    payload["htu"] =
3238                        json!("https://other.example/xrpc/com.atproto.repo.createRecord");
3239                    "invalid_dpop_proof"
3240                }
3241                "ath" => {
3242                    payload["ath"] = json!("wrong-token-hash");
3243                    "invalid_dpop_proof"
3244                }
3245                "missing_ath" => {
3246                    payload.as_object_mut().unwrap().remove("ath");
3247                    "invalid_dpop_proof"
3248                }
3249                "nonce" => {
3250                    payload["nonce"] = json!("invalid-server-nonce");
3251                    "use_dpop_nonce"
3252                }
3253                "missing_nonce" => {
3254                    payload.as_object_mut().unwrap().remove("nonce");
3255                    "use_dpop_nonce"
3256                }
3257                _ => unreachable!(),
3258            };
3259            let mut headers = HeaderMap::new();
3260            headers.insert("DPoP", sign_write_proof(key, &payload).parse().unwrap());
3261            let response = app
3262                .clone()
3263                .oneshot(write_http_request(&access, &write_input(7), headers))
3264                .await
3265                .unwrap();
3266            assert_eq!(response.status(), StatusCode::UNAUTHORIZED, "{case}");
3267            assert_eq!(body_json(response).await["error"], error, "{case}");
3268            assert_eq!(
3269                gate.0.load(std::sync::atomic::Ordering::Relaxed),
3270                0,
3271                "{case}"
3272            );
3273            assert!(
3274                store.snapshot("did:web:pub.example.com").unwrap().is_none(),
3275                "{case}"
3276            );
3277        }
3278    }
3279
3280    #[tokio::test]
3281    async fn router_create_record_dpop_replay_rejected_but_fresh_retry_succeeds() {
3282        let (_dir, store, gate, app, access) = build_write_input_fixture().await;
3283        let mut headers = HeaderMap::new();
3284        headers.insert(
3285            "DPoP",
3286            sign_write_proof(&access.key, &access.proof_payload())
3287                .parse()
3288                .unwrap(),
3289        );
3290        headers.insert("Idempotency-Key", "dpop-retry".parse().unwrap());
3291        let response = app
3292            .clone()
3293            .oneshot(write_http_request(
3294                &access,
3295                &write_input(7),
3296                headers.clone(),
3297            ))
3298            .await
3299            .unwrap();
3300        assert_eq!(response.status(), StatusCode::OK);
3301        let created = body_json(response).await;
3302        let head = store
3303            .snapshot("did:web:pub.example.com")
3304            .unwrap()
3305            .unwrap()
3306            .commit
3307            .cid();
3308        assert_eq!(gate.0.load(std::sync::atomic::Ordering::Relaxed), 1);
3309
3310        // Replay cannot reach the authorizer, even when the body/idempotency
3311        // request changes. A fresh proof can retry the original operation.
3312        for input in [write_input(7), write_input(8)] {
3313            let response = app
3314                .clone()
3315                .oneshot(write_http_request(&access, &input, headers.clone()))
3316                .await
3317                .unwrap();
3318            assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
3319            assert_eq!(body_json(response).await["error"], "invalid_dpop_proof");
3320            assert_eq!(gate.0.load(std::sync::atomic::Ordering::Relaxed), 1);
3321            let snapshot = store.snapshot("did:web:pub.example.com").unwrap().unwrap();
3322            assert_eq!(snapshot.commit.cid(), head);
3323            assert_eq!(snapshot.records.len(), 1);
3324        }
3325        headers.remove("DPoP");
3326        let response = app
3327            .oneshot(write_http_request(&access, &write_input(7), headers))
3328            .await
3329            .unwrap();
3330        assert_eq!(response.status(), StatusCode::OK);
3331        assert_eq!(body_json(response).await, created);
3332        assert_eq!(gate.0.load(std::sync::atomic::Ordering::Relaxed), 2);
3333        let snapshot = store.snapshot("did:web:pub.example.com").unwrap().unwrap();
3334        assert_eq!(snapshot.commit.cid(), head);
3335        assert_eq!(snapshot.records.len(), 1);
3336    }
3337
3338    fn read_request(uri: &str) -> HttpRequest<Body> {
3339        HttpRequest::builder().uri(uri).body(Body::empty()).unwrap()
3340    }
3341
3342    #[tokio::test]
3343    async fn router_durable_reads_enforce_aggregate_snapshot_budget() {
3344        for (count, bytes) in [(257, 1), (18, 60_000)] {
3345            let (_dir, store, _gate, app, _token) = build_write_input_fixture().await;
3346            store
3347                .insert_snapshot_budget_fixture_for_test("did:web:pub.example.com", count, bytes)
3348                .unwrap();
3349            for uri in [
3350                "/xrpc/com.atproto.repo.getRecord?repo=pub.example.com&collection=app.bsky.feed.post&rkey=0000",
3351                "/xrpc/com.atproto.repo.describeRepo?repo=pub.example.com",
3352                "/xrpc/com.atproto.sync.getRepo?did=did:web:pub.example.com",
3353            ] {
3354                let response = app.clone().oneshot(read_request(uri)).await.unwrap();
3355                assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
3356                assert_eq!(body_json(response).await, json!({"error":"InternalServerError","message":"public repository read failed"}));
3357            }
3358        }
3359    }
3360
3361    #[tokio::test]
3362    async fn router_point_reads_remain_available_with_four_held_car_bodies() {
3363        let (_dir, _store, _gate, app, token) = build_write_input_fixture().await;
3364        let created = app
3365            .clone()
3366            .oneshot(write_http_request(
3367                &token,
3368                &write_input(7),
3369                HeaderMap::new(),
3370            ))
3371            .await
3372            .unwrap();
3373        assert_eq!(created.status(), StatusCode::OK);
3374        let mut held = Vec::new();
3375        for _ in 0..GET_REPO_CONCURRENCY {
3376            held.push(
3377                app.clone()
3378                    .oneshot(read_request(
3379                        "/xrpc/com.atproto.sync.getRepo?did=did:web:pub.example.com",
3380                    ))
3381                    .await
3382                    .unwrap(),
3383            );
3384        }
3385        assert!(held
3386            .iter()
3387            .all(|response| response.status() == StatusCode::OK));
3388        // Waiting exports must acquire body admission before snapshot work.
3389        let mut queued_exports = Vec::new();
3390        for _ in 0..DURABLE_SNAPSHOT_CONCURRENCY {
3391            let app = app.clone();
3392            queued_exports.push(tokio::spawn(async move {
3393                app.oneshot(read_request(
3394                    "/xrpc/com.atproto.sync.getRepo?did=did:web:pub.example.com",
3395                ))
3396                .await
3397                .unwrap()
3398            }));
3399        }
3400        assert!(
3401            tokio::time::timeout(std::time::Duration::from_millis(50), &mut queued_exports[0])
3402                .await
3403                .is_err()
3404        );
3405        let mut pending = Vec::new();
3406        for uri in [
3407            format!("/xrpc/com.atproto.repo.getRecord?repo=pub.example.com&collection=app.bsky.feed.post&rkey={}", Tid::from_raw(7).encode()),
3408            "/xrpc/com.atproto.repo.describeRepo?repo=pub.example.com".to_owned(),
3409        ] {
3410            let app = app.clone();
3411            pending.push(tokio::spawn(async move { app.oneshot(read_request(&uri)).await.unwrap() }));
3412        }
3413        for request in pending {
3414            let response = tokio::time::timeout(std::time::Duration::from_secs(2), request)
3415                .await
3416                .unwrap()
3417                .unwrap();
3418            assert_eq!(response.status(), StatusCode::OK);
3419        }
3420        assert_eq!(held.len(), GET_REPO_CONCURRENCY);
3421        for export in queued_exports {
3422            export.abort();
3423        }
3424    }
3425
3426    #[tokio::test]
3427    async fn router_snapshot_work_admission_bounds_every_durable_reader() {
3428        let (_dir, _store, _gate, app, token, reads) = build_write_input_fixture_with_admission(
3429            "did:web:pub.example.com",
3430            "https://h.example.com",
3431        )
3432        .await;
3433        let created = app
3434            .clone()
3435            .oneshot(write_http_request(
3436                &token,
3437                &write_input(7),
3438                HeaderMap::new(),
3439            ))
3440            .await
3441            .unwrap();
3442        assert_eq!(created.status(), StatusCode::OK);
3443        let mut held = Vec::new();
3444        for _ in 0..DURABLE_SNAPSHOT_CONCURRENCY {
3445            held.push(reads.acquire_snapshot_work_owned().await.unwrap());
3446        }
3447        let mut pending = Vec::new();
3448        for uri in [
3449            format!("/xrpc/com.atproto.repo.getRecord?repo=pub.example.com&collection=app.bsky.feed.post&rkey={}", Tid::from_raw(7).encode()),
3450            "/xrpc/com.atproto.repo.describeRepo?repo=pub.example.com".to_owned(),
3451            "/xrpc/com.atproto.sync.getRepo?did=did:web:pub.example.com".to_owned(),
3452        ] {
3453            let app = app.clone();
3454            pending.push(tokio::spawn(async move { app.oneshot(read_request(&uri)).await.unwrap() }));
3455        }
3456        for request in &mut pending {
3457            assert!(
3458                tokio::time::timeout(std::time::Duration::from_millis(50), request)
3459                    .await
3460                    .is_err()
3461            );
3462        }
3463        drop(held.pop());
3464        let mut responses = Vec::new();
3465        for request in pending {
3466            let response = tokio::time::timeout(std::time::Duration::from_secs(2), request)
3467                .await
3468                .unwrap()
3469                .unwrap();
3470            assert_eq!(response.status(), StatusCode::OK);
3471            responses.push(response);
3472        }
3473        // CAR body retains only export admission, not snapshot-work admission.
3474        assert_eq!(reads.snapshot_work_sema.available_permits(), 1);
3475        assert_eq!(
3476            reads.get_repo_sema.available_permits(),
3477            GET_REPO_CONCURRENCY - 1
3478        );
3479        drop(responses);
3480        assert_eq!(
3481            reads.get_repo_sema.available_permits(),
3482            GET_REPO_CONCURRENCY
3483        );
3484    }
3485
3486    #[tokio::test]
3487    async fn router_describes_nonissuer_writers_without_legacy_handle_metadata() {
3488        for did in [
3489            "did:plc:abcdefghijklmnopqrstuvwx",
3490            "did:web:account.example.com",
3491        ] {
3492            let (_dir, _store, _gate, app, token) =
3493                build_write_input_fixture_for(did, "https://pds.example.com").await;
3494            let mut input = write_input(7);
3495            input["repo"] = json!(did);
3496            let created = app
3497                .clone()
3498                .oneshot(write_http_request(&token, &input, HeaderMap::new()))
3499                .await
3500                .unwrap();
3501            assert_eq!(created.status(), StatusCode::OK);
3502            let response = app
3503                .clone()
3504                .oneshot(read_request(&format!(
3505                    "/xrpc/com.atproto.repo.describeRepo?repo={did}"
3506                )))
3507                .await
3508                .unwrap();
3509            assert_eq!(response.status(), StatusCode::OK);
3510            let body = body_json(response).await;
3511            assert_eq!(body["did"], did);
3512            assert_eq!(body["didDoc"]["id"], did);
3513            assert_eq!(body["handle"], "handle.invalid");
3514            assert_eq!(body["handleIsCorrect"], false);
3515            assert!(body["didDoc"].get("alsoKnownAs").is_none());
3516            assert_eq!(body["collections"], json!(["app.bsky.feed.post"]));
3517            // The unknown account handle must not claim the PDS issuer handle.
3518            input["repo"] = json!("pds.example.com");
3519            let foreign = app
3520                .oneshot(write_http_request(&token, &input, HeaderMap::new()))
3521                .await
3522                .unwrap();
3523            assert_eq!(foreign.status(), StatusCode::FORBIDDEN);
3524        }
3525    }
3526
3527    #[tokio::test]
3528    async fn router_rejects_unverified_blobs_in_every_validation_mode_and_read_path() {
3529        let (_dir, store, gate, app, token) = build_write_input_fixture().await;
3530        let blob = json!({"$type":"blob","ref":{"$link":Cid::from_raw(b"missing").to_string()},"mimeType":"image/png","size":7});
3531        for mode in [None, Some(true), Some(false)] {
3532            for extension in [
3533                blob.clone(),
3534                json!([{"nested":[blob.clone()]}]),
3535                json!({"$type":"com.example.future","media":blob}),
3536                json!({"cid":Cid::from_raw(b"missing").to_string(),"mimeType":"image/png"}),
3537            ] {
3538                let mut input = write_input(7);
3539                input["record"]["extension"] = extension;
3540                if let Some(mode) = mode {
3541                    input["validate"] = json!(mode);
3542                }
3543                let response = app
3544                    .clone()
3545                    .oneshot(write_http_request(&token, &input, HeaderMap::new()))
3546                    .await
3547                    .unwrap();
3548                assert_eq!(response.status(), StatusCode::BAD_REQUEST);
3549                assert_eq!(
3550                    body_json(response).await,
3551                    json!({"error":"InvalidRequest","message":"blob storage verification is unavailable"})
3552                );
3553                assert!(store.snapshot("did:web:pub.example.com").unwrap().is_none());
3554                assert_eq!(gate.0.load(std::sync::atomic::Ordering::Relaxed), 0);
3555            }
3556        }
3557        // Model an otherwise correctly signed repository from before blob enforcement.
3558        store
3559            .insert_unverified_blob_for_test("did:web:pub.example.com")
3560            .unwrap();
3561        assert!(store
3562            .snapshot("did:web:pub.example.com")
3563            .unwrap_err()
3564            .to_string()
3565            .contains("blob storage verification"));
3566        for uri in [
3567            "/xrpc/com.atproto.repo.getRecord?repo=pub.example.com&collection=app.bsky.feed.post&rkey=legacy",
3568            "/xrpc/com.atproto.repo.describeRepo?repo=pub.example.com",
3569            "/xrpc/com.atproto.sync.getRepo?did=did:web:pub.example.com",
3570        ] {
3571            let response = app.clone().oneshot(read_request(uri)).await.unwrap();
3572            assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
3573            assert_eq!(body_json(response).await, json!({"error":"InternalServerError","message":"public repository read failed"}));
3574        }
3575    }
3576
3577    #[tokio::test]
3578    async fn router_retry_rejects_substituted_swap_without_rechecking_latest_head() {
3579        let (_dir, store, _gate, app, token) = build_write_input_fixture().await;
3580        let first = app
3581            .clone()
3582            .oneshot(write_http_request(
3583                &token,
3584                &write_input(7),
3585                HeaderMap::new(),
3586            ))
3587            .await
3588            .unwrap();
3589        assert_eq!(first.status(), StatusCode::OK);
3590        let previous = store
3591            .snapshot("did:web:pub.example.com")
3592            .unwrap()
3593            .unwrap()
3594            .commit
3595            .cid_atproto()
3596            .unwrap()
3597            .to_string();
3598        let mut input = write_input(8);
3599        input["swapCommit"] = json!(previous);
3600        let second = app
3601            .clone()
3602            .oneshot(write_http_request(&token, &input, HeaderMap::new()))
3603            .await
3604            .unwrap();
3605        assert_eq!(second.status(), StatusCode::OK);
3606        let second = body_json(second).await;
3607        let third = app
3608            .clone()
3609            .oneshot(write_http_request(
3610                &token,
3611                &write_input(9),
3612                HeaderMap::new(),
3613            ))
3614            .await
3615            .unwrap();
3616        assert_eq!(third.status(), StatusCode::OK);
3617        let head = store
3618            .snapshot("did:web:pub.example.com")
3619            .unwrap()
3620            .unwrap()
3621            .commit
3622            .cid_atproto()
3623            .unwrap();
3624        let retry = app
3625            .clone()
3626            .oneshot(write_http_request(&token, &input, HeaderMap::new()))
3627            .await
3628            .unwrap();
3629        assert_eq!(retry.status(), StatusCode::OK);
3630        assert_eq!(body_json(retry).await, second);
3631        for changed in [
3632            Some(head.to_string()),
3633            Some(Cid::from_dag_cbor(b"substituted").to_string()),
3634            None,
3635        ] {
3636            let mut input = input.clone();
3637            match changed {
3638                Some(cid) => {
3639                    input["swapCommit"] = json!(cid);
3640                }
3641                None => {
3642                    input.as_object_mut().unwrap().remove("swapCommit");
3643                }
3644            }
3645            let response = app
3646                .clone()
3647                .oneshot(write_http_request(&token, &input, HeaderMap::new()))
3648                .await
3649                .unwrap();
3650            assert_eq!(response.status(), StatusCode::BAD_REQUEST);
3651            assert_eq!(
3652                body_json(response).await,
3653                json!({"error":"InvalidRequest","message":"record or request parameters are invalid"})
3654            );
3655            assert_eq!(
3656                store
3657                    .snapshot("did:web:pub.example.com")
3658                    .unwrap()
3659                    .unwrap()
3660                    .commit
3661                    .cid_atproto()
3662                    .unwrap(),
3663                head
3664            );
3665        }
3666    }
3667
3668    #[tokio::test]
3669    async fn router_issuer_port_handle_uses_canonical_did_without_registry_entry() {
3670        let did = "did:web:pds.example.test%3A8443";
3671        let (_dir, store, gate, app, token) =
3672            build_write_input_fixture_for(did, "https://pds.example.test:8443").await;
3673        let resolve = app
3674            .clone()
3675            .oneshot(read_request(
3676                "/xrpc/com.atproto.identity.resolveHandle?handle=pds.example.test",
3677            ))
3678            .await
3679            .unwrap();
3680        assert_eq!(resolve.status(), StatusCode::OK);
3681        assert_eq!(body_json(resolve).await, json!({"did":did}));
3682        let mut input = write_input(7);
3683        input["repo"] = json!("pds.example.test");
3684        let created = app
3685            .clone()
3686            .oneshot(write_http_request(&token, &input, HeaderMap::new()))
3687            .await
3688            .unwrap();
3689        assert_eq!(created.status(), StatusCode::OK);
3690        let created = body_json(created).await;
3691        input["repo"] = json!(did);
3692        let retry = app
3693            .clone()
3694            .oneshot(write_http_request(&token, &input, HeaderMap::new()))
3695            .await
3696            .unwrap();
3697        assert_eq!(retry.status(), StatusCode::OK);
3698        assert_eq!(body_json(retry).await, created);
3699        for repo in [
3700            "pds.example.test".to_owned(),
3701            urlencoding::encode(did).into_owned(),
3702        ] {
3703            let read = app.clone().oneshot(read_request(&format!("/xrpc/com.atproto.repo.getRecord?repo={repo}&collection=app.bsky.feed.post&rkey={}", input["rkey"].as_str().unwrap()))).await.unwrap();
3704            assert_eq!(read.status(), StatusCode::OK);
3705            assert_eq!(body_json(read).await["uri"], created["uri"]);
3706            let describe = app
3707                .clone()
3708                .oneshot(read_request(&format!(
3709                    "/xrpc/com.atproto.repo.describeRepo?repo={repo}"
3710                )))
3711                .await
3712                .unwrap();
3713            assert_eq!(describe.status(), StatusCode::OK);
3714            let describe = body_json(describe).await;
3715            assert_eq!(describe["did"], did);
3716            assert_eq!(describe["handle"], "pds.example.test");
3717            assert_eq!(describe["didDoc"]["id"], did);
3718        }
3719        assert_eq!(store.snapshot(did).unwrap().unwrap().records.len(), 1);
3720        assert_eq!(gate.0.load(std::sync::atomic::Ordering::Relaxed), 2);
3721    }
3722
3723    #[tokio::test(flavor = "current_thread")]
3724    async fn router_writes_release_tokio_worker_and_serialize_same_did() {
3725        let (_dir, store, gate, app, token) = build_write_input_fixture().await;
3726        let response = app
3727            .clone()
3728            .oneshot(write_http_request(
3729                &token,
3730                &write_input(7),
3731                HeaderMap::new(),
3732            ))
3733            .await
3734            .unwrap();
3735        assert_eq!(response.status(), StatusCode::OK);
3736        let head = store
3737            .snapshot("did:web:pub.example.com")
3738            .unwrap()
3739            .unwrap()
3740            .commit
3741            .cid_atproto()
3742            .unwrap()
3743            .to_string();
3744        let (held_tx, held_rx) = std::sync::mpsc::channel();
3745        let (release_tx, release_rx) = std::sync::mpsc::channel();
3746        let locked_store = store.clone();
3747        let owner = std::thread::spawn(move || {
3748            locked_store
3749                .with_account_lock_for_test("did:web:pub.example.com", || {
3750                    held_tx.send(()).unwrap();
3751                    let _ = release_rx.recv_timeout(std::time::Duration::from_secs(5));
3752                })
3753                .unwrap();
3754        });
3755        held_rx
3756            .recv_timeout(std::time::Duration::from_secs(2))
3757            .unwrap();
3758        let started = std::time::Instant::now();
3759        let mut writes = Vec::new();
3760        for id in [8, 9] {
3761            let mut input = write_input(id);
3762            input["swapCommit"] = json!(head);
3763            let request = write_http_request(&token, &input, HeaderMap::new());
3764            let app = app.clone();
3765            writes.push(tokio::spawn(
3766                async move { app.oneshot(request).await.unwrap() },
3767            ));
3768        }
3769        tokio::time::timeout(std::time::Duration::from_secs(2), async {
3770            while gate.0.load(std::sync::atomic::Ordering::Relaxed) < 3 {
3771                tokio::task::yield_now().await;
3772            }
3773        })
3774        .await
3775        .unwrap();
3776        let response = app
3777            .oneshot(read_request(
3778                "/xrpc/com.atproto.identity.resolveHandle?handle=pub.example.com",
3779            ))
3780            .await
3781            .unwrap();
3782        assert_eq!(response.status(), StatusCode::OK);
3783        assert!(started.elapsed() < std::time::Duration::from_secs(2));
3784        assert!(writes.iter().all(|write| !write.is_finished()));
3785        release_tx.send(()).unwrap();
3786        owner.join().unwrap();
3787        let mut statuses = Vec::new();
3788        for write in writes {
3789            statuses.push(write.await.unwrap().status().as_u16());
3790        }
3791        statuses.sort();
3792        assert_eq!(statuses, vec![200, 409]);
3793        assert_eq!(
3794            store
3795                .snapshot("did:web:pub.example.com")
3796                .unwrap()
3797                .unwrap()
3798                .records
3799                .len(),
3800            2
3801        );
3802    }
3803
3804    #[tokio::test]
3805    async fn router_create_accepts_owned_handle_and_rejects_foreign_handles() {
3806        let (_dir, store, gate, app, token) = build_write_input_fixture().await;
3807        for repo in [
3808            "priv.example.com",
3809            "h.example.com",
3810            "unknown.example.com",
3811            "did:web:priv.example.com",
3812        ] {
3813            let mut input = write_input(7);
3814            input["repo"] = json!(repo);
3815            let response = app
3816                .clone()
3817                .oneshot(write_http_request(&token, &input, HeaderMap::new()))
3818                .await
3819                .unwrap();
3820            assert_eq!(response.status(), StatusCode::FORBIDDEN, "{repo}");
3821            assert!(store.snapshot("did:web:pub.example.com").unwrap().is_none());
3822            assert_eq!(gate.0.load(std::sync::atomic::Ordering::Relaxed), 0);
3823        }
3824        let mut input = write_input(7);
3825        input["repo"] = json!("PUB.EXAMPLE.COM");
3826        let mut headers = HeaderMap::new();
3827        headers.insert("Idempotency-Key", "owned-handle-retry".parse().unwrap());
3828        let response = app
3829            .clone()
3830            .oneshot(write_http_request(&token, &input, headers.clone()))
3831            .await
3832            .unwrap();
3833        assert_eq!(response.status(), StatusCode::OK);
3834        let created = body_json(response).await;
3835        assert!(created["uri"]
3836            .as_str()
3837            .unwrap()
3838            .starts_with("at://did:web:pub.example.com/"));
3839        let retry = app
3840            .oneshot(write_http_request(&token, &write_input(7), headers))
3841            .await
3842            .unwrap();
3843        assert_eq!(retry.status(), StatusCode::OK);
3844        assert_eq!(body_json(retry).await, created);
3845        assert_eq!(gate.0.load(std::sync::atomic::Ordering::Relaxed), 2);
3846        assert_eq!(
3847            store
3848                .snapshot("did:web:pub.example.com")
3849                .unwrap()
3850                .unwrap()
3851                .records
3852                .len(),
3853            1
3854        );
3855    }
3856
3857    #[tokio::test]
3858    async fn router_durable_creates_are_readable_without_stale_snapshot_fallback() {
3859        let (_dir, store, _gate, app, token) = build_write_input_fixture().await;
3860        let repo_uri = "/xrpc/com.atproto.sync.getRepo?did=did:web:pub.example.com";
3861        // The fixture already contains a legacy model snapshot for this DID.
3862        let missing = app.clone().oneshot(read_request(repo_uri)).await.unwrap();
3863        assert_eq!(missing.status(), StatusCode::BAD_REQUEST);
3864        assert_eq!(body_json(missing).await["error"], "RepoNotFound");
3865        let mut input = write_input(7);
3866        input["record"]["extension"] = json!({"bytes":{"$bytes":"AQI="},"link":{"$link":Cid::from_dag_cbor(b"extension").to_string()}});
3867        let created = app
3868            .clone()
3869            .oneshot(write_http_request(&token, &input, HeaderMap::new()))
3870            .await
3871            .unwrap();
3872        assert_eq!(created.status(), StatusCode::OK);
3873        let created = body_json(created).await;
3874        for repo in ["did:web:pub.example.com", "pub.example.com"] {
3875            let uri = format!("/xrpc/com.atproto.repo.getRecord?repo={repo}&collection=app.bsky.feed.post&rkey={}", input["rkey"].as_str().unwrap());
3876            let read = app.clone().oneshot(read_request(&uri)).await.unwrap();
3877            assert_eq!(read.status(), StatusCode::OK);
3878            let read = body_json(read).await;
3879            assert_eq!(read["uri"], created["uri"]);
3880            assert_eq!(read["cid"], created["cid"]);
3881            assert_eq!(read["value"], input["record"]);
3882        }
3883        let profile = json!({"repo":"pub.example.com","collection":"app.bsky.actor.profile","rkey":"self","record":{"$type":"app.bsky.actor.profile","displayName":"Durable"}});
3884        let response = app
3885            .clone()
3886            .oneshot(write_http_request(&token, &profile, HeaderMap::new()))
3887            .await
3888            .unwrap();
3889        assert_eq!(response.status(), StatusCode::OK);
3890        let profile_read = app.clone().oneshot(read_request("/xrpc/com.atproto.repo.getRecord?repo=pub.example.com&collection=app.bsky.actor.profile&rkey=self")).await.unwrap();
3891        assert_eq!(profile_read.status(), StatusCode::OK);
3892        assert_eq!(body_json(profile_read).await["value"], profile["record"]);
3893        let describe_uri = "/xrpc/com.atproto.repo.describeRepo?repo=pub.example.com";
3894        let describe = app
3895            .clone()
3896            .oneshot(read_request(describe_uri))
3897            .await
3898            .unwrap();
3899        assert_eq!(describe.status(), StatusCode::OK);
3900        assert_eq!(
3901            body_json(describe).await["collections"],
3902            json!(["app.bsky.actor.profile", "app.bsky.feed.post"])
3903        );
3904        let exported = app.clone().oneshot(read_request(repo_uri)).await.unwrap();
3905        assert_eq!(exported.status(), StatusCode::OK);
3906        let bytes = axum::body::to_bytes(exported.into_body(), 1024 * 1024)
3907            .await
3908            .unwrap();
3909        let (roots, blocks) = hyprstream_pds::car::parse_car_v1_atproto(&bytes).unwrap();
3910        let snapshot = store.snapshot("did:web:pub.example.com").unwrap().unwrap();
3911        assert_eq!(roots, vec![snapshot.commit.cid_atproto().unwrap()]);
3912        for (cid, bytes) in &blocks {
3913            assert_eq!(*cid, Cid::from_dag_cbor(bytes));
3914        }
3915        for record in snapshot.records.values() {
3916            assert!(blocks
3917                .iter()
3918                .any(|(cid, bytes)| *cid == record.cid() && bytes == record.bytes()));
3919        }
3920        store
3921            .insert_malformed_record_for_test(
3922                "did:web:pub.example.com",
3923                "app.bsky.feed.post",
3924                "private-storage-context",
3925            )
3926            .unwrap();
3927        for uri in [repo_uri, describe_uri, "/xrpc/com.atproto.repo.getRecord?repo=pub.example.com&collection=app.bsky.actor.profile&rkey=self"] {
3928            let response = app.clone().oneshot(read_request(uri)).await.unwrap();
3929            assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
3930            assert_eq!(body_json(response).await, json!({"error":"InternalServerError","message":"public repository read failed"}));
3931        }
3932    }
3933
3934    #[tokio::test]
3935    async fn router_durable_export_holds_permit_until_body_drop() {
3936        let (_dir, _store, _gate, app, token) = build_write_input_fixture().await;
3937        let created = app
3938            .clone()
3939            .oneshot(write_http_request(
3940                &token,
3941                &write_input(7),
3942                HeaderMap::new(),
3943            ))
3944            .await
3945            .unwrap();
3946        assert_eq!(created.status(), StatusCode::OK);
3947        let uri = "/xrpc/com.atproto.sync.getRepo?did=did:web:pub.example.com";
3948        let mut responses = Vec::new();
3949        for _ in 0..GET_REPO_CONCURRENCY {
3950            let response = app.clone().oneshot(read_request(uri)).await.unwrap();
3951            assert_eq!(response.status(), StatusCode::OK);
3952            responses.push(response);
3953        }
3954        let mut pending =
3955            tokio::spawn(async move { app.oneshot(read_request(uri)).await.unwrap() });
3956        assert!(
3957            tokio::time::timeout(std::time::Duration::from_millis(50), &mut pending)
3958                .await
3959                .is_err()
3960        );
3961        drop(responses.pop());
3962        let response = tokio::time::timeout(std::time::Duration::from_secs(2), pending)
3963            .await
3964            .unwrap()
3965            .unwrap();
3966        assert_eq!(response.status(), StatusCode::OK);
3967    }
3968
3969    #[tokio::test]
3970    async fn router_create_record_maps_input_and_conflicts_without_mutation() {
3971        let (_dir, store, _gate, app, token) = build_write_input_fixture().await;
3972        let mut invalid = write_input(7);
3973        invalid["record"]["$type"] = json!("private.authorization.denied");
3974        invalid["validate"] = json!(false); // Exercise the writer's typed input failure.
3975        let response = app
3976            .clone()
3977            .oneshot(write_http_request(&token, &invalid, HeaderMap::new()))
3978            .await
3979            .unwrap();
3980        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
3981        assert_eq!(
3982            body_json(response).await,
3983            json!({
3984                "error": "InvalidRequest", "message": "record or request parameters are invalid"
3985            })
3986        );
3987        assert!(store.snapshot("did:web:pub.example.com").unwrap().is_none());
3988
3989        let response = app
3990            .clone()
3991            .oneshot(write_http_request(
3992                &token,
3993                &write_input(7),
3994                HeaderMap::new(),
3995            ))
3996            .await
3997            .unwrap();
3998        assert_eq!(response.status(), StatusCode::OK);
3999        let original = body_json(response).await;
4000        let head = store
4001            .snapshot("did:web:pub.example.com")
4002            .unwrap()
4003            .unwrap()
4004            .commit
4005            .cid_atproto()
4006            .unwrap();
4007        let mut headers = HeaderMap::new();
4008        headers.insert("Idempotency-Key", "another-request".parse().unwrap());
4009        let response = app
4010            .clone()
4011            .oneshot(write_http_request(&token, &write_input(7), headers))
4012            .await
4013            .unwrap();
4014        assert_eq!(response.status(), StatusCode::CONFLICT);
4015        assert_eq!(
4016            body_json(response).await,
4017            json!({
4018                "error": "RecordAlreadyExists", "message": "record key already exists"
4019            })
4020        );
4021        let mut stale = write_input(8);
4022        stale["swapCommit"] = json!(hyprstream_pds::Cid::from_dag_cbor(b"stale").to_string());
4023        let response = app
4024            .clone()
4025            .oneshot(write_http_request(&token, &stale, HeaderMap::new()))
4026            .await
4027            .unwrap();
4028        assert_eq!(response.status(), StatusCode::CONFLICT);
4029        assert_eq!(
4030            body_json(response).await,
4031            json!({
4032                "error": "InvalidSwap", "message": "swapCommit does not match the repository head"
4033            })
4034        );
4035        let snapshot = store.snapshot("did:web:pub.example.com").unwrap().unwrap();
4036        assert_eq!(snapshot.commit.cid_atproto().unwrap(), head);
4037        assert_eq!(snapshot.records.len(), 1);
4038        let response = app
4039            .oneshot(write_http_request(
4040                &token,
4041                &write_input(7),
4042                HeaderMap::new(),
4043            ))
4044            .await
4045            .unwrap();
4046        assert_eq!(response.status(), StatusCode::OK);
4047        assert_eq!(body_json(response).await, original);
4048    }
4049
4050    #[tokio::test]
4051    async fn router_create_record_authorization_errors_ignore_source_text() {
4052        let (_dir, store, gate, app, token) = build_write_input_fixture().await;
4053        // Deliberately use words that formerly selected conflict or input status.
4054        for detail in [
4055            "private credential: CAS conflict",
4056            "private credential: already exists",
4057            "private credential",
4058        ] {
4059            *gate.1.lock() = Some(detail.to_owned());
4060            let response = app
4061                .clone()
4062                .oneshot(write_http_request(
4063                    &token,
4064                    &write_input(7),
4065                    HeaderMap::new(),
4066                ))
4067                .await
4068                .unwrap();
4069            assert_eq!(response.status(), StatusCode::FORBIDDEN);
4070            assert_eq!(
4071                body_json(response).await,
4072                json!({
4073                    "error": "AuthRequired", "message": "public repository publication is not authorized"
4074                })
4075            );
4076            assert!(store.snapshot("did:web:pub.example.com").unwrap().is_none());
4077        }
4078        assert_eq!(gate.0.load(std::sync::atomic::Ordering::Relaxed), 3);
4079    }
4080
4081    #[tokio::test]
4082    async fn router_create_record_internal_errors_are_sanitized() {
4083        let (_dir, store, gate, app, token) = build_write_input_fixture().await;
4084        let private_key = "private-authorization-denied-CAS-conflict";
4085        store
4086            .insert_malformed_record_for_test(
4087                "did:web:pub.example.com",
4088                "app.bsky.feed.post",
4089                private_key,
4090            )
4091            .unwrap();
4092        let source = store
4093            .snapshot("did:web:pub.example.com")
4094            .unwrap_err()
4095            .to_string();
4096        assert!(
4097            source.contains(private_key),
4098            "fixture must exercise sensitive internal context"
4099        );
4100        let response = app
4101            .oneshot(write_http_request(
4102                &token,
4103                &write_input(7),
4104                HeaderMap::new(),
4105            ))
4106            .await
4107            .unwrap();
4108        assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
4109        assert_eq!(
4110            body_json(response).await,
4111            json!({
4112                "error": "InternalServerError", "message": "public repository operation failed"
4113            })
4114        );
4115        assert_eq!(gate.0.load(std::sync::atomic::Ordering::Relaxed), 1);
4116    }
4117
4118    #[tokio::test]
4119    async fn router_create_record_rejects_malformed_optional_fields_without_writes() {
4120        let (_dir, store, gate, app, token) = build_write_input_fixture().await;
4121        for field in ["swapCommit", "validate", "returnRecord"] {
4122            let mut invalid = vec![Value::Null, json!(1), json!(""), json!([]), json!({})];
4123            if field == "swapCommit" {
4124                invalid.extend([json!(false), json!(true), json!("not-a-cid")]);
4125            }
4126            for value in invalid {
4127                let mut input = write_input(7);
4128                input[field] = value.clone();
4129                let response = app
4130                    .clone()
4131                    .oneshot(write_http_request(&token, &input, HeaderMap::new()))
4132                    .await
4133                    .unwrap();
4134                assert_eq!(
4135                    response.status(),
4136                    StatusCode::BAD_REQUEST,
4137                    "{field}={value}"
4138                );
4139                assert_eq!(body_json(response).await["error"], errors::INVALID_REQUEST);
4140                assert!(store.snapshot("did:web:pub.example.com").unwrap().is_none());
4141                assert_eq!(gate.0.load(std::sync::atomic::Ordering::Relaxed), 0);
4142            }
4143        }
4144    }
4145
4146    #[tokio::test]
4147    async fn router_create_record_rejects_invalid_idempotency_headers_without_writes() {
4148        use axum::http::HeaderValue;
4149        let (_dir, store, gate, app, token) = build_write_input_fixture().await;
4150        for value in [
4151            HeaderValue::from_static(""),
4152            HeaderValue::from_static(" "),
4153            HeaderValue::from_static("bad/key"),
4154            HeaderValue::from_static("first,second"),
4155            HeaderValue::from_str(&"a".repeat(129)).unwrap(),
4156            HeaderValue::from_bytes(&[0xff]).unwrap(),
4157        ] {
4158            let mut headers = HeaderMap::new();
4159            headers.insert("Idempotency-Key", value);
4160            let response = app
4161                .clone()
4162                .oneshot(write_http_request(&token, &write_input(7), headers))
4163                .await
4164                .unwrap();
4165            assert_eq!(response.status(), StatusCode::BAD_REQUEST);
4166            assert_eq!(body_json(response).await["error"], errors::INVALID_REQUEST);
4167            assert!(store.snapshot("did:web:pub.example.com").unwrap().is_none());
4168            assert_eq!(gate.0.load(std::sync::atomic::Ordering::Relaxed), 0);
4169        }
4170        let mut headers = HeaderMap::new();
4171        headers.append("Idempotency-Key", HeaderValue::from_static("first"));
4172        headers.append("Idempotency-Key", HeaderValue::from_static("second"));
4173        let response = app
4174            .oneshot(write_http_request(&token, &write_input(7), headers))
4175            .await
4176            .unwrap();
4177        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
4178        assert_eq!(body_json(response).await["error"], errors::INVALID_REQUEST);
4179        assert!(store.snapshot("did:web:pub.example.com").unwrap().is_none());
4180        assert_eq!(gate.0.load(std::sync::atomic::Ordering::Relaxed), 0);
4181    }
4182
4183    #[tokio::test]
4184    async fn router_create_record_false_skips_schema_but_not_structural_checks() {
4185        let (_dir, store, _gate, app, token) = build_write_input_fixture().await;
4186        let mut input = write_input(7);
4187        input["validate"] = json!(false);
4188        input["returnRecord"] = json!(true);
4189        input["record"].as_object_mut().unwrap().remove("text");
4190        input["record"].as_object_mut().unwrap().remove("createdAt");
4191        let response = app
4192            .clone()
4193            .oneshot(write_http_request(&token, &input, HeaderMap::new()))
4194            .await
4195            .unwrap();
4196        assert_eq!(response.status(), StatusCode::OK);
4197        assert_eq!(body_json(response).await["value"], input["record"]);
4198        let head = store
4199            .snapshot("did:web:pub.example.com")
4200            .unwrap()
4201            .unwrap()
4202            .commit
4203            .cid_atproto()
4204            .unwrap();
4205        input["record"]["unsupported"] = json!(1.5);
4206        let response = app
4207            .oneshot(write_http_request(&token, &input, HeaderMap::new()))
4208            .await
4209            .unwrap();
4210        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
4211        let snapshot = store.snapshot("did:web:pub.example.com").unwrap().unwrap();
4212        assert_eq!(snapshot.records.len(), 1);
4213        assert_eq!(snapshot.commit.cid_atproto().unwrap(), head);
4214    }
4215
4216    #[tokio::test]
4217    async fn router_create_record_known_schemas_validate_omitted_and_true() {
4218        for mode in [None, Some(true)] {
4219            let (_dir, store, gate, app, token) = build_write_input_fixture().await;
4220            let blob = json!({"$type":"blob", "ref":{"$link":hyprstream_pds::Cid::from_raw(b"image").to_string()}, "mimeType":"image/png", "size":5});
4221            let strong = json!({"uri":"at://did:plc:abc/app.bsky.feed.post/custom-key", "cid":hyprstream_pds::Cid::from_dag_cbor(b"record").to_string()});
4222            let mut post = write_input(7);
4223            post["record"]["text"] = json!("e\u{301}".repeat(300)); // 300 graphemes, 600 code points.
4224            post["record"]["langs"] = json!(["en", "i-klingon", "qaa-Zzzz-419"]);
4225            post["record"]["reply"] = json!({"root":strong.clone(), "parent":strong.clone()});
4226            post["record"]["facets"] = json!([{"index":{"byteStart":0,"byteEnd":1}, "features":[
4227                {"$type":"app.bsky.richtext.facet#mention", "did":"did:key:zExample"},
4228                {"$type":"app.bsky.richtext.facet#link", "uri":"https://example.com/path"}
4229            ]}]);
4230            post["record"]["embed"] = json!({"$type":"app.bsky.embed.images","images":[{"image":blob.clone(),"alt":"image","aspectRatio":{"width":1,"height":1}}]});
4231            let profile = json!({"repo":"did:web:pub.example.com", "collection":"app.bsky.actor.profile", "record":{
4232                "$type":"app.bsky.actor.profile", "displayName":"Profile", "pronouns":"they/them", "website":"https://example.com", "avatar":blob, "pinnedPost":strong,
4233                "createdAt":"1985-04-12T23:20:50.12345678912345Z"
4234            }});
4235            let mut invalid = Vec::new();
4236            for field in ["text", "createdAt"] {
4237                let mut missing = post.clone();
4238                missing["record"].as_object_mut().unwrap().remove(field);
4239                invalid.push(missing);
4240                for bad in [Value::Null, json!(5), json!([])] {
4241                    let mut bad_type = post.clone();
4242                    bad_type["record"][field] = bad;
4243                    invalid.push(bad_type);
4244                }
4245            }
4246            for (pointer, bad) in [
4247                ("/record/text", json!("x".repeat(301))),
4248                (
4249                    "/record/text",
4250                    json!(format!("x{}", "\u{301}".repeat(1600))),
4251                ),
4252                ("/record/createdAt", json!("2026-02-30T00:00:00Z")),
4253                ("/record/createdAt", json!("2026-01-01t00:00:00z")),
4254                ("/record/createdAt", json!("2026-01-01T00:00:00-00:00")),
4255                ("/record/langs", json!(["en_US"])),
4256                ("/record/langs", json!(["en", "en", "en", "en"])),
4257                ("/record/reply/root/cid", json!("private-not-a-cid")),
4258                (
4259                    "/record/reply/root/uri",
4260                    json!("at://invalid/app.bsky.feed.post/key"),
4261                ),
4262                ("/record/facets/0/index/byteStart", json!(-1)),
4263                ("/record/facets/0/features/0/did", json!("did::private")),
4264                (
4265                    "/record/facets/0/features/0/did",
4266                    json!("did:key:zExample%"),
4267                ),
4268                (
4269                    "/record/reply/root/uri",
4270                    json!("at://did:key:zExample%/app.bsky.feed.post/key"),
4271                ),
4272                (
4273                    "/record/facets/0/features/1/uri",
4274                    json!("https://example.com/invalid space"),
4275                ),
4276                ("/record/embed/images/0/image/mimeType", json!("text/plain")),
4277                ("/record/embed/images/0/image/size", json!(2000001)),
4278                ("/record/embed/images/0/aspectRatio/width", json!(0)),
4279            ] {
4280                let mut bad_input = post.clone();
4281                *bad_input.pointer_mut(pointer).unwrap() = bad;
4282                invalid.push(bad_input);
4283            }
4284            for (field, bad) in [
4285                ("displayName", json!("x".repeat(65))),
4286                ("description", json!("x".repeat(257))),
4287                ("pronouns", json!("x".repeat(21))),
4288                ("avatar", Value::Null),
4289                ("website", json!("relative/path")),
4290                ("displayName", json!(false)),
4291                ("pinnedPost", json!({})),
4292                (
4293                    "labels",
4294                    json!({"$type":"com.atproto.label.defs#selfLabels","values":[{}]}),
4295                ),
4296            ] {
4297                let mut bad_input = profile.clone();
4298                bad_input["record"][field] = bad;
4299                invalid.push(bad_input);
4300            }
4301            for mut input in invalid {
4302                if let Some(mode) = mode {
4303                    input["validate"] = json!(mode);
4304                }
4305                let response = app
4306                    .clone()
4307                    .oneshot(write_http_request(&token, &input, HeaderMap::new()))
4308                    .await
4309                    .unwrap();
4310                assert_eq!(response.status(), StatusCode::BAD_REQUEST, "{input}");
4311                assert_eq!(
4312                    body_json(response).await,
4313                    json!({"error":"InvalidRequest","message":"record does not match its known schema"})
4314                );
4315                assert!(store.snapshot("did:web:pub.example.com").unwrap().is_none());
4316                assert_eq!(gate.0.load(std::sync::atomic::Ordering::Relaxed), 0);
4317            }
4318            for mut input in [post, profile] {
4319                record_validation::validate(
4320                    input["collection"].as_str().unwrap(),
4321                    &input["record"],
4322                )
4323                .unwrap();
4324                input["record"].as_object_mut().unwrap().remove("embed");
4325                input["record"].as_object_mut().unwrap().remove("avatar");
4326                if let Some(mode) = mode {
4327                    input["validate"] = json!(mode);
4328                }
4329                let response = app
4330                    .clone()
4331                    .oneshot(write_http_request(&token, &input, HeaderMap::new()))
4332                    .await
4333                    .unwrap();
4334                assert_eq!(
4335                    response.status(),
4336                    StatusCode::OK,
4337                    "{}",
4338                    body_json(response).await
4339                );
4340            }
4341            assert_eq!(
4342                store
4343                    .snapshot("did:web:pub.example.com")
4344                    .unwrap()
4345                    .unwrap()
4346                    .records
4347                    .len(),
4348                2
4349            );
4350        }
4351    }
4352
4353    #[tokio::test]
4354    async fn router_explicit_tids_preserve_odd_low_bits_in_all_validation_modes() {
4355        for mode in [None, Some(true), Some(false)] {
4356            let (_dir, store, gate, app, token) = build_write_input_fixture().await;
4357            for rkey in ["3jzfcijpj2z2b", "2222222222223"] {
4358                let mut input = write_input(7);
4359                input["rkey"] = json!(rkey);
4360                if let Some(mode) = mode {
4361                    input["validate"] = json!(mode);
4362                }
4363                let response = app
4364                    .clone()
4365                    .oneshot(write_http_request(&token, &input, HeaderMap::new()))
4366                    .await
4367                    .unwrap();
4368                assert_eq!(response.status(), StatusCode::OK);
4369                let created = body_json(response).await;
4370                assert!(created["uri"]
4371                    .as_str()
4372                    .unwrap()
4373                    .ends_with(&format!("/{rkey}")));
4374                let read = app.clone().oneshot(read_request(&format!("/xrpc/com.atproto.repo.getRecord?repo=pub.example.com&collection=app.bsky.feed.post&rkey={rkey}"))).await.unwrap();
4375                assert_eq!(read.status(), StatusCode::OK);
4376                assert_eq!(body_json(read).await["uri"], created["uri"]);
4377            }
4378            assert_eq!(
4379                store
4380                    .snapshot("did:web:pub.example.com")
4381                    .unwrap()
4382                    .unwrap()
4383                    .records
4384                    .len(),
4385                2
4386            );
4387            assert_eq!(gate.0.load(std::sync::atomic::Ordering::Relaxed), 2);
4388        }
4389    }
4390
4391    #[tokio::test]
4392    async fn router_create_record_canonical_keys_and_unknown_collections() {
4393        let (_dir, store, gate, app, token) = build_write_input_fixture().await;
4394        let noncanonical = "kjzfcijpj2z2a";
4395        assert!(Tid::parse(noncanonical).is_err());
4396        for mode in [None, Some(true), Some(false)] {
4397            let mut input = write_input(7);
4398            if let Some(mode) = mode {
4399                input["validate"] = json!(mode);
4400            }
4401            let mut unknown = input.clone();
4402            unknown["collection"] = json!("com.example.unknown");
4403            unknown["record"]["$type"] = unknown["collection"].clone();
4404            input["rkey"] = json!(noncanonical);
4405            for invalid in [input, unknown] {
4406                let response = app
4407                    .clone()
4408                    .oneshot(write_http_request(&token, &invalid, HeaderMap::new()))
4409                    .await
4410                    .unwrap();
4411                assert_eq!(response.status(), StatusCode::BAD_REQUEST);
4412                assert_eq!(body_json(response).await["error"], errors::INVALID_REQUEST);
4413                assert!(store.snapshot("did:web:pub.example.com").unwrap().is_none());
4414                assert_eq!(gate.0.load(std::sync::atomic::Ordering::Relaxed), 0);
4415            }
4416        }
4417        let mut input = write_input(7);
4418        input["record"]["embed"] = json!({"$type":"com.example.futureEmbed","extension":true});
4419        input["record"]["extension"] = json!({"value":true});
4420        let response = app
4421            .oneshot(write_http_request(&token, &input, HeaderMap::new()))
4422            .await
4423            .unwrap();
4424        assert_eq!(response.status(), StatusCode::OK); // Open unions and extra properties stay extensible.
4425    }
4426
4427    #[tokio::test]
4428    async fn router_create_record_profiles_use_self_for_explicit_and_omitted_keys() {
4429        for omit_key in [false, true] {
4430            let (_dir, store, gate, app, token) = build_write_input_fixture().await;
4431            let mut input = json!({
4432                "repo": "did:web:pub.example.com",
4433                "collection": "app.bsky.actor.profile",
4434                "record": {"$type": "app.bsky.actor.profile", "displayName": "Profile"},
4435                "validate": false
4436            });
4437            for invalid in [
4438                Value::Null,
4439                json!(false),
4440                json!(1),
4441                json!(""),
4442                json!("other"),
4443                json!(Tid::from_raw(7).encode()),
4444            ] {
4445                let mut malformed = input.clone();
4446                malformed["rkey"] = invalid;
4447                let response = app
4448                    .clone()
4449                    .oneshot(write_http_request(&token, &malformed, HeaderMap::new()))
4450                    .await
4451                    .unwrap();
4452                assert_eq!(response.status(), StatusCode::BAD_REQUEST);
4453                assert!(store.snapshot("did:web:pub.example.com").unwrap().is_none());
4454                assert_eq!(gate.0.load(std::sync::atomic::Ordering::Relaxed), 0);
4455            }
4456            if !omit_key {
4457                input["rkey"] = json!("self");
4458            }
4459            let response = app
4460                .clone()
4461                .oneshot(write_http_request(&token, &input, HeaderMap::new()))
4462                .await
4463                .unwrap();
4464            assert_eq!(response.status(), StatusCode::OK);
4465            let created = body_json(response).await;
4466            assert_eq!(
4467                created["uri"],
4468                "at://did:web:pub.example.com/app.bsky.actor.profile/self"
4469            );
4470            let response = app
4471                .oneshot(write_http_request(&token, &input, HeaderMap::new()))
4472                .await
4473                .unwrap();
4474            assert_eq!(response.status(), StatusCode::OK);
4475            assert_eq!(body_json(response).await, created);
4476            let snapshot = store.snapshot("did:web:pub.example.com").unwrap().unwrap();
4477            assert_eq!(snapshot.records.len(), 1);
4478            assert!(snapshot.records.contains_key(&(
4479                "app.bsky.actor.profile".into(),
4480                AtprotoRecordKey::new("self").unwrap()
4481            )));
4482        }
4483    }
4484
4485    #[tokio::test]
4486    async fn router_create_record_generates_post_keys_and_recovers_idempotent_results() {
4487        let (_dir, store, gate, app, token) = build_write_input_fixture().await;
4488        let mut input = write_input(7);
4489        input.as_object_mut().unwrap().remove("rkey");
4490        for invalid in [
4491            Value::Null,
4492            json!(false),
4493            json!(1),
4494            json!(""),
4495            json!("self"),
4496            json!("bad/key"),
4497        ] {
4498            let mut malformed = input.clone();
4499            malformed["rkey"] = invalid;
4500            let response = app
4501                .clone()
4502                .oneshot(write_http_request(&token, &malformed, HeaderMap::new()))
4503                .await
4504                .unwrap();
4505            assert_eq!(response.status(), StatusCode::BAD_REQUEST);
4506            assert!(store.snapshot("did:web:pub.example.com").unwrap().is_none());
4507            assert_eq!(gate.0.load(std::sync::atomic::Ordering::Relaxed), 0);
4508        }
4509        let mut headers = HeaderMap::new();
4510        headers.insert("Idempotency-Key", "generated-post".parse().unwrap());
4511        let response = app
4512            .clone()
4513            .oneshot(write_http_request(&token, &input, headers.clone()))
4514            .await
4515            .unwrap();
4516        assert_eq!(response.status(), StatusCode::OK);
4517        let created = body_json(response).await;
4518        let generated_key = created["uri"].as_str().unwrap().rsplit('/').next().unwrap();
4519        assert!(Tid::parse(generated_key).is_ok());
4520        let mut uris = std::collections::BTreeSet::new();
4521        uris.insert(created["uri"].as_str().unwrap().to_owned());
4522        for _ in 0..2 {
4523            let response = app
4524                .clone()
4525                .oneshot(write_http_request(&token, &input, HeaderMap::new()))
4526                .await
4527                .unwrap();
4528            assert_eq!(response.status(), StatusCode::OK);
4529            let created = body_json(response).await;
4530            assert!(uris.insert(created["uri"].as_str().unwrap().to_owned()));
4531        }
4532        let latest = store
4533            .snapshot("did:web:pub.example.com")
4534            .unwrap()
4535            .unwrap()
4536            .commit
4537            .cid_atproto()
4538            .unwrap();
4539        let response = app
4540            .clone()
4541            .oneshot(write_http_request(&token, &input, headers.clone()))
4542            .await
4543            .unwrap();
4544        assert_eq!(response.status(), StatusCode::OK);
4545        assert_eq!(body_json(response).await, created);
4546        let mut explicit_retry = input.clone();
4547        explicit_retry["rkey"] = json!(generated_key);
4548        let response = app
4549            .clone()
4550            .oneshot(write_http_request(&token, &explicit_retry, headers.clone()))
4551            .await
4552            .unwrap();
4553        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
4554        input["record"]["text"] = json!("changed content");
4555        let response = app
4556            .oneshot(write_http_request(&token, &input, headers))
4557            .await
4558            .unwrap();
4559        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
4560        let snapshot = store.snapshot("did:web:pub.example.com").unwrap().unwrap();
4561        assert_eq!(snapshot.records.len(), 3);
4562        assert_eq!(snapshot.commit.cid_atproto().unwrap(), latest);
4563    }
4564
4565    // ── Finding 1: real capacity test through the mounted router ──────────────
4566
4567    #[tokio::test]
4568    async fn router_capacity_n_plus_1_blocked_until_body_dropped() {
4569        let app = build_xrpc_router().await;
4570        let uri = "/xrpc/com.atproto.sync.getRepo?did=did:web:pub.example.com";
4571
4572        // Issue N requests, RETAIN response bodies unconsumed.
4573        let mut held: Vec<axum::response::Response> = Vec::new();
4574        for _ in 0..GET_REPO_CONCURRENCY {
4575            let resp = app.clone().oneshot(req(uri)).await.unwrap();
4576            assert_eq!(resp.status(), StatusCode::OK);
4577            held.push(resp);
4578        }
4579
4580        // N+1th request must NOT complete while all permits are held in bodies.
4581        let n1 = app.clone().oneshot(req(uri));
4582        let mut n1 = Box::pin(n1);
4583        tokio::select! {
4584            _ = &mut n1 => panic!("N+1th getRepo completed before capacity freed"),
4585            _ = tokio::time::sleep(std::time::Duration::from_millis(100)) => {}
4586        }
4587
4588        // Drop ONE held Response → its Body + embedded OwnedSemaphorePermit released.
4589        held.pop();
4590
4591        // N+1th should now complete.
4592        let result = tokio::time::timeout(std::time::Duration::from_secs(2), n1.as_mut()).await;
4593        assert!(
4594            result.is_ok(),
4595            "N+1th getRepo did not complete after dropping a body"
4596        );
4597        assert_eq!(result.unwrap().unwrap().status(), StatusCode::OK);
4598    }
4599
4600    // ── Finding 2: router-mounted endpoint tests ──────────────────────────────
4601
4602    #[tokio::test]
4603    async fn router_private_repo_invisible_describe_repo() {
4604        let app = build_xrpc_router().await;
4605        let resp = app
4606            .oneshot(req(
4607                "/xrpc/com.atproto.repo.describeRepo?repo=did:web:priv.example.com",
4608            ))
4609            .await
4610            .unwrap();
4611        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
4612        let body = resp_json(resp).await;
4613        assert_eq!(body["error"], errors::REPO_NOT_FOUND);
4614    }
4615
4616    #[tokio::test]
4617    async fn router_private_repo_invisible_get_record() {
4618        let app = build_xrpc_router().await;
4619        let resp = app
4620            .oneshot(req(
4621                "/xrpc/com.atproto.repo.getRecord?repo=did:web:priv.example.com\
4622                 &collection=ai.hyprstream.model&rkey=abc",
4623            ))
4624            .await
4625            .unwrap();
4626        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
4627        let body = resp_json(resp).await;
4628        assert_eq!(body["error"], errors::REPO_NOT_FOUND);
4629    }
4630
4631    #[tokio::test]
4632    async fn router_private_repo_invisible_get_repo() {
4633        let app = build_xrpc_router().await;
4634        let resp = app
4635            .oneshot(req(
4636                "/xrpc/com.atproto.sync.getRepo?did=did:web:priv.example.com",
4637            ))
4638            .await
4639            .unwrap();
4640        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
4641        let body = resp_json(resp).await;
4642        assert_eq!(body["error"], errors::REPO_NOT_FOUND);
4643    }
4644
4645    #[tokio::test]
4646    async fn router_private_repo_invisible_resolve_handle() {
4647        let app = build_xrpc_router().await;
4648        let resp = app
4649            .oneshot(req(
4650                "/xrpc/com.atproto.identity.resolveHandle?handle=priv.example.com",
4651            ))
4652            .await
4653            .unwrap();
4654        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
4655        let body = resp_json(resp).await;
4656        assert_eq!(body["error"], errors::HANDLE_NOT_FOUND);
4657    }
4658
4659    #[tokio::test]
4660    async fn router_public_describe_repo_ok() {
4661        let app = build_xrpc_router().await;
4662        let resp = app
4663            .oneshot(req(
4664                "/xrpc/com.atproto.repo.describeRepo?repo=did:web:pub.example.com",
4665            ))
4666            .await
4667            .unwrap();
4668        assert_eq!(resp.status(), StatusCode::OK);
4669        let body = resp_json(resp).await;
4670        assert_eq!(body["did"], "did:web:pub.example.com");
4671        assert_eq!(body["handleIsCorrect"], true);
4672    }
4673
4674    #[tokio::test]
4675    async fn router_describe_server_reports_service_did_and_safe_defaults() {
4676        let app = build_xrpc_router().await;
4677        let resp = app
4678            .oneshot(req("/xrpc/com.atproto.server.describeServer"))
4679            .await
4680            .unwrap();
4681        assert_eq!(resp.status(), StatusCode::OK);
4682        let body = resp_json(resp).await;
4683        assert_eq!(body["did"], "did:web:h.example.com");
4684        assert_eq!(body["availableUserDomains"], json!([]));
4685        assert_eq!(body["inviteCodeRequired"], true);
4686        assert_eq!(body["phoneVerificationRequired"], false);
4687    }
4688
4689    #[tokio::test]
4690    async fn router_issuer_identity_routes_share_canonical_service_did() {
4691        for (issuer, expected) in [
4692            ("https://pds.example", "did:web:pds.example"),
4693            ("https://PDS.example:443/oauth", "did:web:pds.example"),
4694            (
4695                "https://pds.example:8443/oauth",
4696                "did:web:pds.example%3A8443",
4697            ),
4698            ("http://127.0.0.1:6791", "did:web:127.0.0.1%3A6791"),
4699        ] {
4700            let mut state = build_test_state(true).await;
4701            let mutable = Arc::get_mut(&mut state).unwrap();
4702            mutable.issuer_url = issuer.to_owned();
4703            mutable.signing_key = Some(ed25519_dalek::SigningKey::from_bytes(&[0x76; 32]));
4704            let app = build_production_app_from_state(state).await;
4705            for (path, field) in [
4706                ("/xrpc/com.atproto.server.describeServer", "did"),
4707                ("/.well-known/did.json", "id"),
4708                ("/clients/test-client/did.json", "id"),
4709            ] {
4710                let response = app.clone().oneshot(req(path)).await.unwrap();
4711                assert_eq!(response.status(), StatusCode::OK, "{issuer} {path}");
4712                let body = resp_json(response).await;
4713                let subject = if path.starts_with("/clients/") {
4714                    format!("{expected}:clients:test-client")
4715                } else {
4716                    expected.to_owned()
4717                };
4718                assert_eq!(body[field], subject, "{issuer} {path}");
4719                if path == "/.well-known/did.json" {
4720                    assert!(!body["verificationMethod"].as_array().unwrap().is_empty());
4721                }
4722                if let Some(methods) = body["verificationMethod"].as_array() {
4723                    for method in methods {
4724                        assert_eq!(method["controller"], subject);
4725                        assert!(method["id"]
4726                            .as_str()
4727                            .unwrap()
4728                            .starts_with(&format!("{subject}#")));
4729                    }
4730                }
4731            }
4732            let response = app.oneshot(req("/.well-known/atproto-did")).await.unwrap();
4733            assert_eq!(response.status(), StatusCode::OK);
4734            let body = axum::body::to_bytes(response.into_body(), usize::MAX)
4735                .await
4736                .unwrap();
4737            assert_eq!(body.as_ref(), expected.as_bytes());
4738        }
4739    }
4740
4741    #[tokio::test]
4742    async fn router_issuer_identity_routes_reject_unsupported_origins() {
4743        for issuer in [
4744            "https://user@pds.example",
4745            "https://[::1]:8443",
4746            "ftp://pds.example",
4747            "not-a-url",
4748        ] {
4749            let mut state = build_test_state(true).await;
4750            let mutable = Arc::get_mut(&mut state).unwrap();
4751            mutable.issuer_url = issuer.to_owned();
4752            mutable.signing_key = Some(ed25519_dalek::SigningKey::from_bytes(&[0x76; 32]));
4753            let app = build_production_app_from_state(state).await;
4754            for path in [
4755                "/xrpc/com.atproto.server.describeServer",
4756                "/.well-known/did.json",
4757                "/.well-known/atproto-did",
4758                "/clients/test-client/did.json",
4759            ] {
4760                let response = app.clone().oneshot(req(path)).await.unwrap();
4761                assert!(response.status().is_server_error(), "{issuer} {path}");
4762                let body = axum::body::to_bytes(response.into_body(), usize::MAX)
4763                    .await
4764                    .unwrap();
4765                assert!(!String::from_utf8_lossy(&body).contains(issuer));
4766            }
4767        }
4768    }
4769
4770    #[tokio::test]
4771    async fn describe_server_advertises_only_configured_account_zone() {
4772        let mut state = build_test_state(false).await;
4773        Arc::get_mut(&mut state).unwrap().hosted_account_zone =
4774            Some(crate::account::AccountZone::new("acct.example.com").unwrap());
4775        let body = resp_json(describe_server(State(state)).await).await;
4776        assert_eq!(body["availableUserDomains"], json!([".acct.example.com"]));
4777    }
4778
4779    #[tokio::test]
4780    async fn router_get_record_nonexistent_rkey() {
4781        let app = build_xrpc_router().await;
4782        let resp = app
4783            .clone()
4784            .oneshot(req(
4785                "/xrpc/com.atproto.repo.getRecord?repo=did:web:pub.example.com\
4786                 &collection=ai.hyprstream.model&rkey=zzzzzzzzzzzz",
4787            ))
4788            .await
4789            .unwrap();
4790        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
4791        let body = resp_json(resp).await;
4792        assert_eq!(body["error"], errors::RECORD_NOT_FOUND);
4793    }
4794
4795    #[tokio::test]
4796    async fn router_missing_params_invalid_request() {
4797        let app = build_xrpc_router().await;
4798        // Missing repo param.
4799        let resp = app
4800            .clone()
4801            .oneshot(req(
4802                "/xrpc/com.atproto.repo.getRecord?collection=ai.hyprstream.model",
4803            ))
4804            .await
4805            .unwrap();
4806        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
4807        let body = resp_json(resp).await;
4808        assert_eq!(body["error"], errors::INVALID_REQUEST);
4809
4810        // Missing handle param.
4811        let resp = app
4812            .oneshot(req("/xrpc/com.atproto.identity.resolveHandle"))
4813            .await
4814            .unwrap();
4815        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
4816        let body = resp_json(resp).await;
4817        assert_eq!(body["error"], errors::INVALID_REQUEST);
4818    }
4819
4820    #[tokio::test]
4821    async fn router_unknown_handle_handle_not_found() {
4822        let app = build_xrpc_router().await;
4823        let resp = app
4824            .oneshot(req(
4825                "/xrpc/com.atproto.identity.resolveHandle?handle=does-not-exist.com",
4826            ))
4827            .await
4828            .unwrap();
4829        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
4830        let body = resp_json(resp).await;
4831        assert_eq!(body["error"], errors::HANDLE_NOT_FOUND);
4832    }
4833
4834    #[tokio::test]
4835    async fn router_since_empty_rejected() {
4836        let app = build_xrpc_router().await;
4837        let resp = app
4838            .oneshot(req(
4839                "/xrpc/com.atproto.sync.getRepo?did=did:web:pub.example.com&since=",
4840            ))
4841            .await
4842            .unwrap();
4843        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
4844        let body = resp_json(resp).await;
4845        assert_eq!(body["error"], errors::INVALID_REQUEST);
4846    }
4847
4848    #[tokio::test]
4849    async fn router_since_non_empty_rejected() {
4850        let app = build_xrpc_router().await;
4851        let resp = app
4852            .oneshot(req(
4853                "/xrpc/com.atproto.sync.getRepo?did=did:web:pub.example.com\
4854                 &since=3whysti2w4mq2",
4855            ))
4856            .await
4857            .unwrap();
4858        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
4859        let body = resp_json(resp).await;
4860        assert_eq!(body["error"], errors::INVALID_REQUEST);
4861    }
4862
4863    #[tokio::test]
4864    async fn router_get_repo_ok_streams_car() {
4865        let app = build_xrpc_router().await;
4866        let resp = app
4867            .oneshot(req(
4868                "/xrpc/com.atproto.sync.getRepo?did=did:web:pub.example.com",
4869            ))
4870            .await
4871            .unwrap();
4872        assert_eq!(resp.status(), StatusCode::OK);
4873        assert_eq!(
4874            resp.headers().get(header::CONTENT_TYPE).unwrap(),
4875            "application/vnd.ipld.car",
4876        );
4877        // Consume the body fully so the permit is released.
4878        let bytes = axum::body::to_bytes(resp.into_body(), 4 * 1024 * 1024)
4879            .await
4880            .unwrap();
4881        assert!(!bytes.is_empty());
4882    }
4883
4884    // ── Finding 1: feature-gate matrix — all 4 routes, enabled AND disabled ────
4885
4886    #[tokio::test]
4887    async fn router_feature_gate_disabled_all_five_routes_404() {
4888        let app = build_production_app(false).await;
4889        // All five XRPC routes must 404 when the gate is disabled.
4890        let routes = [
4891            "/xrpc/com.atproto.sync.getRepo?did=did:web:pub.example.com",
4892            "/xrpc/com.atproto.repo.describeRepo?repo=did:web:pub.example.com",
4893            "/xrpc/com.atproto.repo.getRecord?repo=did:web:pub.example.com&collection=ai.hyprstream.model&rkey=abc",
4894            "/xrpc/com.atproto.identity.resolveHandle?handle=pub.example.com",
4895            "/xrpc/com.atproto.server.describeServer",
4896        ];
4897        for uri in &routes {
4898            let resp = app.clone().oneshot(req(uri)).await.unwrap();
4899            assert_eq!(
4900                resp.status(),
4901                StatusCode::NOT_FOUND,
4902                "route {uri} should 404 when xrpc_read_slice is disabled"
4903            );
4904        }
4905    }
4906
4907    #[tokio::test]
4908    async fn router_feature_gate_enabled_all_five_routes_reachable() {
4909        // Smoke-test: all five routes reach XRPC handlers (not 404) when enabled.
4910        // Detailed assertions are in the individual endpoint tests above.
4911        let app = build_production_app(true).await;
4912        let routes = [
4913            ("/xrpc/com.atproto.repo.describeRepo?repo=did:web:pub.example.com", StatusCode::OK),
4914            ("/xrpc/com.atproto.identity.resolveHandle?handle=pub.example.com", StatusCode::OK),
4915            ("/xrpc/com.atproto.repo.getRecord?repo=did:web:pub.example.com&collection=ai.hyprstream.model&rkey=abc", StatusCode::BAD_REQUEST), // RecordNotFound
4916            ("/xrpc/com.atproto.sync.getRepo?did=did:web:pub.example.com", StatusCode::OK),
4917            ("/xrpc/com.atproto.server.describeServer", StatusCode::OK),
4918        ];
4919        for (uri, expected) in &routes {
4920            let resp = app.clone().oneshot(req(uri)).await.unwrap();
4921            assert_eq!(
4922                resp.status(),
4923                *expected,
4924                "route {uri} status mismatch when xrpc_read_slice is enabled"
4925            );
4926        }
4927    }
4928
4929    struct SessionProbe {
4930        calls: std::sync::atomic::AtomicUsize,
4931        handle: parking_lot::Mutex<String>,
4932    }
4933
4934    #[async_trait::async_trait]
4935    impl AtprotoSessionResolver for SessionProbe {
4936        async fn resolve_session(&self, did: &str) -> anyhow::Result<Option<AtprotoSessionInfo>> {
4937            self.calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
4938            assert_eq!(did, "did:web:pub.example.com");
4939            Ok(Some(AtprotoSessionInfo {
4940                handle: self.handle.lock().clone(),
4941                active: true,
4942                ..Default::default()
4943            }))
4944        }
4945    }
4946
4947    #[tokio::test]
4948    async fn router_get_session_authenticates_before_native_resolution() {
4949        use std::sync::atomic::Ordering;
4950        if hyprstream_rpc::auth::global_credential_revocation_store().is_none() {
4951            let _ = hyprstream_rpc::auth::set_global_credential_revocation_store(Arc::new(
4952                hyprstream_rpc::auth::InMemoryCredentialRevocationStore::new(),
4953            ));
4954        }
4955        let mut state = build_test_state(true).await;
4956        let probe = Arc::new(SessionProbe {
4957            calls: 0.into(),
4958            handle: parking_lot::Mutex::new("pub.example.com".to_owned()),
4959        });
4960        Arc::get_mut(&mut state).unwrap().atproto_session_resolver = Some(probe.clone());
4961        let key = ed25519_dalek::SigningKey::from_bytes(&[0x76; 32]);
4962        Arc::get_mut(&mut state).unwrap().verifying_key_bytes = key.verifying_key().to_bytes();
4963        let issuer = state.atproto_issuer_url();
4964        let now = chrono::Utc::now().timestamp();
4965        let claims = hyprstream_rpc::auth::Claims::new(
4966            "did:web:pub.example.com".to_owned(),
4967            now,
4968            now + 3600,
4969        )
4970        .with_issuer(issuer.clone())
4971        .with_audience(Some(issuer))
4972        .with_tenant("session-tests".to_owned())
4973        .with_client_id("session-tests")
4974        .with_scope(Some("atproto".to_owned()))
4975        .with_jti();
4976        let key = ed25519_dalek::SigningKey::from_bytes(&[0x76; 32]);
4977        let app = build_production_app_from_state(state).await;
4978        let uri = "/xrpc/com.atproto.server.getSession";
4979        assert_eq!(
4980            app.clone().oneshot(req(uri)).await.unwrap().status(),
4981            StatusCode::UNAUTHORIZED
4982        );
4983        let mut no_scope = claims.clone();
4984        no_scope.scope = Some("openid".to_owned());
4985        let mut expired = claims.clone();
4986        expired.exp = now - 3600;
4987        let mut wrong_audience = claims.clone();
4988        wrong_audience = wrong_audience.with_audience(Some("https://foreign.example".to_owned()));
4989        let mut missing_tenant = claims.clone();
4990        missing_tenant.tenant = None;
4991        let bound_as_bearer = claims
4992            .clone()
4993            .with_cnf_jkt_thumbprint("test-proof-key".to_owned());
4994        for invalid in [
4995            no_scope,
4996            expired,
4997            wrong_audience,
4998            missing_tenant,
4999            bound_as_bearer,
5000        ] {
5001            let token = hyprstream_rpc::auth::jwt::encode(&invalid, &key);
5002            let request = HttpRequest::builder()
5003                .uri(uri)
5004                .header(header::AUTHORIZATION, format!("Bearer {token}"))
5005                .body(Body::empty())
5006                .unwrap();
5007            assert!(app
5008                .clone()
5009                .oneshot(request)
5010                .await
5011                .unwrap()
5012                .status()
5013                .is_client_error());
5014            assert_eq!(probe.calls.load(Ordering::SeqCst), 0);
5015        }
5016        let token = hyprstream_rpc::auth::jwt::encode(&claims, &key);
5017        let request = HttpRequest::builder()
5018            .uri(uri)
5019            .header(header::AUTHORIZATION, format!("Bearer {token}"))
5020            .body(Body::empty())
5021            .unwrap();
5022        let response = app.oneshot(request).await.unwrap();
5023        assert_eq!(response.status(), StatusCode::OK);
5024        assert_eq!(
5025            resp_json(response).await,
5026            json!({
5027                "did": "did:web:pub.example.com", "handle": "pub.example.com", "active": true,
5028            })
5029        );
5030        assert_eq!(probe.calls.load(Ordering::SeqCst), 1);
5031    }
5032
5033    #[tokio::test]
5034    async fn router_get_session_validates_native_handle_syntax() {
5035        use std::sync::atomic::Ordering;
5036        if hyprstream_rpc::auth::global_credential_revocation_store().is_none() {
5037            let _ = hyprstream_rpc::auth::set_global_credential_revocation_store(Arc::new(
5038                hyprstream_rpc::auth::InMemoryCredentialRevocationStore::new(),
5039            ));
5040        }
5041        let mut state = build_test_state(true).await;
5042        let probe = Arc::new(SessionProbe {
5043            calls: 0.into(),
5044            handle: parking_lot::Mutex::new(String::new()),
5045        });
5046        Arc::get_mut(&mut state).unwrap().atproto_session_resolver = Some(probe.clone());
5047        let key = ed25519_dalek::SigningKey::from_bytes(&[0x76; 32]);
5048        Arc::get_mut(&mut state).unwrap().verifying_key_bytes = key.verifying_key().to_bytes();
5049        let issuer = state.atproto_issuer_url();
5050        let now = chrono::Utc::now().timestamp();
5051        let claims = hyprstream_rpc::auth::Claims::new(
5052            "did:web:pub.example.com".to_owned(),
5053            now,
5054            now + 3600,
5055        )
5056        .with_issuer(issuer.clone())
5057        .with_audience(Some(issuer))
5058        .with_tenant("session-tests".to_owned())
5059        .with_client_id("session-tests")
5060        .with_scope(Some("atproto".to_owned()))
5061        .with_jti();
5062        let token = hyprstream_rpc::auth::jwt::encode(&claims, &key);
5063        let app = build_production_app_from_state(state).await;
5064        let max_handle = format!(
5065            "{}.{}.{}.{}",
5066            "a".repeat(63),
5067            "b".repeat(63),
5068            "c".repeat(63),
5069            "d".repeat(61)
5070        );
5071        assert_eq!(max_handle.len(), 253);
5072        let invalid = [
5073            "",
5074            " ",
5075            "not-a-handle",
5076            "foo..example.com",
5077            ".example.com",
5078            "example.com.",
5079            "-foo.example.com",
5080            "foo-.example.com",
5081            "foo_bar.example.com",
5082            "foo.example.123",
5083            "foo.example.0a",
5084            "127.0.0.1",
5085            "[::1]",
5086            "@foo.example.com",
5087            "föo.example.com",
5088            "foo\n.example.com",
5089            "foo.example.com:443",
5090            ".invalid",
5091        ]
5092        .map(str::to_owned)
5093        .into_iter()
5094        .chain([
5095            format!("{}.example.com", "a".repeat(64)),
5096            format!("{max_handle}a"),
5097        ]);
5098        let valid = [
5099            "pub.example.com",
5100            "PUB.Example.COM",
5101            "8.cn",
5102            "a.co",
5103            "name.t--t",
5104            "xn--notarealidn.com",
5105            "xn--fiqa61au8b7zsevnm8ak20mc4a87e.xn--fiqs8s",
5106            // The reserved .invalid API sentinel is explicitly allowed by
5107            // the ATProto spec; it is not a claim of resolvable ownership.
5108            "handle.invalid",
5109        ]
5110        .map(str::to_owned)
5111        .into_iter()
5112        .chain([format!("{}.example.com", "a".repeat(63)), max_handle]);
5113        for (index, (handle, valid)) in invalid
5114            .map(|h| (h, false))
5115            .chain(valid.map(|h| (h, true)))
5116            .enumerate()
5117        {
5118            *probe.handle.lock() = handle.clone();
5119            let request = HttpRequest::builder()
5120                .uri("/xrpc/com.atproto.server.getSession")
5121                .header(header::AUTHORIZATION, format!("Bearer {token}"))
5122                .body(Body::empty())
5123                .unwrap();
5124            let response = app.clone().oneshot(request).await.unwrap();
5125            assert_eq!(probe.calls.load(Ordering::SeqCst), index + 1);
5126            assert_eq!(
5127                response.status(),
5128                if valid {
5129                    StatusCode::OK
5130                } else {
5131                    StatusCode::INTERNAL_SERVER_ERROR
5132                },
5133                "handle {handle:?}"
5134            );
5135            let body = resp_json(response).await;
5136            if valid {
5137                assert_eq!(
5138                    body,
5139                    json!({
5140                        "did": "did:web:pub.example.com", "handle": handle.to_ascii_lowercase(),
5141                        "active": true,
5142                    })
5143                );
5144            } else {
5145                assert_eq!(
5146                    body,
5147                    json!({
5148                        "error": errors::INTERNAL_SERVER_ERROR,
5149                        "message": "native account returned an invalid handle",
5150                    }),
5151                    "malformed authority value must not leak into the fixed error"
5152                );
5153            }
5154        }
5155    }
5156
5157    #[tokio::test]
5158    async fn router_get_session_preserves_open_lifecycle_status() {
5159        struct LifecycleProbe(parking_lot::Mutex<Option<String>>);
5160
5161        #[async_trait::async_trait]
5162        impl AtprotoSessionResolver for LifecycleProbe {
5163            async fn resolve_session(
5164                &self,
5165                did: &str,
5166            ) -> anyhow::Result<Option<AtprotoSessionInfo>> {
5167                assert_eq!(did, "did:web:pub.example.com");
5168                Ok(Some(AtprotoSessionInfo {
5169                    handle: "pub.example.com".to_owned(),
5170                    active: false,
5171                    status: self.0.lock().clone(),
5172                    ..Default::default()
5173                }))
5174            }
5175        }
5176
5177        if hyprstream_rpc::auth::global_credential_revocation_store().is_none() {
5178            let _ = hyprstream_rpc::auth::set_global_credential_revocation_store(Arc::new(
5179                hyprstream_rpc::auth::InMemoryCredentialRevocationStore::new(),
5180            ));
5181        }
5182        let mut state = build_test_state(true).await;
5183        let probe = Arc::new(LifecycleProbe(parking_lot::Mutex::new(None)));
5184        Arc::get_mut(&mut state).unwrap().atproto_session_resolver = Some(probe.clone());
5185        let key = ed25519_dalek::SigningKey::from_bytes(&[0x76; 32]);
5186        Arc::get_mut(&mut state).unwrap().verifying_key_bytes = key.verifying_key().to_bytes();
5187        let issuer = state.atproto_issuer_url();
5188        let now = chrono::Utc::now().timestamp();
5189        let claims = hyprstream_rpc::auth::Claims::new(
5190            "did:web:pub.example.com".to_owned(),
5191            now,
5192            now + 3600,
5193        )
5194        .with_issuer(issuer.clone())
5195        .with_audience(Some(issuer))
5196        .with_tenant("session-tests".to_owned())
5197        .with_client_id("session-tests")
5198        .with_scope(Some("atproto".to_owned()))
5199        .with_jti();
5200        let token = hyprstream_rpc::auth::jwt::encode(&claims, &key);
5201        let app = build_production_app_from_state(state).await;
5202        // The vendored getSession lexicon defines knownValues, not enum:
5203        // lifecycle strings from the trusted native authority remain open.
5204        for status in [
5205            None,
5206            Some("takendown"),
5207            Some("suspended"),
5208            Some("deactivated"),
5209            Some("Pending-Reactivation.v2"),
5210        ] {
5211            *probe.0.lock() = status.map(str::to_owned);
5212            let request = HttpRequest::builder()
5213                .uri("/xrpc/com.atproto.server.getSession")
5214                .header(header::AUTHORIZATION, format!("Bearer {token}"))
5215                .body(Body::empty())
5216                .unwrap();
5217            let response = app.clone().oneshot(request).await.unwrap();
5218            assert_eq!(response.status(), StatusCode::OK, "status {status:?}");
5219            let mut expected = json!({
5220                "did": "did:web:pub.example.com", "handle": "pub.example.com", "active": false,
5221            });
5222            if let Some(status) = status {
5223                expected["status"] = json!(status);
5224            }
5225            assert_eq!(resp_json(response).await, expected);
5226        }
5227    }
5228
5229    #[tokio::test]
5230    async fn router_get_session_not_mounted_without_native_resolver() {
5231        let app = build_xrpc_router().await;
5232        let resp = app
5233            .oneshot(req("/xrpc/com.atproto.server.getSession"))
5234            .await
5235            .unwrap();
5236        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
5237    }
5238
5239    // ── Finding 2: routed CID match/mismatch + malformed query ─────────────────
5240
5241    #[tokio::test]
5242    async fn router_get_record_cid_match_returns_record() {
5243        let state = build_test_state(true).await;
5244        let snap =
5245            sample_snapshot_fixed_tid("did:web:fixed.example.com", "fixed.example.com", true);
5246        let rkey = snap.records.keys().next().unwrap().encode();
5247        let cid = snap.records.values().next().unwrap().cid().to_string();
5248        state.xrpc_repos.put(snap).await.unwrap();
5249        let app = build_production_app_from_state(state).await;
5250        let uri = format!(
5251            "/xrpc/com.atproto.repo.getRecord?repo=did:web:fixed.example.com\
5252             &collection={HOSTED_COLLECTION}&rkey={rkey}&cid={cid}"
5253        );
5254        let resp = app.oneshot(req(&uri)).await.unwrap();
5255        assert_eq!(resp.status(), StatusCode::OK);
5256        let body = resp_json(resp).await;
5257        assert_eq!(body["cid"], cid);
5258        assert_eq!(body["value"]["$type"], HOSTED_COLLECTION);
5259    }
5260
5261    #[tokio::test]
5262    async fn router_get_record_cid_mismatch_returns_record_not_found() {
5263        let state = build_test_state(true).await;
5264        let snap =
5265            sample_snapshot_fixed_tid("did:web:fixed.example.com", "fixed.example.com", true);
5266        let rkey = snap.records.keys().next().unwrap().encode();
5267        state.xrpc_repos.put(snap).await.unwrap();
5268        let app = build_production_app_from_state(state).await;
5269        let uri = format!(
5270            "/xrpc/com.atproto.repo.getRecord?repo=did:web:fixed.example.com\
5271             &collection={HOSTED_COLLECTION}&rkey={rkey}\
5272             &cid=bafyreiwrongcid000000000000000000000000000000000000"
5273        );
5274        let resp = app.oneshot(req(&uri)).await.unwrap();
5275        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
5276        let body = resp_json(resp).await;
5277        assert_eq!(body["error"], errors::RECORD_NOT_FOUND);
5278        assert!(
5279            body["message"]
5280                .as_str()
5281                .unwrap()
5282                .contains("does not match cid"),
5283            "message must explain the cid mismatch: {}",
5284            body["message"]
5285        );
5286    }
5287
5288    #[tokio::test]
5289    async fn router_malformed_query_empty_repo() {
5290        let app = build_xrpc_router().await;
5291        // ?repo= — empty value at the wrapper boundary.
5292        let resp = app
5293            .clone()
5294            .oneshot(req("/xrpc/com.atproto.repo.getRecord?repo=\
5295                 &collection=ai.hyprstream.model&rkey=abc"))
5296            .await
5297            .unwrap();
5298        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
5299        let body = resp_json(resp).await;
5300        assert_eq!(body["error"], errors::INVALID_REQUEST);
5301        assert!(
5302            body["message"].as_str().unwrap().contains("repo"),
5303            "message must mention repo: {}",
5304            body["message"]
5305        );
5306    }
5307
5308    #[tokio::test]
5309    async fn router_bare_since_rejected() {
5310        // ?since (bare key, no =) must still be caught by since-rejection.
5311        let app = build_xrpc_router().await;
5312        let resp = app
5313            .clone()
5314            .oneshot(req(
5315                "/xrpc/com.atproto.sync.getRepo?did=did:web:pub.example.com&since",
5316            ))
5317            .await
5318            .unwrap();
5319        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
5320        let body = resp_json(resp).await;
5321        assert_eq!(body["error"], errors::INVALID_REQUEST);
5322    }
5323
5324    #[tokio::test]
5325    async fn router_percent_encoded_did_resolves() {
5326        // did%3Aweb%3Apub.example.com → did:web:pub.example.com (percent-decoded).
5327        let app = build_xrpc_router().await;
5328        let resp = app
5329            .clone()
5330            .oneshot(req(
5331                "/xrpc/com.atproto.repo.describeRepo?repo=did%3Aweb%3Apub.example.com",
5332            ))
5333            .await
5334            .unwrap();
5335        assert_eq!(resp.status(), StatusCode::OK);
5336        let body = resp_json(resp).await;
5337        assert_eq!(body["did"], "did:web:pub.example.com");
5338    }
5339}