Skip to main content

solid_pod_rs_server/
lib.rs

1//! # solid-pod-rs-server
2//!
3//! Drop-in Solid Pod server binary wrapping
4//! [`solid-pod-rs`](https://crates.io/crates/solid-pod-rs) with
5//! [actix-web](https://docs.rs/actix-web). This crate is both a
6//! library (for integration-test reuse) and a binary.
7//!
8//! ## Public types
9//!
10//! - [`AppState`]  — Shared actix-web application state (storage, dotfile policy, body cap).
11//! - [`build_app`] — Builds the fully-configured `actix_web::App` with all routes and middleware.
12//! - [`NodeInfoMeta`] — NodeInfo 2.1 metadata inputs.
13//! - [`PathTraversalGuard`] — Middleware that rejects `..` path-traversal attempts.
14//! - [`DotfileGuard`] — Middleware that enforces the dotfile allowlist.
15//! - [`ErrorLoggingMiddleware`] — Middleware that logs 5xx responses with full error chains.
16//! - [`body_cap_from_env`] — Reads `JSS_MAX_REQUEST_BODY` from the environment.
17//! - [`cli`] — CLI argument definitions (clap derive).
18//!
19//! ## Route table
20//!
21//! | Method   | Path                                     | Handler              |
22//! |----------|------------------------------------------|----------------------|
23//! | GET/HEAD | `/{tail:.*}`                             | `handle_get`         |
24//! | GET      | `/{folder}/*`                            | Glob merged Turtle   |
25//! | PUT      | `/{tail:.*}`                             | `handle_put`         |
26//! | PUT      | `/{tail:.*}/` + `Link: BasicContainer`   | Container creation   |
27//! | POST     | `/{tail:.*}/`                            | `handle_post`        |
28//! | PATCH    | `/{tail:.*}`                             | `handle_patch`       |
29//! | DELETE   | `/{tail:.*}`                             | `handle_delete`      |
30//! | COPY     | `/{tail:.*}` + `Source` header           | `handle_copy`        |
31//! | OPTIONS  | `/{tail:.*}`                             | `handle_options`     |
32//! | POST     | `/api/accounts/new`                      | Pod provisioning     |
33//! | GET      | `/pods/check/{name}`                     | Pod existence check  |
34//! | POST     | `/login/password`                        | Credentials login    |
35//! | POST     | `/account/password/reset`                | Password reset       |
36//! | POST     | `/account/password/change`               | Password change      |
37//! | GET      | `/.well-known/solid`                     | Solid discovery      |
38//! | GET      | `/.well-known/webfinger`                 | WebFinger JRD        |
39//! | GET      | `/.well-known/nodeinfo`                  | NodeInfo discovery   |
40//! | GET      | `/.well-known/nodeinfo/2.1`              | NodeInfo 2.1         |
41//! | GET      | `/.well-known/did/nostr/{pubkey}.json`   | DID:nostr document   |
42//! | GET      | `/pay/.info`                             | Payment discovery    |
43//! | GET      | `/pay/.balance`                          | Web-Ledger balance   |
44//! | POST     | `/pay/.deposit`                          | TXO + MRC20 deposit  |
45//! | GET      | `/pay/.address`                          | Tweaked deposit addr |
46//! | GET/POST | `/pay/.offers` `.sell` `.swap` `.pool`   | Order book + AMM     |
47//! | POST     | `/pay/.buy` `.withdraw` `.withdraw-sats` | Token mint/voucher   |
48//! | GET      | `/{pod}/{path}.prov.ttl`                 | PROV-O git-mark sidecar |
49//! | GET      | `/{pod}/_prov/{commit_sha}`              | Resolve a git-mark   |
50//! | POST     | `/{pod}/_prov/anchor`                    | Upgrade to Bitcoin anchor |
51//! | GET      | `/api/exports/all`                       | JSON-LD pod export (`export-jsonld`, `acl:Control`-gated) |
52//! | GET/POST | `/{pod}/info/refs` `…/git-{upload,receive}-pack` | Git smart-HTTP (WAC-gated) |
53//! | GET/POST | `/forge` `/forge/{tail:.*}`               | Git forge — browse, issues, push tokens (`forge` feature, namespace-scoped, not WAC-gated) |
54//!
55//! The `/pay/*` HTTP-402 economy routes (`handlers::pay`) wire the
56//! `solid-pod-rs` Web-Ledger / order-book / AMM core onto actix; the `_prov`
57//! routes (`handlers::prov`, `--features git`) expose the git-mark +
58//! block-trail provenance API (ADR-059). Block-trail anchor verification and
59//! broadcast go through the native [`mempool`] client (mempool.space testnet4
60//! by default), with trail persistence via [`trail_store`]. Every LDP
61//! `PUT`/`POST`/`PATCH` to a git-backed pod additionally fires the always-on
62//! git-mark write hook (`git_mark_write`, when built with `--features git`).
63//!
64//! The `/forge/*` git forge (JSS `forge` plugin port; `solid_pod_rs_forge`)
65//! is mounted under `--features forge`, which implies `git` (the forge
66//! reuses the smart-HTTP CGI). `forge-anchoring` adds the Blocktrails tier
67//! (`solid_pod_rs::mrc20`); `forge-announce` adds NIP-34 discovery
68//! publication over `solid-pod-rs-nostr`. Forge routes are registered
69//! *before* the pod-git smart-HTTP catch-all so
70//! `/forge/<owner>/<repo>.git/info/refs` resolves to the forge's own CGI
71//! forwarding rather than the pod-git handler. Unlike `handle_git`, the
72//! forge does **not** go through the pod's WAC ACL evaluator: it enforces
73//! its own fail-closed namespace-ownership guard (an agent may only
74//! push/comment into the namespace matching its own `did:nostr` pubkey or
75//! pod username; see `solid_pod_rs_forge::ownership`) plus an own-area SSRF
76//! check on pod-hosted issue/PR bodies. Repository browsing (tree/blob/
77//! commits/issues list) is unauthenticated-public by design.
78//!
79//! ## Middleware stack (applied in order)
80//!
81//! 1. `NormalizePath` -- collapse `//` and decode %-encoded segments.
82//! 2. `PathTraversalGuard` -- defence-in-depth `..` re-check.
83//! 3. `DotfileGuard` -- rejects `.env` etc unless on the allowlist.
84//! 4. `PayloadConfig` -- enforces `JSS_MAX_REQUEST_BODY` body cap.
85//! 5. `ErrorLoggingMiddleware` -- structured 5xx logging.
86//! 6. WAC-on-write -- PUT/POST/PATCH/DELETE require a write/append grant.
87//!
88//! ## Security posture (closeout, 0.5.0-alpha.4)
89//!
90//! - **NIP-98 single-use replay guard** — every request runs through a
91//!   shared process-local `Nip98ReplayCache`, so a captured token cannot be
92//!   replayed within the ±120s NIP-98 tolerance window (`extract_pubkey`
93//!   returns `None` on a replayed id → the WAC gate denies with 401). TTL /
94//!   size via `SOLID_POD_NIP98_REPLAY_TTL_SECS` / `SOLID_POD_NIP98_REPLAY_MAX_SIZE`.
95//!   The cache is per-process; multi-replica deployments share no state.
96//! - **Fail-open compile guard** — this binary references
97//!   `solid_pod_rs::auth::nip98::assert_schnorr_verification_enabled` in const
98//!   context, so a build that ever dropped BIP-340 signature verification from
99//!   the NIP-98 verifier is a **compile error**, not a silently fail-open
100//!   server.
101//! - **WAC `acl:origin` gate** — the request `Origin` header is threaded into
102//!   the evaluator (`enforce_read_ctx` / `enforce_write_ctx`), so ACLs bearing
103//!   `acl:origin` triples gate cross-origin access. Plain ACLs are unaffected;
104//!   `acl:Control` bypasses the origin gate by design.
105
106#![doc = include_str!("../README.md")]
107#![deny(unsafe_code)]
108#![warn(rust_2018_idioms)]
109
110#[cfg(feature = "activitypub")]
111pub mod activitypub;
112/// CLI argument definitions (clap derive structs).
113pub mod cli;
114pub mod cross_identity;
115pub mod scheme;
116
117pub(crate) mod hardened_git;
118
119/// HTTP request handlers grouped by domain. Currently hosts the payment
120/// routing layer ([`handlers::pay`]) which wires the orphaned
121/// `solid-pod-rs` order-book / AMM / Web-Ledger logic onto actix routes
122/// with JSS-parity JSON.
123mod handlers;
124
125#[cfg(feature = "jev")]
126pub mod jev;
127/// MCP (Model Context Protocol) server subsystem — `POST /mcp`, mounted
128/// only when [`AppState::mcp_enabled`] (`--mcp` / `JSS_MCP`, JSS #490).
129mod mcp;
130
131/// Native mempool.space REST client (provenance-upgrade Phase 3). Concrete
132/// [`solid_pod_rs::mrc20::MempoolLookup`] + the verify-side
133/// [`solid_pod_rs::provenance::BlockAnchorer`]. Server-side only (builds a
134/// `reqwest::Client`); wasm consumers implement the trait over `fetch`.
135pub mod mempool;
136
137/// MRC20 trail persistence (provenance-upgrade Phase 4). Loads/saves a
138/// token's Bitcoin-anchored state chain at `/.well-known/token/{ticker}.json`
139/// via the pod's [`solid_pod_rs::storage::Storage`] backend (JSS
140/// `token.js:189-208`). Native-only; holds the issuer secret off the public
141/// [`solid_pod_rs::mrc20::Mrc20Trail`] type.
142pub mod trail_store;
143
144use std::collections::HashMap;
145use std::net::{IpAddr, Ipv4Addr};
146use std::path::{Path, PathBuf};
147use std::sync::{Arc, Mutex};
148use std::time::{Duration, Instant};
149
150use actix_web::body::{BoxBody, EitherBody};
151use actix_web::dev::{Service, ServiceRequest, ServiceResponse, Transform};
152use actix_web::http::{header, StatusCode};
153use actix_web::middleware::{NormalizePath, TrailingSlash};
154use actix_web::{web, App, Error as ActixError, HttpRequest, HttpResponse};
155use bytes::Bytes;
156use futures_util::future::{ready, LocalBoxFuture, Ready};
157use futures_util::StreamExt;
158use percent_encoding::percent_decode_str;
159use serde::Deserialize;
160use solid_pod_rs::{
161    // `ReplayStore` is the seam the process-local replay cache implements
162    // (ADR-060 Decision 2); it must be in scope to call `check_and_record`
163    // through the trait rather than an inherent method.
164    auth::{nip98, replay::ReplayStore},
165    config::sources::parse_size,
166    interop,
167    ldp::{
168        self, cache_control_for_response, LdpContainerOps, PatchCreateOutcome, ResponseAudience,
169    },
170    mashlib::{self, MashlibConfig},
171    provenance::{ProvenanceReceipt, ProvenanceSkip},
172    security::DotfileAllowlist,
173    storage::Storage,
174    wac::{
175        self, conditions::RequestContext, effective_acl_target, parse_jsonld_acl,
176        parser::parse_turtle_acl, protected_resource_for_acl, AccessMode,
177    },
178    PodError,
179};
180
181// ---------------------------------------------------------------------------
182// F3 compile guard — refuse to build a fail-open NIP-98 auth path.
183// ---------------------------------------------------------------------------
184//
185// `assert_schnorr_verification_enabled` is a `const fn` that exists ONLY
186// under the core crate's `nip98-schnorr` feature. Referencing it in const
187// context here makes this binary impossible to build if BIP-340 signature
188// verification is ever dropped from the NIP-98 verifier — a dependency
189// change or a feature-unification regression that removed it becomes a
190// compile error rather than a server that silently accepts any forged
191// pubkey after structural checks alone.
192const _: () = solid_pod_rs::auth::nip98::assert_schnorr_verification_enabled();
193
194/// Process-local NIP-98 single-use replay guard (F3). Shared across every
195/// request in this server process; a captured token cannot be replayed
196/// within the ~120s NIP-98 tolerance window. TTL/size are overridable via
197/// `SOLID_POD_NIP98_REPLAY_TTL_SECS` / `SOLID_POD_NIP98_REPLAY_MAX_SIZE`.
198/// See `solid_pod_rs::auth::replay` for the tier persistence limit
199/// (process-local; multi-replica deployments share no state).
200static NIP98_REPLAY: std::sync::LazyLock<solid_pod_rs::auth::replay::Nip98ReplayCache> =
201    std::sync::LazyLock::new(solid_pod_rs::auth::replay::Nip98ReplayCache::from_env);
202
203/// Serialises every local payment-state transition in this process. The
204/// storage API has no cross-resource CAS primitive, so handlers must hold
205/// this guard across replay checks, ledger/order/pool/trail mutation, and
206/// persistence. Durable intent records add crash recovery where an external
207/// broadcast is involved.
208pub(crate) static PAYMENT_STATE_LOCK: std::sync::LazyLock<tokio::sync::Mutex<()>> =
209    std::sync::LazyLock::new(|| tokio::sync::Mutex::new(()));
210
211// ---------------------------------------------------------------------------
212// Shared app state
213// ---------------------------------------------------------------------------
214
215/// Actix-web shared state.
216#[derive(Clone)]
217pub struct AppState {
218    pub storage: Arc<dyn Storage>,
219    pub dotfiles: Arc<DotfileAllowlist>,
220    pub body_cap: usize,
221    pub nodeinfo: NodeInfoMeta,
222    pub mashlib: MashlibConfig,
223    /// Legacy alias — reads from `mashlib.mode` when `Cdn`.  Deprecated;
224    /// use `mashlib` directly.
225    pub mashlib_cdn: Option<String>,
226    /// Inject a development-only WebSocket reload client into HTML responses.
227    pub live_reload: bool,
228    /// Payment configuration — drives `/pay/.info` and the `X-Balance` /
229    /// `X-Cost` / `X-Pay-Currency` response headers on paid resources.
230    pub pay_config: solid_pod_rs::payments::PayConfig,
231    /// Absolute filesystem root of the pod storage tree. `Some` when the
232    /// backend is `FsBackend`; `None` for in-memory or cloud-backed
233    /// storage. Required by the `git` feature to locate pod directories
234    /// for `GitAutoInit` (provisioning) and `GitHttpService` (serving).
235    pub data_root: Option<PathBuf>,
236    /// Optional atomic per-pod quota policy applied to every LDP mutation.
237    pub quota: Option<Arc<dyn solid_pod_rs::quota::QuotaPolicy>>,
238    /// JSS-compatible pod creation limiter: one `POST /.pods` per IP per day.
239    pub pod_create_limiter: Arc<PodCreateLimiter>,
240    /// When non-empty, CORS responses are only reflected for origins in this
241    /// list. Origins not in the list receive no `Access-Control-Allow-Origin`
242    /// header. When empty (the default), the request `Origin` is echoed back
243    /// (wildcard-equivalent behaviour, suitable for local dev).
244    ///
245    /// Configured via `--allowed-origins` / `SOLID_ALLOWED_ORIGINS` (comma-separated).
246    pub allowed_origins: Vec<String>,
247    /// Pre-shared key for the `POST /_admin/provision/{pubkey}` endpoint.
248    /// When `None`, the endpoint returns 403 unconditionally.
249    ///
250    /// Configured via `--admin-key` / `SOLID_ADMIN_KEY`.
251    pub admin_key: Option<String>,
252    /// When true, the MCP (Model Context Protocol) server is mounted at
253    /// `POST /mcp`, exposing the pod as a tool surface for agents. OFF by
254    /// default — keys-on-disk and agent write access are an opt-in
255    /// security tradeoff. Configured via `--mcp` / `JSS_MCP` (JSS #490).
256    pub mcp_enabled: bool,
257    /// Optional override for the mempool REST base URL used by the MRC20
258    /// `/pay/.deposit` anchor verification (provenance-upgrade Phase 3).
259    /// `None` ⇒ the handler reads `JSS_PAY_MEMPOOL_URL` (default testnet4).
260    /// Tests point this at a local fixture server so they never reach
261    /// mempool.space; production leaves it `None`.
262    pub mempool_url: Option<String>,
263    /// Content negotiation (JSS `--conneg`). When on, `text/n3` is accepted
264    /// and advertised alongside Turtle for request bodies; when off a
265    /// `text/n3` body is refused with 415 as in JSS `canAcceptInput`.
266    pub conneg_enabled: bool,
267    /// Honour `X-Forwarded-Proto` / `cf-visitor` for the request scheme and
268    /// `X-Forwarded-Host` / `Forwarded` for the host.
269    /// Off by default: only enable behind a proxy that overwrites them.
270    pub trust_proxy: bool,
271    /// Public base URL of this server (`JSS_PUBLIC_BASE_URL`). When set it
272    /// is the origin used for NIP-98 URL matching and every generated
273    /// absolute URL, whatever `Host` or forwarding headers say.
274    pub public_base_url: Option<String>,
275    /// Hosts this server answers for (`JSS_ALLOWED_HOSTS`). Empty permits
276    /// any `Host`; otherwise a request for another host gets `421`.
277    pub allowed_hosts: Vec<String>,
278    /// did:nostr to WebID resolver applied to NIP-98 callers. `None`
279    /// disables cross-identity (the caller is the `did:nostr` agent only).
280    pub cross_identity: Option<Arc<dyn cross_identity::CrossIdentityResolver>>,
281    /// ActivityPub actor provider; `Some` mounts the actor route (set by the
282    /// `activitypub` feature's `ApConfig`; always `None` otherwise).
283    pub activitypub: Option<Arc<dyn ActorDocument>>,
284}
285
286/// Source of the ActivityPub actor document served at
287/// `GET /profile/card.jsonld` for activity+json requests.
288pub trait ActorDocument: Send + Sync {
289    /// The actor JSON for the site at `base_url` (`scheme://host`).
290    fn actor_json(&self, base_url: &str) -> serde_json::Value;
291}
292
293#[cfg(test)]
294mod nip98_request_binding_tests {
295    use super::*;
296    use actix_web::test::TestRequest;
297
298    const SECRET: &str = "3333333333333333333333333333333333333333333333333333333333333333";
299
300    fn now() -> u64 {
301        std::time::SystemTime::now()
302            .duration_since(std::time::UNIX_EPOCH)
303            .unwrap()
304            .as_secs()
305    }
306
307    #[actix_web::test]
308    async fn authentication_binds_the_complete_query_string() {
309        let signed_url = "http://localhost:8080/private?include=true";
310        let token = nip98::mint(signed_url, "GET", SECRET, now()).unwrap();
311        let request = TestRequest::get()
312            .uri("/private?include=true")
313            .insert_header((header::AUTHORIZATION, format!("Nostr {token}")))
314            .to_http_request();
315        assert!(extract_pubkey(&request).await.is_some());
316
317        let path_only = nip98::mint("http://localhost:8080/private", "GET", SECRET, now()).unwrap();
318        let request = TestRequest::get()
319            .uri("/private?include=true")
320            .insert_header((header::AUTHORIZATION, format!("Nostr {path_only}")))
321            .to_http_request();
322        assert!(extract_pubkey(&request).await.is_none());
323    }
324
325    #[actix_web::test]
326    async fn authentication_binds_the_exact_raw_body() {
327        let expected = br#"{"value":"authorised"}"#;
328        let token = nip98::mint_with_payload(
329            "http://localhost:8080/resource",
330            "PUT",
331            Some(expected),
332            SECRET,
333            now(),
334        )
335        .unwrap();
336        let request = TestRequest::put()
337            .uri("/resource")
338            .insert_header((header::AUTHORIZATION, format!("Nostr {token}")))
339            .to_http_request();
340
341        assert!(
342            extract_pubkey_with_body(&request, Some(br#"{"value":"tampered"}"#))
343                .await
344                .is_none()
345        );
346        assert!(extract_pubkey_with_body(&request, Some(expected))
347            .await
348            .is_some());
349    }
350}
351
352/// NodeInfo 2.1 body inputs. Kept here so tests can override them.
353#[derive(Clone, Debug)]
354pub struct NodeInfoMeta {
355    pub software_name: String,
356    pub software_version: String,
357    pub open_registrations: bool,
358    pub total_users: u64,
359    pub base_url: String,
360}
361
362impl Default for NodeInfoMeta {
363    fn default() -> Self {
364        Self {
365            software_name: "solid-pod-rs-server".to_string(),
366            software_version: env!("CARGO_PKG_VERSION").to_string(),
367            open_registrations: false,
368            total_users: 0,
369            base_url: "http://localhost".to_string(),
370        }
371    }
372}
373
374/// Discover the body cap from the environment. Accepts values like
375/// `50MB`, `1.5GB`, or a bare integer (bytes). Falls back to 50 MiB.
376pub const DEFAULT_BODY_CAP: usize = 50 * 1024 * 1024;
377
378/// Read `JSS_MAX_REQUEST_BODY` (or, as a drop-in-config alias, upstream
379/// JSS's `JSS_BODY_LIMIT`, #474/#543) and parse via [`parse_size`]. The
380/// canonical name wins when both are set. On any failure, returns
381/// [`DEFAULT_BODY_CAP`].
382pub fn body_cap_from_env() -> usize {
383    match std::env::var("JSS_MAX_REQUEST_BODY").or_else(|_| std::env::var("JSS_BODY_LIMIT")) {
384        Ok(v) => parse_size(&v)
385            .map(|u| u as usize)
386            .unwrap_or(DEFAULT_BODY_CAP),
387        Err(_) => DEFAULT_BODY_CAP,
388    }
389}
390
391impl AppState {
392    /// The configured public origin (`scheme://authority`), if any.
393    pub fn public_origin(&self) -> Option<String> {
394        self.public_base_url
395            .as_deref()
396            .and_then(scheme::normalise_origin)
397    }
398
399    /// Convenience constructor for tests and the binary. Callers may
400    /// replace fields after creation since `AppState` is a plain struct.
401    pub fn new(storage: Arc<dyn Storage>) -> Self {
402        Self {
403            storage,
404            dotfiles: Arc::new(DotfileAllowlist::from_env()),
405            body_cap: body_cap_from_env(),
406            nodeinfo: NodeInfoMeta::default(),
407            mashlib: MashlibConfig::default(),
408            mashlib_cdn: None,
409            live_reload: false,
410            pay_config: solid_pod_rs::payments::PayConfig::default(),
411            data_root: None,
412            quota: None,
413            pod_create_limiter: Arc::new(PodCreateLimiter::default()),
414            allowed_origins: Vec::new(),
415            admin_key: None,
416            mcp_enabled: false,
417            mempool_url: None,
418            conneg_enabled: false,
419            trust_proxy: false,
420            public_base_url: None,
421            allowed_hosts: Vec::new(),
422            cross_identity: None,
423            activitypub: None,
424        }
425    }
426}
427
428const LIVE_RELOAD_SCRIPT: &str = "<script>(function(){var ws=new WebSocket((location.protocol==='https:'?'wss:':'ws:')+'//'+location.host+'/.notifications');ws.onopen=function(){ws.send('sub '+location.href)};ws.onmessage=function(e){if(e.data.startsWith('pub '))location.reload()};ws.onclose=function(){setTimeout(function(){location.reload()},1000)}})();</script>";
429
430fn inject_live_reload(html: impl AsRef<[u8]>, enabled: bool) -> Vec<u8> {
431    let bytes = html.as_ref();
432    if !enabled {
433        return bytes.to_vec();
434    }
435    let html = String::from_utf8_lossy(bytes);
436    if let Some(index) = html.find("</body>") {
437        let mut out = String::with_capacity(html.len() + LIVE_RELOAD_SCRIPT.len());
438        out.push_str(&html[..index]);
439        out.push_str(LIVE_RELOAD_SCRIPT);
440        out.push_str(&html[index..]);
441        out.into_bytes()
442    } else {
443        format!("{html}{LIVE_RELOAD_SCRIPT}").into_bytes()
444    }
445}
446
447#[cfg(test)]
448mod live_reload_tests {
449    use super::*;
450
451    #[test]
452    fn injects_before_body_close_and_is_disabled_by_default() {
453        let html = b"<html><body>ok</body></html>";
454        assert_eq!(inject_live_reload(html, false), html);
455        let injected = String::from_utf8(inject_live_reload(html, true)).unwrap();
456        assert!(injected.contains("/.notifications"));
457        assert!(injected.find("<script>").unwrap() < injected.find("</body>").unwrap());
458    }
459}
460
461#[cfg(all(test, feature = "dev-bearer"))]
462mod dev_bearer_tests {
463    use super::*;
464    use base64::Engine as _;
465    use hmac::{Hmac, Mac};
466    use sha2::Sha256;
467    use std::sync::Mutex;
468
469    static ENV: Mutex<()> = Mutex::new(());
470
471    fn now() -> u64 {
472        std::time::SystemTime::now()
473            .duration_since(std::time::UNIX_EPOCH)
474            .unwrap()
475            .as_secs()
476    }
477
478    fn token_with(iat: u64, exp: u64, aud: Option<&str>) -> String {
479        let mut claims = serde_json::json!({"webId":"https://alice.example/profile/card#me","iat":iat,"exp":exp});
480        if let Some(a) = aud {
481            claims["aud"] = serde_json::json!(a);
482        }
483        let data = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(claims.to_string());
484        let mut mac = Hmac::<Sha256>::new_from_slice(b"01234567890123456789012345678901").unwrap();
485        mac.update(data.as_bytes());
486        let sig =
487            base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(mac.finalize().into_bytes());
488        format!("{data}.{sig}")
489    }
490
491    fn token(exp: u64) -> String {
492        token_with(now().saturating_sub(10), exp, Some(DEV_BEARER_AUDIENCE))
493    }
494
495    #[test]
496    fn simple_bearer_verifies_signature_and_expiry() {
497        let _guard = ENV.lock().unwrap();
498        std::env::set_var("TOKEN_SECRET", "01234567890123456789012345678901");
499        assert_eq!(
500            verify_dev_bearer(&token(now() + 3600)).as_deref(),
501            Some("https://alice.example/profile/card#me")
502        );
503        assert!(verify_dev_bearer(&(token(now() + 3600) + "x")).is_none());
504        assert!(verify_dev_bearer(&token(2)).is_none());
505        std::env::remove_var("TOKEN_SECRET");
506    }
507
508    #[test]
509    fn dev_bearer_enforces_audience_and_max_lifetime() {
510        let _guard = ENV.lock().unwrap();
511        std::env::set_var("TOKEN_SECRET", "01234567890123456789012345678901");
512        let n = now();
513        // Missing and wrong audience are refused.
514        assert!(verify_dev_bearer(&token_with(n, n + 60, None)).is_none());
515        assert!(verify_dev_bearer(&token_with(n, n + 60, Some("solid"))).is_none());
516        // Exactly 24 h is the ceiling; one second more is refused.
517        assert!(verify_dev_bearer(&token_with(
518            n,
519            n + DEV_BEARER_MAX_LIFETIME_SECS,
520            Some(DEV_BEARER_AUDIENCE)
521        ))
522        .is_some());
523        assert!(verify_dev_bearer(&token_with(
524            n,
525            n + DEV_BEARER_MAX_LIFETIME_SECS + 1,
526            Some(DEV_BEARER_AUDIENCE)
527        ))
528        .is_none());
529        // A back-dated iat cannot stretch the lifetime beyond 24 h from now.
530        assert!(verify_dev_bearer(&token_with(1, n + 3600, Some(DEV_BEARER_AUDIENCE))).is_none());
531        assert!(
532            verify_dev_bearer(&token_with(1, u64::MAX / 2, Some(DEV_BEARER_AUDIENCE))).is_none()
533        );
534        std::env::remove_var("TOKEN_SECRET");
535    }
536}
537
538/// In-process sliding-window limiter for JSS-compatible `POST /.pods`.
539#[derive(Debug)]
540pub struct PodCreateLimiter {
541    hits: Mutex<HashMap<IpAddr, Instant>>,
542    window: Duration,
543}
544
545impl Default for PodCreateLimiter {
546    fn default() -> Self {
547        Self {
548            hits: Mutex::new(HashMap::new()),
549            window: Duration::from_secs(24 * 60 * 60),
550        }
551    }
552}
553
554impl PodCreateLimiter {
555    fn check(&self, ip: IpAddr) -> Result<(), u64> {
556        let now = Instant::now();
557        let mut hits = self.hits.lock().unwrap();
558        if let Some(last) = hits.get(&ip).copied() {
559            let elapsed = now.saturating_duration_since(last);
560            if elapsed < self.window {
561                return Err(self.window.saturating_sub(elapsed).as_secs().max(1));
562            }
563        }
564        hits.insert(ip, now);
565        Ok(())
566    }
567}
568
569// ---------------------------------------------------------------------------
570// Error translation
571// ---------------------------------------------------------------------------
572
573pub(crate) fn to_actix(e: PodError) -> ActixError {
574    match e {
575        PodError::NotFound(_) => actix_web::error::ErrorNotFound(e.to_string()),
576        PodError::BadRequest(_) => actix_web::error::ErrorBadRequest(e.to_string()),
577        PodError::Unsupported(_) => actix_web::error::ErrorUnsupportedMediaType(e.to_string()),
578        PodError::Forbidden => actix_web::error::ErrorForbidden(e.to_string()),
579        PodError::Unauthenticated => actix_web::error::ErrorUnauthorized(e.to_string()),
580        PodError::PreconditionFailed(_) => actix_web::error::ErrorPreconditionFailed(e.to_string()),
581        _ => actix_web::error::ErrorInternalServerError(e.to_string()),
582    }
583}
584
585// ---------------------------------------------------------------------------
586// Auth helper — shared across handlers
587// ---------------------------------------------------------------------------
588
589/// Attempt NIP-98 bearer verification; returns the pubkey on success.
590///
591/// Runs the full structural + BIP-340 signature check and then a
592/// **single-use replay check** on the canonical event id: a token whose id
593/// was already seen within the replay window is rejected (returns `None`,
594/// i.e. treated as unauthenticated → the WAC gate denies with 401). This
595/// closes the ~120s replay window the stateless verifier leaves open.
596pub(crate) async fn extract_pubkey(req: &HttpRequest) -> Option<String> {
597    extract_pubkey_with_body(req, None).await
598}
599
600/// NIP-98 verification for a request whose raw body is available.
601/// Supplying the bytes requires a signature-bound `payload` tag and prevents
602/// an otherwise valid token from being replayed with altered content.
603pub(crate) async fn extract_pubkey_with_body(
604    req: &HttpRequest,
605    body: Option<&[u8]>,
606) -> Option<String> {
607    let header_val = req
608        .headers()
609        .get(header::AUTHORIZATION)
610        .and_then(|v| v.to_str().ok())?;
611    if let Some(_token) = header_val.strip_prefix("Bearer ") {
612        // The home-made HMAC bearer exists only in `dev-bearer` builds.
613        // Production builds treat every `Bearer` header as unauthenticated.
614        #[cfg(feature = "dev-bearer")]
615        return verify_dev_bearer(_token);
616        #[cfg(not(feature = "dev-bearer"))]
617        return None;
618    }
619    // Reconstruct the request URL the NIP-98 event was signed over. The
620    // scheme must reflect the externally-visible scheme (honouring
621    // `X-Forwarded-Proto`, only behind `trust_proxy`) — a pod behind TLS
622    // or a federation reverse proxy is reached at `https://`, and the agent
623    // signs that URL. Hardcoding `http://` would break URL matching for
624    // every TLS-fronted deployment. Mirrors the base-URI construction used
625    // elsewhere in this file (see `conn.scheme()` call sites).
626    // Scope the actix `Ref<ConnectionInfo>` guard to a block so it is dropped
627    // before the `.await` below (clippy::await_holding_refcell_ref keys on
628    // lexical scope, not liveness, so an explicit `drop` does not suffice).
629    // Origin from configuration or the plain Host header, never from
630    // client-controlled forwarding headers (`scheme::request_url`).
631    let url = scheme::request_url(req);
632    let now = std::time::SystemTime::now()
633        .duration_since(std::time::UNIX_EPOCH)
634        .map(|d| d.as_secs())
635        .unwrap_or(0);
636    let verified = nip98::verify_at(header_val, &url, req.method().as_str(), body, now).ok()?;
637
638    // F3 replay guard: reject a re-presented token. The event id is the
639    // signature-bound single-use nonce; a hit means the same signed request
640    // was already accepted within the replay window. Fail closed.
641    if NIP98_REPLAY
642        .check_and_record(&verified.event_id)
643        .await
644        .is_err()
645    {
646        tracing::warn!(
647            pubkey = %verified.pubkey,
648            method = %req.method(),
649            "NIP-98 replay rejected: token id already used within window"
650        );
651        return None;
652    }
653
654    Some(verified.pubkey)
655}
656
657pub(crate) fn agent_uri(pubkey: Option<&String>) -> Option<String> {
658    pubkey.map(|pk| {
659        if pk.starts_with("https://") || pk.starts_with("http://") {
660            pk.clone()
661        } else {
662            format!("did:nostr:{pk}")
663        }
664    })
665}
666
667/// Audience a development bearer token must carry in its `aud` claim.
668#[cfg(feature = "dev-bearer")]
669pub const DEV_BEARER_AUDIENCE: &str = "solid-pod-rs-dev-bearer";
670
671/// Hard ceiling on a development bearer token's lifetime (24 h), applied to
672/// both `exp - iat` and `exp - now`.
673#[cfg(feature = "dev-bearer")]
674pub const DEV_BEARER_MAX_LIFETIME_SECS: u64 = 24 * 60 * 60;
675
676/// Verify the development-only HMAC bearer (`<b64url claims>.<b64url mac>`,
677/// HMAC-SHA256 keyed by `TOKEN_SECRET`, ≥ 32 bytes).
678///
679/// Compiled only with the `dev-bearer` cargo feature (off by default). Even
680/// then the token must carry `aud == DEV_BEARER_AUDIENCE` and live at most
681/// 24 h. There is no replay guard: it is a development convenience, not an
682/// authentication scheme for production.
683#[cfg(feature = "dev-bearer")]
684fn verify_dev_bearer(token: &str) -> Option<String> {
685    use base64::Engine as _;
686    use hmac::{Hmac, Mac};
687    use sha2::Sha256;
688
689    let secret = std::env::var("TOKEN_SECRET").ok()?;
690    if secret.len() < 32 {
691        tracing::warn!("TOKEN_SECRET shorter than 32 bytes; refusing development bearer token");
692        return None;
693    }
694    let (data, signature) = token.split_once('.')?;
695    if signature.contains('.') {
696        return None;
697    }
698    let signature = base64::engine::general_purpose::URL_SAFE_NO_PAD
699        .decode(signature)
700        .ok()?;
701    let mut mac = Hmac::<Sha256>::new_from_slice(secret.as_bytes()).ok()?;
702    mac.update(data.as_bytes());
703    mac.verify_slice(&signature).ok()?;
704
705    #[derive(serde::Deserialize)]
706    #[serde(rename_all = "camelCase")]
707    struct Claims {
708        web_id: String,
709        iat: u64,
710        exp: u64,
711        #[serde(default)]
712        aud: Option<String>,
713    }
714    let payload = base64::engine::general_purpose::URL_SAFE_NO_PAD
715        .decode(data)
716        .ok()?;
717    let claims: Claims = serde_json::from_slice(&payload).ok()?;
718    let now = std::time::SystemTime::now()
719        .duration_since(std::time::UNIX_EPOCH)
720        .ok()?
721        .as_secs();
722    if claims.aud.as_deref() != Some(DEV_BEARER_AUDIENCE) {
723        return None;
724    }
725    if claims.exp < now || claims.iat > now.saturating_add(60) || claims.exp <= claims.iat {
726        return None;
727    }
728    if claims.exp - claims.iat > DEV_BEARER_MAX_LIFETIME_SECS
729        || claims.exp - now > DEV_BEARER_MAX_LIFETIME_SECS
730    {
731        return None;
732    }
733    let url = url::Url::parse(&claims.web_id).ok()?;
734    if !matches!(url.scheme(), "http" | "https") || url.host_str().is_none() {
735        return None;
736    }
737    Some(claims.web_id)
738}
739
740/// The request `Origin` header value, if present and valid UTF-8.
741///
742/// Threaded into the WAC `acl:origin` gate (F4) via the `enforce_*_ctx`
743/// paths so an ACL that declares `acl:origin` triples can restrict
744/// cross-origin access (CSRF defence). Requests without an `Origin` header
745/// (server-to-server, git smart-protocol, curl) yield `None`, which the
746/// evaluator rejects only for resources whose ACL explicitly restricts
747/// origins — plain ACLs (no `acl:origin`) are unaffected.
748fn req_origin(req: &HttpRequest) -> Option<&str> {
749    req.headers()
750        .get(header::ORIGIN)
751        .and_then(|v| v.to_str().ok())
752}
753
754/// Canonical pod-relative path of the Web Ledger document. The
755/// `acl:PaymentCondition` evaluator is fed the requesting principal's
756/// satoshi balance read from this resource.
757pub(crate) const WEBLEDGER_PATH: &str = "/.well-known/webledgers/webledgers.json";
758
759/// Resolve the requesting principal's satoshi balance from the pod's
760/// Web Ledger so the WAC `acl:PaymentCondition` evaluator receives a
761/// concrete value instead of `None`.
762///
763/// Returns:
764/// * `None` when there is no authenticated principal (anonymous request)
765///   — a `PaymentCondition` then fails closed (402/403);
766/// * `Some(0)` when the principal is authenticated but has no ledger
767///   entry (or no ledger exists yet) — sufficient to satisfy only a
768///   zero-cost condition;
769/// * `Some(balance)` resolved from the ledger entry keyed by the
770///   principal's `did:nostr` URI otherwise.
771///
772/// The lookup is keyed by the authenticated principal's WebID, which for
773/// a NIP-98 caller is `did:nostr:<hex-pubkey>` — the same key the
774/// `/pay/.deposit` credit path writes into the ledger.
775async fn resolve_balance_sats(storage: &dyn Storage, agent_uri: Option<&str>) -> Option<u64> {
776    let did = agent_uri?;
777    let balance = match storage.get(WEBLEDGER_PATH).await {
778        Ok((bytes, _meta)) => {
779            match serde_json::from_slice::<solid_pod_rs::payments::WebLedger>(&bytes) {
780                Ok(ledger) => ledger.get_balance(did),
781                // A malformed ledger document must not crash the auth
782                // path; treat it as an empty balance (fail-closed for
783                // any non-zero PaymentCondition).
784                Err(_) => 0,
785            }
786        }
787        // No ledger provisioned yet: authenticated principal with zero
788        // balance.
789        Err(_) => 0,
790    };
791    Some(balance)
792}
793
794/// Return `true` when the `Accept` header includes `text/html`.
795///
796/// Used for container `index.html` content negotiation: if a browser
797/// requests `text/html` on a container URL and that container contains
798/// an `index.html` resource, the server serves the HTML file instead of
799/// the RDF container listing. Solid clients that send `Accept: text/turtle`
800/// or `application/ld+json` skip this path entirely.
801fn accept_includes_html(accept: &str) -> bool {
802    accept.split(',').any(|entry| {
803        let mime = entry.split(';').next().unwrap_or("").trim();
804        mime.eq_ignore_ascii_case("text/html")
805    })
806}
807
808// ---------------------------------------------------------------------------
809// WAC enforcement for writes (PUT / POST / PATCH / DELETE)
810// ---------------------------------------------------------------------------
811
812// `protected_resource_for_acl` and the sidecar-elevation decision now live
813// in wasm-safe core (`solid_pod_rs::wac::{protected_resource_for_acl,
814// effective_acl_target}`) so this server, the CF-Workers pod, and any
815// downstream consumer share one policy. Imported above via the `wac::{…}`
816// use; the lockout-guard call sites below and the enforcement functions
817// both route through it.
818
819/// [`effective_acl_target`] plus the server-managed-state rules. A trail file
820/// holding an issuer private key (`trail_store::is_secret_trail_path`), the
821/// `/.well-known/prov/` state, the `/.well-known/webledgers/` payment
822/// documents (a forged ledger entry is spendable) are evaluated as `acl:Control`
823/// on themselves, so only the pod's Control holder can read or overwrite them.
824/// An `acl:Read` or `acl:Write` grant, including a public one on the pod root,
825/// is not enough to reach them over HTTP.
826pub(crate) fn guarded_acl_target(path: &str, mode: AccessMode) -> (String, AccessMode) {
827    let (resource, mode) = effective_acl_target(path, mode);
828    // Judge the protected-path rules on the canonical spelling, whatever the
829    // caller handed in; a path that cannot be canonicalised is held to the
830    // strictest mode rather than waved through.
831    match canonical_pod_path(&resource) {
832        Some(canon)
833            if !trail_store::is_secret_trail_path(&canon)
834                && !trail_store::is_prov_state_path(&canon)
835                && !trail_store::is_server_state_path(&canon) =>
836        {
837            (resource, mode)
838        }
839        _ => (resource, AccessMode::Control),
840    }
841}
842
843/// The one canonical spelling of a pod path, or `None` to reject it.
844///
845/// Percent-decodes exactly once, rejects `.` and `..` segments, backslashes,
846/// NUL and invalid UTF-8, collapses empty segments (`//`), forces a leading
847/// `/` and keeps a trailing `/`. The permission check and the storage call
848/// must both use this output, never the caller's spelling, so that a check
849/// and a read cannot see different files.
850pub(crate) fn canonical_pod_path(raw: &str) -> Option<String> {
851    let decoded = percent_decode_str(raw).decode_utf8().ok()?;
852    if decoded.contains(['\\', '\0']) {
853        return None;
854    }
855    let mut out = String::with_capacity(decoded.len() + 1);
856    for seg in decoded.split('/') {
857        match seg {
858            "" => {}
859            "." | ".." => return None,
860            _ => {
861                out.push('/');
862                out.push_str(seg);
863            }
864        }
865    }
866    if out.is_empty() || decoded.ends_with('/') {
867        out.push('/');
868    }
869    Some(out)
870}
871
872/// P0-2 lockout guard (mirrors `mcp/tools.rs:511-552`). Parse a proposed
873/// `.acl` document body and confirm at least one authorization still
874/// grants `acl:Control` to `caller` (by exact WebID, `foaf:Agent`, or —
875/// for an authenticated caller — `acl:AuthenticatedAgent`). Returns
876/// `true` when the proposed ACL is unparseable (the storage layer will
877/// reject malformed bodies; the guard only fires on a parseable ACL that
878/// would strip the caller's Control) or when Control is preserved.
879fn proposed_acl_keeps_caller_control(
880    body: &[u8],
881    content_type: &str,
882    caller: Option<&str>,
883) -> bool {
884    let doc = match parse_jsonld_acl(body) {
885        Ok(d) => Some(d),
886        Err(_) => {
887            let ct = content_type.to_ascii_lowercase();
888            let text = std::str::from_utf8(body).unwrap_or("");
889            let looks_turtle = ct.starts_with("text/turtle")
890                || ct.starts_with("application/turtle")
891                || ct.starts_with("application/x-turtle")
892                || ct.starts_with("application/n-triples")
893                || text.contains("@prefix")
894                || text.contains("acl:Authorization")
895                // N-Triples ACL bodies (e.g. the post-PATCH write-back form)
896                // carry no `@prefix`/`acl:` shorthand — they use the full
897                // ACL IRI. Recognise that so the lockout guard can parse them.
898                || text.contains("auth/acl#Authorization");
899            if looks_turtle {
900                parse_turtle_acl(text).ok()
901            } else {
902                None
903            }
904        }
905    };
906    let Some(doc) = doc else {
907        // Unparseable as an ACL — not our concern; let storage reject it.
908        return true;
909    };
910    let Some(graph) = doc.graph.as_ref() else {
911        return false;
912    };
913    graph.iter().any(|auth| {
914        let grants_control = ids_of_acl_field(&auth.mode)
915            .iter()
916            .any(|m| *m == "acl:Control" || *m == "http://www.w3.org/ns/auth/acl#Control");
917        if !grants_control {
918            return false;
919        }
920        let agents = ids_of_acl_field(&auth.agent);
921        if let Some(web_id) = caller {
922            if agents.contains(&web_id) {
923                return true;
924            }
925        }
926        let classes = ids_of_acl_field(&auth.agent_class);
927        if classes
928            .iter()
929            .any(|c| *c == "http://xmlns.com/foaf/0.1/Agent" || *c == "foaf:Agent")
930        {
931            return true;
932        }
933        if caller.is_some()
934            && classes.iter().any(|c| {
935                *c == "http://www.w3.org/ns/auth/acl#AuthenticatedAgent"
936                    || *c == "acl:AuthenticatedAgent"
937            })
938        {
939            return true;
940        }
941        false
942    })
943}
944
945/// Flatten an optional `IdOrIds` ACL field into a `Vec<&str>` of IRIs.
946fn ids_of_acl_field(field: &Option<wac::IdOrIds>) -> Vec<&str> {
947    match field {
948        None => Vec::new(),
949        Some(wac::IdOrIds::Single(r)) => vec![r.id.as_str()],
950        Some(wac::IdOrIds::Multiple(v)) => v.iter().map(|r| r.id.as_str()).collect(),
951    }
952}
953
954/// Origin-unaware convenience wrapper (used where no HTTP `Origin` is
955/// available — internal callers and unit tests). Delegates with
956/// `request_origin = None`; under `acl-origin` this denies only ACLs that
957/// explicitly restrict by origin, leaving plain ACLs (NoPolicySet) intact.
958/// Live request handlers call [`enforce_write_ctx`] directly, so in a
959/// non-test build this wrapper is exercised only by the test suite.
960#[cfg_attr(not(test), allow(dead_code))]
961async fn enforce_write(
962    state: &AppState,
963    path: &str,
964    mode: AccessMode,
965    agent_uri: Option<&str>,
966) -> Result<(), ActixError> {
967    enforce_write_ctx(state, path, mode, agent_uri, None).await
968}
969
970/// WAC write enforcement threading the request `Origin` (F4 `acl:origin`).
971///
972/// `request_origin` is the raw HTTP `Origin` header; it is parsed to a
973/// canonical [`wac::Origin`] and passed to the evaluator so an ACL bearing
974/// `acl:origin` triples gates cross-origin writes. `acl:Control` (the
975/// sidecar path below) bypasses the origin gate by design so an owner can
976/// always repair a mis-configured ACL from any origin.
977async fn enforce_write_ctx(
978    state: &AppState,
979    path: &str,
980    mode: AccessMode,
981    agent_uri: Option<&str>,
982    request_origin: Option<&str>,
983) -> Result<(), ActixError> {
984    let origin = request_origin.and_then(wac::Origin::parse);
985    // P0-2 / P0-4: an `.acl`/`.meta` sidecar governs *another* resource's
986    // permissions. Authorising its mutation as plain `Write`/`Append` on
987    // the sidecar path lets any writer rewrite the ACL and self-escalate
988    // (privilege escalation). WAC §4.3.5 requires `acl:Control` on the
989    // PROTECTED resource. That elevation is no longer hand-rolled here:
990    // `wac::effective_acl_target` is the single source of truth, shared
991    // with the read path (`enforce_read_ctx`) and any wasm runtime. For an
992    // ordinary resource it returns `(path, mode)` unchanged; for a sidecar
993    // it returns `(protected_resource, Control)`. The lockout guard
994    // (`proposed_acl_keeps_caller_control`) still runs at the PUT/POST/PATCH
995    // handler call sites, keyed on the same `protected_resource_for_acl`.
996    let (resource, eff_mode) = guarded_acl_target(path, mode);
997
998    // `StorageAclResolver` is generic over a concrete backend. `state`
999    // holds an `Arc<dyn Storage>`; `find_effective_acl_dyn` wraps it in a
1000    // trait-object-friendly adapter so the resolver runs against the
1001    // effective resource (the sidecar's governed resource, or `path`).
1002    // ADR-2005: resolve with typed outcomes. A missing policy inherits (the
1003    // walk already did that); an invalid or unreadable one denies here and is
1004    // never allowed to fall through to a broader ancestor grant.
1005    let outcome = resolve_policy_dyn(&*state.storage, &resource).await;
1006    if outcome.is_failure() {
1007        return Err(policy_failure_to_actix(&outcome, &resource));
1008    }
1009    let acl_doc = outcome.document().cloned();
1010
1011    // Resolve the principal's satoshi balance from the Web Ledger so a
1012    // sat-priced resource (`acl:PaymentCondition`) is actually gated.
1013    // `None` only for anonymous callers (no `did:nostr` principal), in
1014    // which case any PaymentCondition fails closed.
1015    let payment_balance_sats = resolve_balance_sats(&*state.storage, agent_uri).await;
1016
1017    let registry = wac::conditions::ConditionRegistry::default_with_client_and_issuer();
1018    let groups: wac::StaticGroupMembership = wac::StaticGroupMembership::default();
1019    // Row 60: a did:nostr caller with a verified WebID link presents as
1020    // both, so an ACL naming either matches.
1021    let linked = cross_identity::linked_identities(state.cross_identity.as_ref(), agent_uri).await;
1022    let Some(ctx) = grant_for_identities(
1023        acl_doc.as_ref(),
1024        agent_uri,
1025        &linked,
1026        payment_balance_sats,
1027        &resource,
1028        eff_mode,
1029        origin.as_ref(),
1030        &groups,
1031        &registry,
1032    ) else {
1033        return Err(acl_denial(acl_doc.as_ref(), agent_uri, &resource));
1034    };
1035    // Sat-gating consumption applies only to a non-elevated (ordinary)
1036    // write. A sidecar elevation demands `acl:Control` on the protected
1037    // resource — the owner-repair path — and is never itself a metered
1038    // write, matching the pre-unification behaviour where the Control
1039    // pre-check returned `Ok` without a Web-Ledger debit. `resource ==
1040    // path` iff `effective_acl_target` did NOT elevate a sidecar.
1041    if resource.as_str() == path {
1042        // A granted write whose authorising rule carried an
1043        // `acl:PaymentCondition` debits the caller's Web Ledger by the
1044        // matched rule's cost. The WAC gate above already proved `balance
1045        // >= cost`, so a debit failure can only mean a concurrent spend
1046        // raced the balance below cost — fail closed, never serve unpaid.
1047        charge_granted_payment(
1048            state,
1049            acl_doc.as_ref(),
1050            &ctx,
1051            &resource,
1052            eff_mode,
1053            &groups,
1054            &registry,
1055            agent_uri,
1056        )
1057        .await?;
1058    }
1059    Ok(())
1060}
1061
1062/// Apply the `acl:PaymentCondition` debit for a request the WAC gate has
1063/// already granted. Computes the cost of the single granting rule via
1064/// [`wac::granted_payment_cost`] and, when that cost is non-zero and the
1065/// caller is an authenticated principal, debits their Web Ledger exactly
1066/// once. A zero cost (no PaymentCondition on the granting rule) is a
1067/// no-op. A debit failure (insufficient balance after a concurrent
1068/// spend, or ledger I/O error) is surfaced as the same WAC denial the
1069/// caller would have received, so the request is never served unpaid.
1070#[allow(clippy::too_many_arguments)]
1071async fn charge_granted_payment(
1072    state: &AppState,
1073    acl_doc: Option<&wac::AclDocument>,
1074    ctx: &RequestContext<'_>,
1075    path: &str,
1076    mode: AccessMode,
1077    groups: &wac::StaticGroupMembership,
1078    registry: &wac::conditions::ConditionRegistry,
1079    payer: Option<&str>,
1080) -> Result<(), ActixError> {
1081    let cost = wac::granted_payment_cost(acl_doc, ctx, path, mode, groups, registry);
1082    if cost == 0 {
1083        return Ok(());
1084    }
1085    // The ledger is keyed by the authenticated principal (`payer`), which is
1086    // the `did:nostr` agent even when a linked WebID is what the ACL granted.
1087    if let Some(did) = payer {
1088        if debit_ledger(&*state.storage, did, cost).await.is_err() {
1089            return Err(acl_denial(acl_doc, payer, path));
1090        }
1091    }
1092    Ok(())
1093}
1094
1095/// Evaluate WAC for the principal and each identity linked to it (row 60),
1096/// returning the request context of the first identity the ACL grants.
1097///
1098/// Evaluating identities one at a time (rather than widening a single
1099/// agent match) keeps every ACL rule, `acl:origin` gate and payment
1100/// condition evaluated exactly as for an ordinary single-identity caller.
1101#[allow(clippy::too_many_arguments)]
1102pub(crate) fn grant_for_identities<'a>(
1103    acl_doc: Option<&wac::AclDocument>,
1104    primary: Option<&'a str>,
1105    linked: &'a [String],
1106    payment_balance_sats: Option<u64>,
1107    resource: &str,
1108    mode: AccessMode,
1109    origin: Option<&wac::Origin>,
1110    groups: &wac::StaticGroupMembership,
1111    registry: &wac::conditions::ConditionRegistry,
1112) -> Option<RequestContext<'a>> {
1113    std::iter::once(primary)
1114        .chain(linked.iter().map(|s| Some(s.as_str())))
1115        .map(|web_id| RequestContext {
1116            web_id,
1117            client_id: None,
1118            issuer: None,
1119            payment_balance_sats,
1120        })
1121        .find(|ctx| {
1122            wac::evaluate_access_ctx_with_registry(
1123                acl_doc, ctx, resource, mode, origin, groups, registry,
1124            )
1125        })
1126}
1127
1128/// Build the WAC denial `actix_web::Error` shared by the read and write
1129/// enforcement paths: `401` (with a `WWW-Authenticate` challenge) for an
1130/// unauthenticated caller so a retry with credentials is signalled, or
1131/// `403` for an authenticated caller the ACL does not grant. Both carry
1132/// the advisory `WAC-Allow` header describing the effective permissions.
1133fn acl_denial(
1134    acl_doc: Option<&wac::AclDocument>,
1135    agent_uri: Option<&str>,
1136    path: &str,
1137) -> ActixError {
1138    let allow_header = wac::wac_allow_header(acl_doc, agent_uri, path);
1139    let (status, body, unauthenticated) = if agent_uri.is_none() {
1140        (StatusCode::UNAUTHORIZED, "authentication required", true)
1141    } else {
1142        (StatusCode::FORBIDDEN, "access forbidden", false)
1143    };
1144    let mut rsp = HttpResponse::new(status);
1145    rsp.headers_mut().insert(
1146        header::HeaderName::from_static("wac-allow"),
1147        header::HeaderValue::from_str(&allow_header)
1148            .unwrap_or(header::HeaderValue::from_static("")),
1149    );
1150    if unauthenticated {
1151        // Advertise every auth scheme the pod accepts so an
1152        // unauthenticated agent knows how to retry. `extract_pubkey` verifies
1153        // NIP-98 (`Authorization: Nostr <base64(kind-27235 event)>`), which is
1154        // how a `did:nostr` agent authenticates against the pod — without the
1155        // `Nostr` challenge an agent has no protocol signal that NIP-98 is
1156        // accepted. DPoP/Bearer remain advertised for OIDC/DPoP clients.
1157        rsp.headers_mut().insert(
1158            header::WWW_AUTHENTICATE,
1159            header::HeaderValue::from_static(
1160                "Nostr realm=\"Solid\", DPoP realm=\"Solid\", Bearer realm=\"Solid\"",
1161            ),
1162        );
1163    }
1164    actix_web::error::InternalError::from_response(body, rsp).into()
1165}
1166
1167/// P0-1: WAC `acl:Read` enforcement for GET / HEAD / container listing.
1168///
1169/// Mirror of [`enforce_write`] for the `Read` mode. Before this guard the
1170/// GET path resolved an advisory `WAC-Allow` header but returned the
1171/// resource body verbatim with no read-authz check, so every private
1172/// resource was world-readable. Returns `Ok(())` on grant; on deny a
1173/// `401`/`403` matching the write path's denial shape.
1174/// Origin-unaware convenience wrapper (see [`enforce_write`]). Delegates
1175/// with `request_origin = None`. Live handlers call [`enforce_read_ctx`]
1176/// directly, so in a non-test build this is exercised only by tests.
1177#[cfg_attr(not(test), allow(dead_code))]
1178async fn enforce_read(
1179    state: &AppState,
1180    path: &str,
1181    agent_uri: Option<&str>,
1182) -> Result<ResponseAudience, ActixError> {
1183    enforce_read_ctx(state, path, agent_uri, None).await
1184}
1185
1186/// WAC read enforcement threading the request `Origin` (F4 `acl:origin`).
1187/// See [`enforce_write_ctx`] for the origin-gate semantics.
1188async fn enforce_read_ctx(
1189    state: &AppState,
1190    path: &str,
1191    agent_uri: Option<&str>,
1192    request_origin: Option<&str>,
1193) -> Result<ResponseAudience, ActixError> {
1194    enforce_read_inner(state, path, agent_uri, request_origin, true).await
1195}
1196
1197/// [`enforce_read_ctx`] with the payment step selectable. With
1198/// `charge == false` a read whose authorising rule carries an
1199/// `acl:PaymentCondition` is refused instead of debited, for callers that
1200/// would otherwise bill one request many times (glob GET).
1201async fn enforce_read_inner(
1202    state: &AppState,
1203    path: &str,
1204    agent_uri: Option<&str>,
1205    request_origin: Option<&str>,
1206    charge: bool,
1207) -> Result<ResponseAudience, ActixError> {
1208    let origin = request_origin.and_then(wac::Origin::parse);
1209    // P0-3: reading an `.acl`/`.meta` sidecar discloses the full
1210    // authorization graph of the resource it governs — every WebID,
1211    // `acl:agentGroup` IRI, `acl:origin`, and `acl:PaymentCondition`
1212    // amount. WAC §4.3.5 requires `acl:Control` on the PROTECTED resource
1213    // to read (as well as write) its ACL — the invariant a downstream
1214    // forum previously got wrong on the READ side. This elevation is now
1215    // the SAME shared `wac::effective_acl_target` the write path uses
1216    // (base mode `Read`), so read and write can no longer drift: an
1217    // ordinary resource stays `(path, Read)`; a sidecar becomes
1218    // `(protected_resource, Control)`, gating ACL disclosure on Control
1219    // exactly as JSS does (`auth/middleware.js:93`).
1220    let (resource, eff_mode) = guarded_acl_target(path, AccessMode::Read);
1221    // ADR-2005: see `enforce_write_ctx` — invalid/unavailable policy denies
1222    // rather than inheriting an ancestor's broader grant.
1223    let outcome = resolve_policy_dyn(&*state.storage, &resource).await;
1224    if outcome.is_failure() {
1225        return Err(policy_failure_to_actix(&outcome, &resource));
1226    }
1227    let acl_doc = outcome.document().cloned();
1228    let payment_balance_sats = resolve_balance_sats(&*state.storage, agent_uri).await;
1229    let registry = wac::conditions::ConditionRegistry::default_with_client_and_issuer();
1230    let groups: wac::StaticGroupMembership = wac::StaticGroupMembership::default();
1231    let linked = cross_identity::linked_identities(state.cross_identity.as_ref(), agent_uri).await;
1232    let Some(ctx) = grant_for_identities(
1233        acl_doc.as_ref(),
1234        agent_uri,
1235        &linked,
1236        payment_balance_sats,
1237        &resource,
1238        eff_mode,
1239        origin.as_ref(),
1240        &groups,
1241        &registry,
1242    ) else {
1243        return Err(acl_denial(acl_doc.as_ref(), agent_uri, &resource));
1244    };
1245    // Sat-gating consumption applies only to a non-elevated (ordinary)
1246    // read; a sidecar Control elevation is never metered (see
1247    // `enforce_write_ctx`). `resource == path` iff no elevation happened.
1248    if resource.as_str() == path && !charge {
1249        if wac::granted_payment_cost(
1250            acl_doc.as_ref(),
1251            &ctx,
1252            &resource,
1253            eff_mode,
1254            &groups,
1255            &registry,
1256        ) > 0
1257        {
1258            return Err(acl_denial(acl_doc.as_ref(), agent_uri, &resource));
1259        }
1260    } else if resource.as_str() == path {
1261        // A granted read whose authorising rule carried an
1262        // `acl:PaymentCondition` debits the caller's Web Ledger by the
1263        // matched rule's cost (fail-closed on a raced balance). See
1264        // `charge_granted_payment`.
1265        charge_granted_payment(
1266            state,
1267            acl_doc.as_ref(),
1268            &ctx,
1269            &resource,
1270            eff_mode,
1271            &groups,
1272            &registry,
1273            agent_uri,
1274        )
1275        .await?;
1276    }
1277    // ADR-2002: classify the response's audience so the caller can mark it
1278    // uncacheable. The question is not "what media type is this?" but "could
1279    // an anonymous client have received the same body?" — so re-evaluate the
1280    // SAME already-resolved ACL with no principal. Pure; no extra I/O.
1281    //
1282    // A sidecar read (elevated to Control) is never public regardless of what
1283    // the ACL says, and a payment-gated read fails the anonymous evaluation
1284    // (no balance), so both correctly classify as private.
1285    let anon_ctx = RequestContext {
1286        web_id: None,
1287        client_id: None,
1288        issuer: None,
1289        payment_balance_sats: None,
1290    };
1291    let anonymous_would_be_granted = wac::evaluate_access_ctx_with_registry(
1292        acl_doc.as_ref(),
1293        &anon_ctx,
1294        &resource,
1295        eff_mode,
1296        origin.as_ref(),
1297        &groups,
1298        &registry,
1299    );
1300    Ok(if anonymous_would_be_granted && resource.as_str() == path {
1301        ResponseAudience::Public
1302    } else {
1303        ResponseAudience::Private
1304    })
1305}
1306
1307/// Debit `cost` satoshis from `did`'s Web Ledger entry and persist the
1308/// updated ledger document, deducting exactly once for a granted
1309/// payment-gated request.
1310///
1311/// Reads [`WEBLEDGER_PATH`], applies [`WebLedger::charge`] (which fails
1312/// closed on an insufficient or missing balance), and writes the ledger
1313/// back. A read, debit, or write failure returns `Err` so the caller can
1314/// deny the request rather than serve it unpaid.
1315async fn debit_ledger(
1316    storage: &dyn Storage,
1317    did: &str,
1318    cost: u64,
1319) -> Result<(), solid_pod_rs::payments::PaymentError> {
1320    use solid_pod_rs::payments::{PaymentError, WebLedger};
1321    let _transaction = PAYMENT_STATE_LOCK.lock().await;
1322
1323    let (bytes, _meta) = storage
1324        .get(WEBLEDGER_PATH)
1325        .await
1326        .map_err(|e| PaymentError::Store(e.to_string()))?;
1327    let mut ledger: WebLedger = serde_json::from_slice(&bytes)
1328        .map_err(|e| PaymentError::Store(format!("malformed ledger: {e}")))?;
1329    // The access fee is spent, not refunded: the request is served.
1330    let _charge = ledger.charge(did, cost)?;
1331    let body = serde_json::to_vec(&ledger)
1332        .map_err(|e| PaymentError::Store(format!("serialise ledger: {e}")))?;
1333    storage
1334        .put(WEBLEDGER_PATH, Bytes::from(body), "application/json")
1335        .await
1336        .map_err(|e| PaymentError::Store(e.to_string()))?;
1337    Ok(())
1338}
1339
1340// ---------------------------------------------------------------------------
1341// Handlers
1342// ---------------------------------------------------------------------------
1343
1344fn set_link_headers(rsp: &mut HttpResponse, path: &str) {
1345    let links = ldp::link_headers(path).join(", ");
1346    if let Ok(value) = header::HeaderValue::from_str(&links) {
1347        rsp.headers_mut()
1348            .insert(header::HeaderName::from_static("link"), value);
1349    }
1350}
1351
1352fn set_wac_allow(rsp: &mut HttpResponse, header_value: &str) {
1353    if let Ok(v) = header::HeaderValue::from_str(header_value) {
1354        rsp.headers_mut()
1355            .insert(header::HeaderName::from_static("wac-allow"), v);
1356    }
1357}
1358
1359fn set_updates_via(rsp: &mut HttpResponse, base_url: &str) {
1360    let ws_base = base_url
1361        .replacen("https://", "wss://", 1)
1362        .replacen("http://", "ws://", 1);
1363    let ws_url = format!("{}/.notifications", ws_base.trim_end_matches('/'));
1364    if let Ok(v) = header::HeaderValue::from_str(&ws_url) {
1365        rsp.headers_mut()
1366            .insert(header::HeaderName::from_static("updates-via"), v);
1367    }
1368}
1369
1370/// Surface a [`ProvenanceReceipt`] to the caller on the write's response
1371/// (ADR-2004).
1372///
1373/// The LDP write has already succeeded, so the status code must not change —
1374/// but the client is entitled to know which provenance tier its write actually
1375/// reached. `X-Provenance` carries the stage (`resource-stored`,
1376/// `local-mark-committed`, `anchor-submitted`, `anchor-confirmed`, `skipped`)
1377/// plus any failure detail; `X-Provenance-Commit` carries the git SHA when one
1378/// exists. A failed mark is therefore visible in the response rather than only
1379/// in the server log.
1380fn set_provenance_headers(rsp: &mut HttpResponse, receipt: &ProvenanceReceipt) {
1381    if let Ok(v) = header::HeaderValue::from_str(&receipt.summary()) {
1382        rsp.headers_mut()
1383            .insert(header::HeaderName::from_static("x-provenance"), v);
1384    }
1385    if let Some(sha) = receipt.commit_sha() {
1386        if let Ok(v) = header::HeaderValue::from_str(sha) {
1387            rsp.headers_mut()
1388                .insert(header::HeaderName::from_static("x-provenance-commit"), v);
1389        }
1390    }
1391}
1392
1393/// Apply the ADR-2002 cache policy to a response.
1394///
1395/// A response that an anonymous client would not have received is marked
1396/// `private, no-store` so no shared cache may store or re-serve it, and
1397/// `Vary: Authorization` is set so a cache keyed on the request cannot fuse
1398/// an authenticated response with an anonymous one. Public responses keep the
1399/// media-type policy (RDF gets `private, no-cache, must-revalidate`; public
1400/// binaries are left to ordinary caching).
1401///
1402/// Never overwrites a `Cache-Control` a handler has already set deliberately
1403/// (the mashlib HTML wrapper sets `no-store` of its own).
1404fn set_cache_policy(rsp: &mut HttpResponse, content_type: &str, audience: ResponseAudience) {
1405    if audience == ResponseAudience::Private {
1406        // Vary matters even when the body is uncacheable: an intermediary
1407        // that ignores `no-store` must at least not key this response for an
1408        // anonymous requester.
1409        append_vary(rsp, "Authorization");
1410    }
1411    if rsp.headers().contains_key(header::CACHE_CONTROL) {
1412        return;
1413    }
1414    if let Some(value) = cache_control_for_response(content_type, audience) {
1415        rsp.headers_mut().insert(
1416            header::CACHE_CONTROL,
1417            header::HeaderValue::from_static(value),
1418        );
1419    }
1420}
1421
1422/// Add `field` to the response's `Vary` header, preserving any existing value.
1423fn append_vary(rsp: &mut HttpResponse, field: &str) {
1424    let existing = rsp
1425        .headers()
1426        .get(header::VARY)
1427        .and_then(|v| v.to_str().ok())
1428        .unwrap_or("")
1429        .to_string();
1430    if existing
1431        .split(',')
1432        .any(|f| f.trim().eq_ignore_ascii_case(field))
1433    {
1434        return;
1435    }
1436    let merged = if existing.trim().is_empty() {
1437        field.to_string()
1438    } else {
1439        format!("{existing}, {field}")
1440    };
1441    if let Ok(v) = header::HeaderValue::from_str(&merged) {
1442        rsp.headers_mut().insert(header::VARY, v);
1443    }
1444}
1445
1446async fn handle_get(
1447    req: HttpRequest,
1448    state: web::Data<AppState>,
1449) -> Result<HttpResponse, ActixError> {
1450    let path = req.uri().path().to_string();
1451
1452    // JSS server.js 545-570: the dedicated `/profile/card.jsonld` route
1453    // answers ActivityPub-flavoured Accept headers with the actor document
1454    // and defers to the normal resource handler otherwise. Public, like
1455    // the JSS route.
1456    #[cfg(feature = "activitypub")]
1457    if let (Some(ap), "/profile/card.jsonld") = (state.activitypub.as_ref(), path.as_str()) {
1458        let accept = req
1459            .headers()
1460            .get(header::ACCEPT)
1461            .and_then(|v| v.to_str().ok())
1462            .unwrap_or("");
1463        if solid_pod_rs_activitypub::negotiate_actor_format(accept)
1464            == solid_pod_rs_activitypub::ActorFormat::ActivityJson
1465        {
1466            let doc = ap.actor_json(&scheme::request_origin(&req));
1467            return Ok(HttpResponse::Ok()
1468                .content_type("application/activity+json")
1469                .insert_header((header::VARY, "Accept"))
1470                .json(doc));
1471        }
1472    }
1473
1474    if path.contains('*') {
1475        return handle_glob_get(req, state).await;
1476    }
1477
1478    let auth_pk = extract_pubkey(&req).await;
1479    let agent = agent_uri(auth_pk.as_ref());
1480
1481    // P0-1: enforce WAC `acl:Read` before serving any bytes. This guards
1482    // both resource GETs and the RDF container listing below, and — since
1483    // HEAD is routed to this same handler — HEAD requests too. Without it
1484    // a private resource is world-readable.
1485    let audience = enforce_read_ctx(&state, &path, agent.as_deref(), req_origin(&req)).await?;
1486
1487    let wac_allow = wac::wac_allow_header(None, agent.as_deref(), &path);
1488
1489    if ldp::is_container(&path) {
1490        let accept = req
1491            .headers()
1492            .get(header::ACCEPT)
1493            .and_then(|v| v.to_str().ok())
1494            .unwrap_or("");
1495
1496        // Content negotiation: when a browser requests text/html, check
1497        // whether the container has an index.html child resource. If so,
1498        // serve it directly instead of the RDF container listing. This is
1499        // standard HTTP content negotiation — browsers get HTML, Solid
1500        // clients get RDF.
1501        if accept_includes_html(accept) {
1502            let index_path = format!("{path}index.html");
1503            // The child has its own ACL: Read on the container does not entitle
1504            // the caller to it. On denial fall through to the listing.
1505            let index_audience =
1506                enforce_read_ctx(&state, &index_path, agent.as_deref(), req_origin(&req))
1507                    .await
1508                    .ok();
1509            if let (Some(index_audience), Ok((body, _meta))) =
1510                (index_audience, state.storage.get(&index_path).await)
1511            {
1512                let mut rsp = HttpResponse::Ok()
1513                    .content_type("text/html; charset=utf-8")
1514                    .body(inject_live_reload(&body, state.live_reload));
1515                set_cache_policy(&mut rsp, "text/html", index_audience);
1516                set_wac_allow(&mut rsp, &wac_allow);
1517                set_updates_via(&mut rsp, &state.nodeinfo.base_url);
1518                set_link_headers(&mut rsp, &path);
1519                return Ok(rsp);
1520            }
1521        }
1522
1523        let v = state
1524            .storage
1525            .container_representation(&path)
1526            .await
1527            .map_err(to_actix)?;
1528
1529        // Mashlib: serve HTML wrapper for browser navigation.
1530        let sec_fetch_dest = req
1531            .headers()
1532            .get("sec-fetch-dest")
1533            .and_then(|v| v.to_str().ok());
1534        if mashlib::should_serve(
1535            accept,
1536            sec_fetch_dest,
1537            "application/ld+json",
1538            state.mashlib.enabled,
1539        ) {
1540            let json_ld = serde_json::to_string(&v).ok();
1541            let html = mashlib::generate_html(&path, &state.mashlib, json_ld.as_deref());
1542            let mut rsp = HttpResponse::Ok()
1543                .content_type("text/html; charset=utf-8")
1544                .insert_header(("X-Frame-Options", "DENY"))
1545                .insert_header(("Content-Security-Policy", "frame-ancestors 'none'"))
1546                .insert_header(("Cache-Control", "no-store"))
1547                .body(inject_live_reload(html, state.live_reload));
1548            set_cache_policy(&mut rsp, "text/html", audience);
1549            set_wac_allow(&mut rsp, &wac_allow);
1550            set_updates_via(&mut rsp, &state.nodeinfo.base_url);
1551            set_link_headers(&mut rsp, &path);
1552            return Ok(rsp);
1553        }
1554
1555        let mut rsp = HttpResponse::Ok().json(v);
1556        rsp.headers_mut().insert(
1557            header::CONTENT_TYPE,
1558            header::HeaderValue::from_static("application/ld+json"),
1559        );
1560        set_cache_policy(&mut rsp, "application/ld+json", audience);
1561        set_wac_allow(&mut rsp, &wac_allow);
1562        set_updates_via(&mut rsp, &state.nodeinfo.base_url);
1563        set_link_headers(&mut rsp, &path);
1564        return Ok(rsp);
1565    }
1566
1567    match state.storage.get(&path).await {
1568        Ok((body, meta)) => {
1569            // Mashlib: serve HTML wrapper for browser navigation to RDF resources.
1570            let accept = req
1571                .headers()
1572                .get(header::ACCEPT)
1573                .and_then(|v| v.to_str().ok())
1574                .unwrap_or("");
1575            let sec_fetch_dest = req
1576                .headers()
1577                .get("sec-fetch-dest")
1578                .and_then(|v| v.to_str().ok());
1579            if mashlib::should_serve(
1580                accept,
1581                sec_fetch_dest,
1582                &meta.content_type,
1583                state.mashlib.enabled,
1584            ) {
1585                let embed = if body.len() <= state.mashlib.data_island_max_bytes {
1586                    std::str::from_utf8(&body).ok().map(|s| s.to_string())
1587                } else {
1588                    None
1589                };
1590                let html = mashlib::generate_html(&path, &state.mashlib, embed.as_deref());
1591                let mut rsp = HttpResponse::Ok()
1592                    .content_type("text/html; charset=utf-8")
1593                    .insert_header(("X-Frame-Options", "DENY"))
1594                    .insert_header(("Content-Security-Policy", "frame-ancestors 'none'"))
1595                    .insert_header(("Cache-Control", "no-store"))
1596                    .body(inject_live_reload(html, state.live_reload));
1597                set_cache_policy(&mut rsp, "text/html", audience);
1598                set_wac_allow(&mut rsp, &wac_allow);
1599                set_updates_via(&mut rsp, &state.nodeinfo.base_url);
1600                set_link_headers(&mut rsp, &path);
1601                return Ok(rsp);
1602            }
1603
1604            // RDF content negotiation: when the client explicitly asks for
1605            // a concrete RDF serialisation that differs from how the
1606            // resource is stored, transcode it. KG resources persist as
1607            // N-Triples (see the PATCH handler), so an agent or extractor
1608            // can GET the same graph as Turtle, N-Triples, or JSON-LD on
1609            // demand (PRD-014 Seam C / C4). Non-RDF resources, unparseable
1610            // bodies, and wildcard/`*/*` Accepts fall through to verbatim.
1611            if let Some((negotiated_body, negotiated_ct)) =
1612                rdf_content_negotiate(&body, &meta.content_type, accept)
1613            {
1614                let mut rsp = HttpResponse::Ok().body(negotiated_body);
1615                rsp.headers_mut().insert(
1616                    header::CONTENT_TYPE,
1617                    header::HeaderValue::from_str(negotiated_ct)
1618                        .unwrap_or_else(|_| header::HeaderValue::from_static("text/turtle")),
1619                );
1620                rsp.headers_mut()
1621                    .insert(header::VARY, header::HeaderValue::from_static("Accept"));
1622                if let Ok(etag) = header::HeaderValue::from_str(&format!("\"{}\"", meta.etag)) {
1623                    rsp.headers_mut().insert(header::ETAG, etag);
1624                }
1625                set_cache_policy(&mut rsp, negotiated_ct, audience);
1626                set_wac_allow(&mut rsp, &wac_allow);
1627                set_updates_via(&mut rsp, &state.nodeinfo.base_url);
1628                set_link_headers(&mut rsp, &path);
1629                return Ok(rsp);
1630            }
1631
1632            let response_body = if meta.content_type.starts_with("text/html") {
1633                inject_live_reload(&body, state.live_reload)
1634            } else {
1635                body.to_vec()
1636            };
1637            let mut rsp = HttpResponse::Ok().body(response_body);
1638            rsp.headers_mut().insert(
1639                header::CONTENT_TYPE,
1640                header::HeaderValue::from_str(&meta.content_type).unwrap_or_else(|_| {
1641                    header::HeaderValue::from_static("application/octet-stream")
1642                }),
1643            );
1644            if let Ok(etag) = header::HeaderValue::from_str(&format!("\"{}\"", meta.etag)) {
1645                rsp.headers_mut().insert(header::ETAG, etag);
1646            }
1647            set_cache_policy(&mut rsp, &meta.content_type, audience);
1648            set_wac_allow(&mut rsp, &wac_allow);
1649            set_updates_via(&mut rsp, &state.nodeinfo.base_url);
1650            set_link_headers(&mut rsp, &path);
1651            Ok(rsp)
1652        }
1653        Err(PodError::NotFound(_)) => Ok(HttpResponse::NotFound().finish()),
1654        Err(e) => Err(to_actix(e)),
1655    }
1656}
1657
1658fn has_basic_container_link(req: &HttpRequest) -> bool {
1659    req.headers()
1660        .get_all(header::LINK)
1661        .filter_map(|v| v.to_str().ok())
1662        .any(|v| {
1663            v.contains("http://www.w3.org/ns/ldp#BasicContainer") && v.contains("rel=\"type\"")
1664        })
1665}
1666
1667/// Validate a Turtle / N3 request body (parity row 35).
1668///
1669/// `text/turtle` bodies must parse (400 on a syntax error). `text/n3` is
1670/// accepted only with conneg on (415 otherwise, JSS `canAcceptInput`), and
1671/// N3 formulas, variables and rules are refused with 415. The base IRI is
1672/// the request URL of the resource being written. Other content types pass
1673/// through untouched. The parsed graph is discarded: the stored bytes are
1674/// the client's own representation.
1675fn validate_rdf_body(
1676    req: &HttpRequest,
1677    state: &AppState,
1678    resource_path: &str,
1679    content_type: &str,
1680    body: &[u8],
1681) -> Result<(), ActixError> {
1682    use solid_pod_rs::rdf_input::{parse_rdf_body, RdfInputSyntax};
1683    let Some(syntax) = RdfInputSyntax::from_content_type(content_type) else {
1684        return Ok(());
1685    };
1686    if syntax == RdfInputSyntax::N3 && !state.conneg_enabled {
1687        return Err(actix_web::error::ErrorUnsupportedMediaType(
1688            "text/n3 request bodies require content negotiation (conneg) to be enabled",
1689        ));
1690    }
1691    let base = format!("{}{}", scheme::request_origin(req), resource_path);
1692    match parse_rdf_body(syntax, body, &base) {
1693        Ok(_) => Ok(()),
1694        Err(solid_pod_rs::PodError::PayloadTooLarge(m)) => {
1695            Err(actix_web::error::ErrorPayloadTooLarge(m))
1696        }
1697        Err(e) => Err(to_actix(e)),
1698    }
1699}
1700
1701async fn handle_put(
1702    req: HttpRequest,
1703    body: web::Bytes,
1704    state: web::Data<AppState>,
1705) -> Result<HttpResponse, ActixError> {
1706    let path = req.uri().path().to_string();
1707
1708    if ldp::is_container(&path) {
1709        if has_basic_container_link(&req) {
1710            let auth_pk = extract_pubkey_with_body(&req, Some(&body)).await;
1711            let agent = agent_uri(auth_pk.as_ref());
1712            enforce_write_ctx(
1713                &state,
1714                &path,
1715                AccessMode::Write,
1716                agent.as_deref(),
1717                req_origin(&req),
1718            )
1719            .await?;
1720            let meta = state
1721                .storage
1722                .create_container(&path)
1723                .await
1724                .map_err(to_actix)?;
1725            let mut rsp = HttpResponse::Created().finish();
1726            if let Ok(etag) = header::HeaderValue::from_str(&format!("\"{}\"", meta.etag)) {
1727                rsp.headers_mut().insert(header::ETAG, etag);
1728            }
1729            set_link_headers(&mut rsp, &path);
1730            return Ok(rsp);
1731        }
1732        return Ok(HttpResponse::MethodNotAllowed().body("cannot PUT to a container"));
1733    }
1734
1735    let auth_pk = extract_pubkey_with_body(&req, Some(&body)).await;
1736    let agent = agent_uri(auth_pk.as_ref());
1737    enforce_write_ctx(
1738        &state,
1739        &path,
1740        AccessMode::Write,
1741        agent.as_deref(),
1742        req_origin(&req),
1743    )
1744    .await?;
1745
1746    let ct = req
1747        .headers()
1748        .get(header::CONTENT_TYPE)
1749        .and_then(|v| v.to_str().ok())
1750        .unwrap_or("application/octet-stream");
1751
1752    // P0-2 lockout guard: when writing an `.acl`/`.meta` sidecar, refuse a
1753    // proposed ACL that would strip the caller's own Control — the same
1754    // footgun the MCP `write_acl` path blocks (mcp/tools.rs:511). Without
1755    // this a Control holder could lock themselves (and everyone) out.
1756    if protected_resource_for_acl(&path).is_some()
1757        && !proposed_acl_keeps_caller_control(&body, ct, agent.as_deref())
1758    {
1759        return Ok(HttpResponse::Conflict().body(
1760            "refused: the proposed ACL would not grant Control to the caller \
1761             (use an absolute WebID, foaf:Agent, or acl:AuthenticatedAgent)",
1762        ));
1763    }
1764
1765    validate_rdf_body(&req, &state, &path, ct, &body)?;
1766
1767    let quota = reserve_quota_for_size(&state, &path, body.len() as u64).await?;
1768    let write = state
1769        .storage
1770        .put(&path, Bytes::from(body.to_vec()), ct)
1771        .await;
1772    finish_quota_reservation(&state, quota, write.is_ok()).await;
1773    let meta = write.map_err(to_actix)?;
1774    // git-mark (Phase 2): commit + PROV-O sidecar on git-backed pods. Runs
1775    // AFTER the write succeeded; additive + best-effort (errors swallowed),
1776    // git-backed-only, never changes the response.
1777    let provenance = git_mark_write(&state, &path, agent.as_deref(), "PUT").await;
1778    let mut rsp = HttpResponse::Created().finish();
1779    if let Ok(etag) = header::HeaderValue::from_str(&format!("\"{}\"", meta.etag)) {
1780        rsp.headers_mut().insert(header::ETAG, etag);
1781    }
1782    set_provenance_headers(&mut rsp, &provenance);
1783    set_link_headers(&mut rsp, &path);
1784    Ok(rsp)
1785}
1786
1787/// P1-k: probe storage for `target` and, if it already exists, append
1788/// `-1`, `-2`, … before the file extension (or at the end when there is no
1789/// extension) until a free name is found — mirroring JSS
1790/// `generateUniqueFilename` so an LDP POST never overwrites a sibling. The
1791/// probe is bounded; on the practically-unreachable ceiling it falls back
1792/// to a content-hash suffix so the write still lands on a fresh name.
1793async fn mint_unique_target(storage: &dyn Storage, target: &str) -> String {
1794    if !storage.exists(target).await.unwrap_or(false) {
1795        return target.to_string();
1796    }
1797    // Split stem/ext at the last '.' that falls after the last '/', so a
1798    // leading-dot filename (e.g. `/c/.keep`) is treated as extension-less.
1799    let seg_start = target.rfind('/').map(|s| s + 1).unwrap_or(0);
1800    let (stem, ext) = match target.rfind('.') {
1801        Some(dot) if dot > seg_start => (&target[..dot], &target[dot..]),
1802        _ => (target, ""),
1803    };
1804    for n in 1..10_000u32 {
1805        let candidate = format!("{stem}-{n}{ext}");
1806        if !storage.exists(&candidate).await.unwrap_or(false) {
1807            return candidate;
1808        }
1809    }
1810    use std::hash::{Hash, Hasher};
1811    let mut h = std::collections::hash_map::DefaultHasher::new();
1812    target.hash(&mut h);
1813    format!("{stem}-{:x}{ext}", h.finish())
1814}
1815
1816async fn handle_post(
1817    req: HttpRequest,
1818    body: web::Bytes,
1819    state: web::Data<AppState>,
1820) -> Result<HttpResponse, ActixError> {
1821    let path = req.uri().path().to_string();
1822    // POST route only matches container paths (trailing slash) via the
1823    // `POST /{tail:.*}/` registration.
1824    let auth_pk = extract_pubkey_with_body(&req, Some(&body)).await;
1825    let agent = agent_uri(auth_pk.as_ref());
1826    enforce_write_ctx(
1827        &state,
1828        &path,
1829        AccessMode::Append,
1830        agent.as_deref(),
1831        req_origin(&req),
1832    )
1833    .await?;
1834
1835    let slug = req
1836        .headers()
1837        .get(header::HeaderName::from_static("slug"))
1838        .and_then(|v| v.to_str().ok());
1839    let mut target = match ldp::resolve_slug(&path, slug) {
1840        Ok(p) => p,
1841        Err(e) => return Err(to_actix(e)),
1842    };
1843    let ct = req
1844        .headers()
1845        .get(header::CONTENT_TYPE)
1846        .and_then(|v| v.to_str().ok())
1847        .unwrap_or("application/octet-stream");
1848
1849    // P0-4: POST authorised only `Append` on the container. If the client's
1850    // Slug resolves to an `.acl`/`.meta` sidecar, that sidecar governs
1851    // ANOTHER resource's permissions — minting it from Append-only rights is
1852    // privilege escalation (an attacker self-grants Control on a sibling).
1853    // Elevate exactly as the PUT path does: require `acl:Control` on the
1854    // protected resource AND run the lockout guard on the proposed body.
1855    // (This gap is shared with JSS, which keys its Control guard on the
1856    // container path, not the resolved `.acl` — candidate upstream PR.)
1857    if protected_resource_for_acl(&target).is_some() {
1858        enforce_write_ctx(
1859            &state,
1860            &target,
1861            AccessMode::Write,
1862            agent.as_deref(),
1863            req_origin(&req),
1864        )
1865        .await?;
1866        if !proposed_acl_keeps_caller_control(&body, ct, agent.as_deref()) {
1867            return Ok(HttpResponse::Conflict().body(
1868                "refused: the proposed ACL would not grant Control to the caller \
1869                 (use an absolute WebID, foaf:Agent, or acl:AuthenticatedAgent)",
1870            ));
1871        }
1872    } else {
1873        // P1-k: LDP POST must CREATE a new resource, never overwrite one.
1874        // `resolve_slug` joins the Slug verbatim, so a repeated `Slug: note`
1875        // would clobber the first note (silent data loss). Mint a unique
1876        // target by probing existence and appending `-1`, `-2`, … exactly as
1877        // JSS `generateUniqueFilename` does.
1878        target = mint_unique_target(&*state.storage, &target).await;
1879    }
1880
1881    validate_rdf_body(&req, &state, &target, ct, &body)?;
1882
1883    let quota = reserve_quota_for_size(&state, &target, body.len() as u64).await?;
1884    let write = state
1885        .storage
1886        .put(&target, Bytes::from(body.to_vec()), ct)
1887        .await;
1888    finish_quota_reservation(&state, quota, write.is_ok()).await;
1889    let meta = write.map_err(to_actix)?;
1890    // git-mark (Phase 2): commit + PROV-O sidecar for the newly-created child.
1891    // Additive + best-effort, git-backed-only.
1892    let provenance = git_mark_write(&state, &target, agent.as_deref(), "POST").await;
1893    let mut rsp = HttpResponse::Created().finish();
1894    if let Ok(loc) = header::HeaderValue::from_str(&target) {
1895        rsp.headers_mut().insert(header::LOCATION, loc);
1896    }
1897    if let Ok(etag) = header::HeaderValue::from_str(&format!("\"{}\"", meta.etag)) {
1898        rsp.headers_mut().insert(header::ETAG, etag);
1899    }
1900    set_provenance_headers(&mut rsp, &provenance);
1901    set_link_headers(&mut rsp, &target);
1902    Ok(rsp)
1903}
1904
1905async fn handle_patch(
1906    req: HttpRequest,
1907    body: web::Bytes,
1908    state: web::Data<AppState>,
1909) -> Result<HttpResponse, ActixError> {
1910    let path = req.uri().path().to_string();
1911    if ldp::is_container(&path) {
1912        return Ok(HttpResponse::MethodNotAllowed().body("cannot PATCH a container"));
1913    }
1914    let auth_pk = extract_pubkey_with_body(&req, Some(&body)).await;
1915    let agent = agent_uri(auth_pk.as_ref());
1916    // PATCH can modify or delete data (e.g. N3 Patch with solid:deletes),
1917    // so it requires full Write permission — not just Append. Only POST
1918    // (which creates new child resources in a container) is allowed with
1919    // Append-only permission. This prevents Append-only users from
1920    // overwriting or deleting resource content via PATCH.
1921    enforce_write_ctx(
1922        &state,
1923        &path,
1924        AccessMode::Write,
1925        agent.as_deref(),
1926        req_origin(&req),
1927    )
1928    .await?;
1929
1930    let ct = req
1931        .headers()
1932        .get(header::CONTENT_TYPE)
1933        .and_then(|v| v.to_str().ok())
1934        .unwrap_or("");
1935    let dialect = match ldp::patch_dialect_from_mime(ct) {
1936        Some(d) => d,
1937        None => {
1938            return Ok(HttpResponse::UnsupportedMediaType()
1939                .body(format!("unsupported patch dialect for content-type {ct:?}")))
1940        }
1941    };
1942    let body_str = match std::str::from_utf8(&body) {
1943        Ok(s) => s.to_string(),
1944        Err(_) => return Ok(HttpResponse::BadRequest().body("patch body is not valid UTF-8")),
1945    };
1946
1947    // Existing resource?
1948    let existing = state.storage.get(&path).await;
1949    match existing {
1950        Ok((current_body, meta)) => {
1951            // Seed the working graph from the EXISTING resource body so the
1952            // mutation lands on top of the triples already stored, rather
1953            // than on an empty graph (which silently discarded everything
1954            // on every incremental write — the data-loss bug fixed here;
1955            // PRD-014 Seam C / DDD-012 A2 non-destructive-write invariant).
1956            // RDF resources are persisted as N-Triples by `graph_to_turtle`,
1957            // so the current body round-trips through `parse_ntriples`. A
1958            // body that is not parseable N-Triples is refused, not
1959            // overwritten — fail closed rather than destroy.
1960            let out = match dialect {
1961                ldp::PatchDialect::N3 => {
1962                    let seed = seed_graph_from_patch_target(&current_body)?;
1963                    ldp::apply_n3_patch(seed, &body_str).map_err(patch_parse_err)
1964                }
1965                ldp::PatchDialect::SparqlUpdate => {
1966                    let seed = seed_graph_from_patch_target(&current_body)?;
1967                    ldp::apply_sparql_patch(seed, &body_str).map_err(patch_parse_err)
1968                }
1969                ldp::PatchDialect::JsonPatch => {
1970                    let mut json: serde_json::Value = match serde_json::from_slice(&current_body) {
1971                        Ok(v) => v,
1972                        Err(_) => serde_json::json!({}),
1973                    };
1974                    let patch: serde_json::Value = match serde_json::from_str(&body_str) {
1975                        Ok(v) => v,
1976                        Err(e) => return Err(to_actix(PodError::BadRequest(e.to_string()))),
1977                    };
1978                    ldp::apply_json_patch(&mut json, &patch).map_err(to_actix)?;
1979                    let bytes = serde_json::to_vec(&json)
1980                        .map_err(PodError::from)
1981                        .map_err(to_actix)?;
1982                    let quota = reserve_quota_for_size(&state, &path, bytes.len() as u64).await?;
1983                    let write = state
1984                        .storage
1985                        .put(&path, Bytes::from(bytes), &meta.content_type)
1986                        .await;
1987                    finish_quota_reservation(&state, quota, write.is_ok()).await;
1988                    let _ = write.map_err(to_actix)?;
1989                    let provenance = git_mark_write(&state, &path, agent.as_deref(), "PATCH").await;
1990                    let mut rsp = HttpResponse::NoContent().finish();
1991                    set_provenance_headers(&mut rsp, &provenance);
1992                    return Ok(rsp);
1993                }
1994            };
1995            let outcome = out?;
1996            // Round-trip the updated graph back to Turtle so the next
1997            // GET reflects the mutation.
1998            let serialised = graph_to_turtle(&outcome.graph);
1999            // F7: PATCHing an `.acl`/`.meta` sidecar already required Control
2000            // (enforced above), but — unlike PUT — the POST-patch result was
2001            // never checked against the lockout guard, so a Control holder
2002            // could strip every principal's Control in one patch. Apply the
2003            // same guard PUT uses, on the serialised post-patch ACL.
2004            if protected_resource_for_acl(&path).is_some()
2005                && !proposed_acl_keeps_caller_control(
2006                    serialised.as_bytes(),
2007                    "application/n-triples",
2008                    agent.as_deref(),
2009                )
2010            {
2011                return Ok(HttpResponse::Conflict().body(
2012                    "refused: the patched ACL would not grant Control to the caller \
2013                     (use an absolute WebID, foaf:Agent, or acl:AuthenticatedAgent)",
2014                ));
2015            }
2016            let quota = reserve_quota_for_size(&state, &path, serialised.len() as u64).await?;
2017            let write = state
2018                .storage
2019                .put(&path, Bytes::from(serialised.into_bytes()), "text/turtle")
2020                .await;
2021            finish_quota_reservation(&state, quota, write.is_ok()).await;
2022            let _ = write.map_err(to_actix)?;
2023            let provenance = git_mark_write(&state, &path, agent.as_deref(), "PATCH").await;
2024            let mut rsp = HttpResponse::NoContent().finish();
2025            set_provenance_headers(&mut rsp, &provenance);
2026            Ok(rsp)
2027        }
2028        Err(PodError::NotFound(_)) => {
2029            // PATCH against an absent resource — create it.
2030            let create = ldp::apply_patch_to_absent(dialect, &body_str).map_err(patch_parse_err)?;
2031            let PatchCreateOutcome::Created { graph, .. } = create else {
2032                return Err(to_actix(PodError::Unsupported(
2033                    "unexpected patch outcome on absent resource".into(),
2034                )));
2035            };
2036            let serialised = graph_to_turtle(&graph);
2037            // F7: same lockout guard on the create-via-PATCH `.acl` path.
2038            if protected_resource_for_acl(&path).is_some()
2039                && !proposed_acl_keeps_caller_control(
2040                    serialised.as_bytes(),
2041                    "application/n-triples",
2042                    agent.as_deref(),
2043                )
2044            {
2045                return Ok(HttpResponse::Conflict().body(
2046                    "refused: the patched ACL would not grant Control to the caller \
2047                     (use an absolute WebID, foaf:Agent, or acl:AuthenticatedAgent)",
2048                ));
2049            }
2050            let quota = reserve_quota_for_size(&state, &path, serialised.len() as u64).await?;
2051            let write = state
2052                .storage
2053                .put(&path, Bytes::from(serialised.into_bytes()), "text/turtle")
2054                .await;
2055            finish_quota_reservation(&state, quota, write.is_ok()).await;
2056            let _ = write.map_err(to_actix)?;
2057            let provenance = git_mark_write(&state, &path, agent.as_deref(), "PATCH").await;
2058            let mut rsp = HttpResponse::Created().finish();
2059            set_provenance_headers(&mut rsp, &provenance);
2060            Ok(rsp)
2061        }
2062        Err(e) => Err(to_actix(e)),
2063    }
2064}
2065
2066/// Map a PATCH body parse error to 400 Bad Request. Distinguishes
2067/// "client sent garbage in a supported dialect" (400) from "client
2068/// chose an unsupported dialect" (415 — handled by the dispatcher).
2069fn patch_parse_err(e: PodError) -> ActixError {
2070    match e {
2071        PodError::Unsupported(msg) | PodError::BadRequest(msg) => {
2072            actix_web::error::ErrorBadRequest(msg)
2073        }
2074        other => to_actix(other),
2075    }
2076}
2077
2078/// Serialise a graph to N-Triples so the next GET reflects PATCH
2079/// mutations verbatim. Delegates to the library's canonical serialiser
2080/// — the handler does not add its own formatting.
2081fn graph_to_turtle(g: &ldp::Graph) -> String {
2082    g.to_ntriples()
2083}
2084
2085/// Parse an `Accept` header and return the highest-q *explicit* RDF
2086/// format named by the client. Unlike `ldp::negotiate_format`, wildcard
2087/// media ranges (`*/*`, `text/*`, `application/*`) are NOT mapped to a
2088/// default: a request that names no concrete RDF type yields `None`, so
2089/// the GET handler serves the stored representation verbatim instead of
2090/// surprising a browser (which sends `*/*`) with a transcode.
2091fn best_explicit_rdf_format(accept: &str) -> Option<ldp::RdfFormat> {
2092    let mut best: Option<(f32, ldp::RdfFormat)> = None;
2093    for entry in accept.split(',') {
2094        let entry = entry.trim();
2095        if entry.is_empty() {
2096            continue;
2097        }
2098        let mut parts = entry.split(';').map(|s| s.trim());
2099        let mime = match parts.next() {
2100            Some(m) => m,
2101            None => continue,
2102        };
2103        let mut q: f32 = 1.0;
2104        for token in parts {
2105            if let Some(v) = token.strip_prefix("q=") {
2106                if let Ok(parsed) = v.parse::<f32>() {
2107                    q = parsed;
2108                }
2109            }
2110        }
2111        // `from_mime` rejects wildcards, so only concrete RDF media types
2112        // ever enter the running.
2113        if let Some(format) = ldp::RdfFormat::from_mime(mime) {
2114            match best {
2115                None => best = Some((q, format)),
2116                Some((bq, _)) if q > bq => best = Some((q, format)),
2117                _ => {}
2118            }
2119        }
2120    }
2121    best.map(|(_, f)| f)
2122}
2123
2124/// RDF content negotiation for GET. When a client explicitly asks (via
2125/// `Accept`) for a concrete RDF serialisation different from how the
2126/// resource is stored, transcode the body and return the negotiated
2127/// `(bytes, content-type)`. KG resources persist as N-Triples (see the
2128/// PATCH handler), so an agent or extractor can GET the same graph as
2129/// Turtle, N-Triples, or JSON-LD on demand (PRD-014 Seam C / C4).
2130///
2131/// Returns `None` — meaning "serve the stored body verbatim" — when:
2132///   * the `Accept` header is empty,
2133///   * the stored content-type is not an RDF media type,
2134///   * the client named no concrete RDF type (only wildcards),
2135///   * the requested format equals the stored format (no transcode),
2136///   * the stored body does not parse as N-Triples (GET fails soft to
2137///     verbatim — it never destroys or misrepresents), or
2138///   * the requested target has no serialiser (RDF/XML).
2139fn rdf_content_negotiate(
2140    body: &[u8],
2141    stored_ct: &str,
2142    accept: &str,
2143) -> Option<(Vec<u8>, &'static str)> {
2144    if accept.trim().is_empty() {
2145        return None;
2146    }
2147    let stored_format = ldp::RdfFormat::from_mime(stored_ct)?;
2148    let target = best_explicit_rdf_format(accept)?;
2149    if target == stored_format {
2150        return None;
2151    }
2152    let text = std::str::from_utf8(body).ok()?;
2153    let graph = ldp::Graph::parse_ntriples(text).ok()?;
2154    match target {
2155        // N-Triples is a syntactic subset of Turtle; the canonical
2156        // serialiser emits N-Triples, which is valid Turtle.
2157        ldp::RdfFormat::Turtle => Some((
2158            graph.to_ntriples().into_bytes(),
2159            ldp::RdfFormat::Turtle.mime(),
2160        )),
2161        ldp::RdfFormat::NTriples => Some((
2162            graph.to_ntriples().into_bytes(),
2163            ldp::RdfFormat::NTriples.mime(),
2164        )),
2165        ldp::RdfFormat::JsonLd => {
2166            let json = serde_json::to_vec(&graph.to_jsonld()).ok()?;
2167            Some((json, ldp::RdfFormat::JsonLd.mime()))
2168        }
2169        // The hand-rolled graph has no RDF/XML serialiser; decline.
2170        ldp::RdfFormat::RdfXml => None,
2171    }
2172}
2173
2174/// Seed the PATCH working graph from the existing resource body so an
2175/// N3/SPARQL-Update mutation is applied on top of the triples already
2176/// stored. RDF resources are persisted as N-Triples (see `graph_to_turtle`),
2177/// so the current body round-trips through `Graph::parse_ntriples`. An
2178/// empty body yields an empty graph. A body that is neither empty nor
2179/// parseable N-Triples is REFUSED (409) rather than silently overwritten:
2180/// destroying a resource the patch engine cannot read back would violate
2181/// the non-destructive-write invariant (PRD-014 Seam C, DDD-012 A2).
2182fn seed_graph_from_patch_target(current_body: &[u8]) -> Result<ldp::Graph, ActixError> {
2183    let text = std::str::from_utf8(current_body).map_err(|_| {
2184        actix_web::error::ErrorConflict(
2185            "existing resource is not UTF-8 RDF; refusing destructive RDF PATCH",
2186        )
2187    })?;
2188    if text.trim().is_empty() {
2189        return Ok(ldp::Graph::new());
2190    }
2191    ldp::Graph::parse_ntriples(text).map_err(|_| {
2192        actix_web::error::ErrorConflict(
2193            "existing resource is not N-Triples RDF and cannot be non-destructively \
2194             patched; PUT an N-Triples representation or use a JSON Patch",
2195        )
2196    })
2197}
2198
2199/// Walk the storage tree from `path` upward, returning the first
2200/// `*.acl` document that parses as JSON-LD or Turtle.
2201///
2202/// Object-safe equivalent of `StorageAclResolver::find_effective_acl` — the
2203/// latter is generic over a concrete `Storage`, whereas the binary holds an
2204/// `Arc<dyn Storage>`.
2205///
2206/// **ADR-2005.** The walk itself is no longer duplicated here. Both this
2207/// function and `StorageAclResolver` now delegate to the single implementation
2208/// in `solid_pod_rs::wac::resolve_policy_from_storage`, so the native and
2209/// object-safe paths cannot drift apart on the missing / invalid / unavailable
2210/// distinction. This wrapper keeps the historical `Result<Option<_>, _>` shape
2211/// for callers that do not need the typed outcome; a malformed or unreadable
2212/// `.acl` now surfaces as `Err` instead of silently inheriting an ancestor's
2213/// broader grant.
2214pub(crate) async fn find_effective_acl_dyn(
2215    storage: &dyn Storage,
2216    resource_path: &str,
2217) -> Result<Option<wac::AclDocument>, PodError> {
2218    resolve_policy_dyn(storage, resource_path)
2219        .await
2220        .into_result()
2221}
2222
2223/// Typed-outcome resolution against a trait-object backend (ADR-2005).
2224///
2225/// The enforcement paths use this directly so they can deny on
2226/// `Invalid` / `Unavailable` rather than inheriting past them.
2227pub(crate) async fn resolve_policy_dyn(
2228    storage: &dyn Storage,
2229    resource_path: &str,
2230) -> wac::PolicyOutcome {
2231    wac::resolve_policy_from_storage(storage, resource_path).await
2232}
2233
2234/// Map a failed [`wac::PolicyOutcome`] onto the response the WAC gate must
2235/// return, and log it.
2236///
2237/// `Invalid` is the operator's own unparseable policy: deny with 403, exactly
2238/// as if the policy had granted nothing. Inheriting past it (the pre-ADR-2005
2239/// behaviour) would hand the caller an ancestor's broader rights.
2240/// `Unavailable` is a backend fault: the policy is unknown, so the request
2241/// cannot be authorised — 503, which is retryable and not mistakable for a
2242/// deliberate denial.
2243fn policy_failure_to_actix(outcome: &wac::PolicyOutcome, resource: &str) -> ActixError {
2244    match outcome {
2245        wac::PolicyOutcome::Invalid {
2246            policy_path,
2247            reason,
2248        } => {
2249            tracing::warn!(
2250                target: "solid_pod_rs_server::wac",
2251                resource = %resource,
2252                policy = %policy_path,
2253                "denying: effective ACL is invalid and MUST NOT inherit: {reason}"
2254            );
2255            actix_web::error::ErrorForbidden("access forbidden: governing ACL is invalid")
2256        }
2257        wac::PolicyOutcome::Unavailable {
2258            policy_path,
2259            detail,
2260        } => {
2261            tracing::error!(
2262                target: "solid_pod_rs_server::wac",
2263                resource = %resource,
2264                policy = %policy_path,
2265                "denying: effective ACL could not be read: {detail}"
2266            );
2267            actix_web::error::ErrorServiceUnavailable(
2268                "access control unavailable: governing ACL could not be read",
2269            )
2270        }
2271        // Not a failure — callers only reach here via `is_failure()`.
2272        _ => actix_web::error::ErrorInternalServerError("policy resolution error"),
2273    }
2274}
2275
2276async fn handle_delete(
2277    req: HttpRequest,
2278    state: web::Data<AppState>,
2279) -> Result<HttpResponse, ActixError> {
2280    let path = req.uri().path().to_string();
2281    let auth_pk = extract_pubkey(&req).await;
2282    let agent = agent_uri(auth_pk.as_ref());
2283    enforce_write_ctx(
2284        &state,
2285        &path,
2286        AccessMode::Write,
2287        agent.as_deref(),
2288        req_origin(&req),
2289    )
2290    .await?;
2291
2292    let quota = reserve_quota_for_size(&state, &path, 0).await?;
2293    match state.storage.delete(&path).await {
2294        Ok(()) => {
2295            finish_quota_reservation(&state, quota, true).await;
2296            Ok(HttpResponse::NoContent().finish())
2297        }
2298        Err(PodError::NotFound(_)) => Ok(HttpResponse::NotFound().finish()),
2299        Err(e) => Err(to_actix(e)),
2300    }
2301}
2302
2303async fn handle_options(
2304    req: HttpRequest,
2305    state: web::Data<AppState>,
2306) -> Result<HttpResponse, ActixError> {
2307    let path = req.uri().path().to_string();
2308    let o = ldp::options_for_conneg(&path, state.conneg_enabled);
2309    let mut rsp = HttpResponse::NoContent().finish();
2310    if let Ok(v) = header::HeaderValue::from_str(&o.allow.join(", ")) {
2311        rsp.headers_mut()
2312            .insert(header::HeaderName::from_static("allow"), v);
2313    }
2314    if let Some(ap) = o.accept_post {
2315        if let Ok(v) = header::HeaderValue::from_str(ap) {
2316            rsp.headers_mut()
2317                .insert(header::HeaderName::from_static("accept-post"), v);
2318        }
2319    }
2320    if let Ok(v) = header::HeaderValue::from_str(o.accept_patch) {
2321        rsp.headers_mut()
2322            .insert(header::HeaderName::from_static("accept-patch"), v);
2323    }
2324    if let Ok(v) = header::HeaderValue::from_str(o.accept_ranges) {
2325        rsp.headers_mut()
2326            .insert(header::HeaderName::from_static("accept-ranges"), v);
2327    }
2328    set_updates_via(&mut rsp, &state.nodeinfo.base_url);
2329    Ok(rsp)
2330}
2331
2332// ---------------------------------------------------------------------------
2333// .well-known handlers
2334// ---------------------------------------------------------------------------
2335
2336async fn handle_well_known_solid(state: web::Data<AppState>) -> HttpResponse {
2337    let doc = interop::well_known_solid(&state.nodeinfo.base_url, &state.nodeinfo.base_url);
2338    HttpResponse::Ok()
2339        .content_type("application/ld+json")
2340        .json(doc)
2341}
2342
2343#[derive(Debug, Deserialize)]
2344struct WebFingerQuery {
2345    resource: Option<String>,
2346}
2347
2348async fn handle_well_known_webfinger(
2349    state: web::Data<AppState>,
2350    q: web::Query<WebFingerQuery>,
2351) -> HttpResponse {
2352    let resource = q.resource.clone().unwrap_or_else(|| {
2353        format!(
2354            "acct:anonymous@{}",
2355            state
2356                .nodeinfo
2357                .base_url
2358                .trim_start_matches("http://")
2359                .trim_start_matches("https://")
2360        )
2361    });
2362    let webid = format!(
2363        "{}/profile/card#me",
2364        state.nodeinfo.base_url.trim_end_matches('/')
2365    );
2366    match interop::webfinger_response(&resource, &state.nodeinfo.base_url, &webid) {
2367        Some(jrd) => HttpResponse::Ok()
2368            .content_type("application/jrd+json")
2369            .json(jrd),
2370        None => HttpResponse::NotFound().finish(),
2371    }
2372}
2373
2374async fn handle_well_known_nodeinfo(state: web::Data<AppState>) -> HttpResponse {
2375    let doc = interop::nodeinfo_discovery(&state.nodeinfo.base_url);
2376    HttpResponse::Ok()
2377        .content_type("application/json")
2378        .json(doc)
2379}
2380
2381async fn handle_well_known_nodeinfo_2_1(state: web::Data<AppState>) -> HttpResponse {
2382    let doc = interop::nodeinfo_2_1(
2383        &state.nodeinfo.software_name,
2384        &state.nodeinfo.software_version,
2385        state.nodeinfo.open_registrations,
2386        state.nodeinfo.total_users,
2387    );
2388    HttpResponse::Ok()
2389        .content_type("application/json")
2390        .json(doc)
2391}
2392
2393#[cfg(feature = "did-nostr")]
2394async fn handle_well_known_did_nostr(
2395    state: web::Data<AppState>,
2396    path: web::Path<String>,
2397) -> HttpResponse {
2398    let pubkey = path.into_inner();
2399    // did:nostr Tier-1 resolution (https://nostrcg.github.io/did-nostr/): a
2400    // malformed identifier is a client error that must never be cached; a
2401    // valid 64-char lowercase-hex key yields a deterministic offline
2402    // (Tier-2) document. Mirrors the JSS resolver's per-status header policy.
2403    let pubkey_is_valid = pubkey.len() == 64
2404        && pubkey
2405            .bytes()
2406            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b));
2407    if !pubkey_is_valid {
2408        return HttpResponse::BadRequest()
2409            .insert_header(("Cache-Control", "no-store"))
2410            .json(serde_json::json!({
2411                "error": "invalid did:nostr pubkey (expected 64-char lowercase hex)"
2412            }));
2413    }
2414    // P1-l: this endpoint asserts an identity binding (did:nostr:<pubkey> ⇒
2415    // this pod's WebID via `alsoKnownAs`). Returning a document for ANY
2416    // well-formed pubkey asserted a FALSE binding for every key the pod
2417    // owner does not hold (and is flatly wrong on a multi-user pod). Resolve
2418    // the owner's declared Nostr key from the pod profile card and return
2419    // 404 ("no account claims this key", JSS behaviour) unless the queried
2420    // key is the owner's — mirroring the NIP-05 owner-resolution path.
2421    let owner_pubkey = match state.storage.get("/profile/card").await {
2422        Ok((body, _)) => solid_pod_rs::webid::extract_nostr_pubkey(&body)
2423            .ok()
2424            .flatten(),
2425        Err(_) => None,
2426    };
2427    let owner_claims_key = owner_pubkey
2428        .as_deref()
2429        .is_some_and(|owner| owner.eq_ignore_ascii_case(&pubkey));
2430    if !owner_claims_key {
2431        return HttpResponse::NotFound()
2432            .insert_header(("Cache-Control", "no-store"))
2433            .json(serde_json::json!({
2434                "error": "no account on this pod claims this did:nostr pubkey"
2435            }));
2436    }
2437    let also = vec![format!(
2438        "{}/profile/card#me",
2439        state.nodeinfo.base_url.trim_end_matches('/')
2440    )];
2441    let doc = interop::did_nostr::did_nostr_document(&pubkey, &also);
2442    let body = serde_json::to_string(&doc).unwrap_or_else(|_| "{}".to_string());
2443    // Feature-match the JSS Tier-1 header policy: max-age=3600 (the DID doc
2444    // seldom changes) + a weak ETag over the deterministic body. Last-Modified
2445    // is intentionally omitted — the document is generated deterministically
2446    // from the pubkey (Tier-2), so there is no underlying mutable resource to
2447    // date; the ETag is the correct validator here.
2448    use std::hash::{Hash, Hasher};
2449    let mut hasher = std::collections::hash_map::DefaultHasher::new();
2450    body.hash(&mut hasher);
2451    let etag = format!("\"{:016x}\"", hasher.finish());
2452    HttpResponse::Ok()
2453        .content_type("application/did+json")
2454        .insert_header(("Cache-Control", "max-age=3600"))
2455        .insert_header(("ETag", etag))
2456        .body(body)
2457}
2458
2459// ---------------------------------------------------------------------------
2460// JSS v0.0.190 Phase 1 port (issue #437) — pod-resident NIP-05 endpoint.
2461//
2462// Parity row 197. Feature `nip05-endpoint`. Resolves `?name=<local>`
2463// against the per-pod WebID `nostr:pubkey` triple.
2464// ---------------------------------------------------------------------------
2465
2466#[cfg(feature = "nip05-endpoint")]
2467#[derive(Debug, Deserialize)]
2468struct Nip05Query {
2469    /// Optional `name=<local>` query parameter per NIP-05. When
2470    /// absent, defaults to `_` (the pod owner / single-user mode).
2471    name: Option<String>,
2472}
2473
2474#[cfg(feature = "nip05-endpoint")]
2475fn nip05_name_is_valid(name: &str) -> bool {
2476    // NIP-05 §"Local part": ^[a-z0-9._-]+$ (case-insensitive in practice).
2477    // Also allow the singleton `_` which means "the pod owner".
2478    if name.is_empty() {
2479        return false;
2480    }
2481    name.bytes()
2482        .all(|b| b.is_ascii_alphanumeric() || b == b'.' || b == b'_' || b == b'-')
2483}
2484
2485#[cfg(feature = "nip05-endpoint")]
2486async fn handle_well_known_nip05(
2487    state: web::Data<AppState>,
2488    query: web::Query<Nip05Query>,
2489) -> HttpResponse {
2490    use solid_pod_rs::webid::extract_nostr_pubkey;
2491
2492    // JSS Phase 1 (issue #437) parity row 197.
2493    let name = query.name.clone().unwrap_or_else(|| "_".to_string());
2494    if !nip05_name_is_valid(&name) {
2495        return HttpResponse::BadRequest().json(serde_json::json!({
2496            "error": "invalid NIP-05 local part",
2497        }));
2498    }
2499
2500    // Single-pod-per-host: profile lives at `/profile/card`. Multi-user
2501    // path-based mode wires the bind via NormalizePath middleware,
2502    // so the lookup happens at the resolved storage path.
2503    // For `_` (default) we look up `/profile/card`. For a non-special
2504    // name we try `/<name>/profile/card` (multi-user path layout).
2505    let profile_path = if name == "_" {
2506        "/profile/card".to_string()
2507    } else {
2508        format!("/{name}/profile/card")
2509    };
2510
2511    let (body, _meta) = match state.storage.get(&profile_path).await {
2512        Ok(v) => v,
2513        Err(_) => {
2514            // Spec behaviour: return an empty `names` map with 200 OK
2515            // when the lookup yields nothing. Damus / nos.lol use this
2516            // shape to mean "no such user".
2517            return nip05_empty_response();
2518        }
2519    };
2520
2521    let pubkey_hex = match extract_nostr_pubkey(&body) {
2522        Ok(Some(p)) => p,
2523        _ => return nip05_empty_response(),
2524    };
2525
2526    let doc = interop::nip05_document([(name, pubkey_hex)]);
2527    HttpResponse::Ok()
2528        .insert_header(("Access-Control-Allow-Origin", "*"))
2529        .content_type("application/json")
2530        .json(doc)
2531}
2532
2533#[cfg(feature = "nip05-endpoint")]
2534fn nip05_empty_response() -> HttpResponse {
2535    HttpResponse::Ok()
2536        .insert_header(("Access-Control-Allow-Origin", "*"))
2537        .content_type("application/json")
2538        .json(serde_json::json!({ "names": {} }))
2539}
2540
2541// ---------------------------------------------------------------------------
2542// JSS v0.0.190 Phase 1 port (issue #437), parity row 198.
2543// JSON-LD time-chain pod export (`GET /api/exports/all`). NATIVE-ONLY:
2544// gated behind `export-jsonld` (default-off); the CF-Workers pod tier does
2545// not walk a local storage tree. `solid_pod_rs::export::export_pod_jsonld`
2546// is the pure-logic walker — this handler adds the HTTP surface + WAC gate.
2547// ---------------------------------------------------------------------------
2548
2549/// `GET /api/exports/all` — export the whole pod as a JSON-LD time-chain
2550/// bundle. Owner-gated: the caller must hold `acl:Control` on the pod root
2551/// (`/`), because the bundle can expose every resource — including
2552/// `/private/*` when `?include_private=true` — bypassing per-resource ACLs.
2553/// A Control credential is therefore the correct (highest) authorisation.
2554#[cfg(feature = "export-jsonld")]
2555async fn handle_export_all(
2556    req: HttpRequest,
2557    state: web::Data<AppState>,
2558) -> Result<HttpResponse, ActixError> {
2559    let auth_pk = extract_pubkey(&req).await;
2560    let agent = agent_uri(auth_pk.as_ref());
2561
2562    // Owner gate: require `acl:Control` on the pod root. `enforce_write_ctx`
2563    // evaluates the passed mode against the root ACL and returns the shared
2564    // 401/403 WAC denial; `Control` bypasses the origin gate by design so an
2565    // owner can always export from any origin.
2566    enforce_write_ctx(
2567        &state,
2568        "/",
2569        AccessMode::Control,
2570        agent.as_deref(),
2571        req_origin(&req),
2572    )
2573    .await?;
2574
2575    // `include_private=true` is honoured only for this Control-authorised
2576    // caller (the export function itself is unauthenticated — the gate above
2577    // is the credential the docs require before flipping the flag).
2578    let include_private = web::Query::<HashMap<String, String>>::from_query(req.query_string())
2579        .ok()
2580        .and_then(|q| q.get("include_private").map(|v| v == "true"))
2581        .unwrap_or(false);
2582
2583    // Pod base URL stamped into the bundle envelope: the externally-visible
2584    // scheme + host (honours `X-Forwarded-Proto`), matching the URL agents
2585    // sign over elsewhere in this file.
2586    let pod_base = format!("{}/", scheme::request_origin(&req));
2587
2588    let options = solid_pod_rs::ExportOptions { include_private };
2589    let bundle = solid_pod_rs::export::export_pod_jsonld(&*state.storage, &pod_base, options)
2590        .await
2591        .map_err(to_actix)?;
2592
2593    let body = serde_json::to_vec(&bundle).map_err(|e| {
2594        actix_web::error::ErrorInternalServerError(format!("export serialise: {e}"))
2595    })?;
2596    Ok(HttpResponse::Ok()
2597        .content_type(solid_pod_rs::export::EXPORT_CONTENT_TYPE)
2598        .body(body))
2599}
2600
2601// ---------------------------------------------------------------------------
2602// Pod management API (JSS parity: /api/accounts/*)
2603// ---------------------------------------------------------------------------
2604
2605#[derive(Debug, Deserialize)]
2606struct CreateAccountRequest {
2607    username: String,
2608    #[serde(default)]
2609    name: Option<String>,
2610}
2611
2612#[derive(Debug, Deserialize)]
2613struct CreatePodRequest {
2614    name: String,
2615}
2616
2617async fn handle_pod_check(state: web::Data<AppState>, path: web::Path<String>) -> HttpResponse {
2618    let pod_name = path.into_inner();
2619    let pod_root = format!("/{pod_name}/");
2620    match state.storage.exists(&pod_root).await {
2621        Ok(true) => HttpResponse::Ok().json(serde_json::json!({"exists": true})),
2622        _ => HttpResponse::NotFound().json(serde_json::json!({"exists": false})),
2623    }
2624}
2625
2626fn valid_pod_name(name: &str) -> bool {
2627    !name.is_empty()
2628        && name
2629            .chars()
2630            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_'))
2631}
2632
2633fn request_ip(req: &HttpRequest) -> IpAddr {
2634    req.peer_addr()
2635        .map(|addr| addr.ip())
2636        .unwrap_or(IpAddr::V4(Ipv4Addr::LOCALHOST))
2637}
2638
2639#[derive(Debug)]
2640struct QuotaReservation {
2641    pod: String,
2642    delta: i64,
2643}
2644
2645fn pod_name_from_path(path: &str) -> Option<&str> {
2646    path.trim_start_matches('/')
2647        .split('/')
2648        .next()
2649        .filter(|p| !p.is_empty())
2650}
2651
2652async fn reserve_quota_for_size(
2653    state: &AppState,
2654    path: &str,
2655    new_size: u64,
2656) -> Result<Option<QuotaReservation>, ActixError> {
2657    let (Some(policy), Some(pod)) = (&state.quota, pod_name_from_path(path)) else {
2658        return Ok(None);
2659    };
2660    let old_size = state
2661        .storage
2662        .head(path)
2663        .await
2664        .map(|meta| meta.size)
2665        .unwrap_or(0);
2666    let delta = i128::from(new_size) - i128::from(old_size);
2667    let delta = delta.clamp(i64::MIN as i128, i64::MAX as i128) as i64;
2668    if delta > 0 {
2669        policy
2670            .reserve(pod, delta as u64)
2671            .await
2672            .map_err(|error| actix_web::error::ErrorInsufficientStorage(error.to_string()))?;
2673    }
2674    Ok(Some(QuotaReservation {
2675        pod: pod.to_string(),
2676        delta,
2677    }))
2678}
2679
2680async fn finish_quota_reservation(
2681    state: &AppState,
2682    reservation: Option<QuotaReservation>,
2683    write_succeeded: bool,
2684) {
2685    let (Some(policy), Some(reservation)) = (&state.quota, reservation) else {
2686        return;
2687    };
2688    if write_succeeded {
2689        if reservation.delta < 0 {
2690            policy.record(&reservation.pod, reservation.delta).await;
2691        }
2692    } else if reservation.delta > 0 {
2693        policy.record(&reservation.pod, -reservation.delta).await;
2694    }
2695}
2696
2697async fn handle_create_account(
2698    req: HttpRequest,
2699    state: web::Data<AppState>,
2700    body: web::Json<CreateAccountRequest>,
2701) -> Result<HttpResponse, ActixError> {
2702    if let Some(response) = provisioning_gate(&req, &state, &body.username).await {
2703        return Ok(response);
2704    }
2705    let pod_root = format!("/{}/", body.username);
2706    if state.storage.exists(&pod_root).await.unwrap_or(false) {
2707        return Ok(
2708            HttpResponse::Conflict().json(serde_json::json!({"error": "account already exists"}))
2709        );
2710    }
2711
2712    let base_uri = state.nodeinfo.base_url.trim_end_matches('/');
2713    let outcome =
2714        provision_named_pod(&state, &body.username, body.name.as_deref(), base_uri).await?;
2715    Ok(HttpResponse::Created().json(serde_json::json!({
2716        "webid": outcome.webid,
2717        "pod_root": outcome.pod_uri,
2718        "username": body.username,
2719    })))
2720}
2721
2722struct NamedPodOutcome {
2723    webid: String,
2724    pod_uri: String,
2725}
2726
2727/// Apply the same closed-by-default registration policy, validation, and
2728/// per-IP rate limiter to every public provisioning surface.
2729async fn provisioning_gate(
2730    req: &HttpRequest,
2731    state: &AppState,
2732    name: &str,
2733) -> Option<HttpResponse> {
2734    if !valid_pod_name(name) {
2735        return Some(HttpResponse::BadRequest().json(serde_json::json!({
2736            "error": "Invalid pod name. Use alphanumeric, dash, or underscore only."
2737        })));
2738    }
2739
2740    let supplied_key = req
2741        .headers()
2742        .get("x-pod-admin-key")
2743        .and_then(|value| value.to_str().ok())
2744        .unwrap_or("");
2745    use subtle::ConstantTimeEq;
2746    let admin_override = state
2747        .admin_key
2748        .as_deref()
2749        .is_some_and(|expected| bool::from(supplied_key.as_bytes().ct_eq(expected.as_bytes())));
2750    let invite = req
2751        .headers()
2752        .get("x-invite-token")
2753        .and_then(|v| v.to_str().ok())
2754        .map(str::trim)
2755        .filter(|t| !t.is_empty());
2756    let closed = !state.nodeinfo.open_registrations && !admin_override;
2757    if closed && invite.is_none() {
2758        return Some(HttpResponse::Forbidden().json(serde_json::json!({
2759            "error": "pod registration is closed"
2760        })));
2761    }
2762
2763    if let Err(retry_after) = state.pod_create_limiter.check(request_ip(req)) {
2764        return Some(
2765            HttpResponse::TooManyRequests()
2766                .insert_header(("Retry-After", retry_after.to_string()))
2767                .json(serde_json::json!({
2768                    "error": "Too Many Requests",
2769                    "message": "Pod creation rate limit exceeded",
2770                    "retryAfter": retry_after
2771                })),
2772        );
2773    }
2774    // Registration is closed and the caller brought an invite: redeem it
2775    // (JSS `validateInvite`). The use is recorded before the pod exists, so a
2776    // single-use invite cannot be spent twice by racing requests; a request
2777    // that then fails validation downstream has still used it.
2778    if closed {
2779        let (Some(token), Some(root)) = (invite, state.data_root.as_deref()) else {
2780            return Some(HttpResponse::Forbidden().json(serde_json::json!({
2781                "error": "pod registration is closed"
2782            })));
2783        };
2784        let refusal =
2785            |why: &str| HttpResponse::Forbidden().json(serde_json::json!({ "error": why }));
2786        match cli::FileInviteStore::new(root).consume(token).await {
2787            Ok(cli::Consume::Granted) => {}
2788            Ok(cli::Consume::Expired) => return Some(refusal("invite has expired")),
2789            Ok(cli::Consume::Exhausted) => return Some(refusal("invite has been used")),
2790            Ok(cli::Consume::Unknown) => return Some(refusal("invalid invite code")),
2791            Err(e) => {
2792                tracing::error!("invite store: {e}");
2793                return Some(
2794                    HttpResponse::InternalServerError()
2795                        .json(serde_json::json!({ "error": "invite store unavailable" })),
2796                );
2797            }
2798        }
2799    }
2800    None
2801}
2802
2803/// Provision only below `/{name}/`; the core `provision_pod` helper expects a
2804/// pod-scoped storage view and must not be called with the server's global
2805/// storage backend.
2806async fn provision_named_pod(
2807    state: &AppState,
2808    name: &str,
2809    display_name: Option<&str>,
2810    base_uri: &str,
2811) -> Result<NamedPodOutcome, ActixError> {
2812    for container in ["", "profile", "inbox", "public", "private", "settings"] {
2813        let path = if container.is_empty() {
2814            format!("/{name}")
2815        } else {
2816            format!("/{name}/{container}")
2817        };
2818        state
2819            .storage
2820            .put(
2821                &format!("{path}.meta"),
2822                Bytes::from_static(b"{}"),
2823                "application/ld+json",
2824            )
2825            .await
2826            .map_err(to_actix)?;
2827    }
2828
2829    let base_uri = base_uri.trim_end_matches('/');
2830    let pod_uri = format!("{base_uri}/{name}/");
2831    let canonical_prefix = format!("{base_uri}/pods/{name}/");
2832    let webid = format!("{pod_uri}profile/card#me");
2833    let profile = solid_pod_rs::webid::generate_webid_html(name, display_name, base_uri)
2834        .replace(&canonical_prefix, &pod_uri);
2835    state
2836        .storage
2837        .put(
2838            &format!("/{name}/profile/card"),
2839            Bytes::from(profile.into_bytes()),
2840            "text/html",
2841        )
2842        .await
2843        .map_err(to_actix)?;
2844
2845    #[cfg(feature = "git")]
2846    if let Some(root) = &state.data_root {
2847        let hook = solid_pod_rs_git::init::GitAutoInit::new();
2848        if let Err(error) = hook.init_repo_at(&root.join(name)).await {
2849            tracing::warn!(pod = name, %error, "git auto-init failed after pod creation");
2850        }
2851    }
2852
2853    Ok(NamedPodOutcome { webid, pod_uri })
2854}
2855
2856async fn handle_create_pod(
2857    req: HttpRequest,
2858    state: web::Data<AppState>,
2859    body: web::Json<CreatePodRequest>,
2860) -> Result<HttpResponse, ActixError> {
2861    if let Some(response) = provisioning_gate(&req, &state, &body.name).await {
2862        return Ok(response);
2863    }
2864
2865    let pod_root = format!("/{}/", body.name);
2866    if state.storage.exists(&pod_root).await.unwrap_or(false) {
2867        return Ok(
2868            HttpResponse::Conflict().json(serde_json::json!({"error": "Pod already exists"}))
2869        );
2870    }
2871
2872    let base_uri = scheme::request_origin(&req);
2873    let outcome = provision_named_pod(&state, &body.name, None, &base_uri).await?;
2874
2875    Ok(HttpResponse::Created()
2876        .insert_header(("Location", outcome.pod_uri.clone()))
2877        .json(serde_json::json!({
2878            "name": body.name,
2879            "webId": outcome.webid,
2880            "podUri": outcome.pod_uri,
2881        })))
2882}
2883
2884// ---------------------------------------------------------------------------
2885// HTTP COPY (JSS parity: handlers/copy.mjs)
2886// ---------------------------------------------------------------------------
2887
2888/// Reduce a COPY `Source` header to a pod path. An absolute URL is accepted
2889/// only for this server's own `host` and is stripped to its path; any other
2890/// host is refused, as are relative references, `.`/`..` segments (also
2891/// percent-encoded) and query or fragment parts. The result is the
2892/// [`canonical_pod_path`] spelling, decoded and cleaned. `None` means reject.
2893fn normalise_copy_source(raw: &str, host: &str) -> Option<String> {
2894    let path = if raw.starts_with("http://") || raw.starts_with("https://") {
2895        let url = url::Url::parse(raw).ok()?;
2896        let authority = match url.port() {
2897            Some(port) => format!("{}:{port}", url.host_str()?),
2898            None => url.host_str()?.to_string(),
2899        };
2900        if !authority.eq_ignore_ascii_case(host)
2901            || url.query().is_some()
2902            || url.fragment().is_some()
2903        {
2904            return None;
2905        }
2906        url.path().to_string()
2907    } else if raw.starts_with('/') && !raw.contains(['?', '#']) {
2908        raw.to_string()
2909    } else {
2910        return None;
2911    };
2912    canonical_pod_path(&path)
2913}
2914
2915async fn handle_copy(
2916    req: HttpRequest,
2917    state: web::Data<AppState>,
2918) -> Result<HttpResponse, ActixError> {
2919    let dest = req.uri().path().to_string();
2920    let auth_pk = extract_pubkey(&req).await;
2921    let agent = agent_uri(auth_pk.as_ref());
2922    enforce_write_ctx(
2923        &state,
2924        &dest,
2925        AccessMode::Write,
2926        agent.as_deref(),
2927        req_origin(&req),
2928    )
2929    .await?;
2930
2931    let source = req
2932        .headers()
2933        .get("source")
2934        .and_then(|v| v.to_str().ok())
2935        .map(|s| s.to_string());
2936    let source = match source {
2937        Some(s) => s,
2938        None => return Ok(HttpResponse::BadRequest().body("Source header required")),
2939    };
2940    let host = scheme::request_host(&req);
2941    let source = match normalise_copy_source(&source, &host) {
2942        Some(s) => s,
2943        None => return Ok(HttpResponse::BadRequest().body("invalid Source")),
2944    };
2945    if !state.dotfiles.is_allowed(Path::new(&source)) {
2946        return Ok(HttpResponse::Forbidden().body("dotfile path denied by allowlist"));
2947    }
2948    // The Source is a read of another resource: it needs the same `acl:Read`
2949    // (sidecars and trail secrets: `acl:Control`) as a plain GET of it.
2950    enforce_read_ctx(&state, &source, agent.as_deref(), req_origin(&req)).await?;
2951
2952    let (body, meta) = match state.storage.get(&source).await {
2953        Ok(v) => v,
2954        Err(PodError::NotFound(_)) => {
2955            return Ok(HttpResponse::NotFound().body("source resource not found"))
2956        }
2957        Err(e) => return Err(to_actix(e)),
2958    };
2959
2960    // Same lockout guard as `handle_put` when the destination is a sidecar.
2961    if protected_resource_for_acl(&dest).is_some()
2962        && !proposed_acl_keeps_caller_control(&body, &meta.content_type, agent.as_deref())
2963    {
2964        return Ok(HttpResponse::Conflict().body(
2965            "refused: the proposed ACL would not grant Control to the caller \
2966             (use an absolute WebID, foaf:Agent, or acl:AuthenticatedAgent)",
2967        ));
2968    }
2969
2970    let quota = reserve_quota_for_size(&state, &dest, body.len() as u64).await?;
2971    let write = state.storage.put(&dest, body, &meta.content_type).await;
2972    finish_quota_reservation(&state, quota, write.is_ok()).await;
2973    write.map_err(to_actix)?;
2974
2975    // Copy the ACL sidecar only for a caller who holds Control on both the
2976    // source (to read it) and the destination (to write it), and only if the
2977    // copy keeps their own Control. Otherwise it is skipped: the resource
2978    // copy above stands, but no one gains or loses access through COPY.
2979    let src_acl = format!("{}.acl", source.trim_end_matches('/'));
2980    let dst_acl = format!("{}.acl", dest.trim_end_matches('/'));
2981    if let Ok((acl_body, acl_meta)) = state.storage.get(&src_acl).await {
2982        let origin = req_origin(&req);
2983        let permitted = enforce_read_ctx(&state, &src_acl, agent.as_deref(), origin)
2984            .await
2985            .is_ok()
2986            && enforce_write_ctx(
2987                &state,
2988                &dst_acl,
2989                AccessMode::Write,
2990                agent.as_deref(),
2991                origin,
2992            )
2993            .await
2994            .is_ok()
2995            && proposed_acl_keeps_caller_control(
2996                &acl_body,
2997                &acl_meta.content_type,
2998                agent.as_deref(),
2999            );
3000        if permitted {
3001            let quota = reserve_quota_for_size(&state, &dst_acl, acl_body.len() as u64).await?;
3002            let write = state
3003                .storage
3004                .put(&dst_acl, acl_body, &acl_meta.content_type)
3005                .await;
3006            finish_quota_reservation(&state, quota, write.is_ok()).await;
3007            write.map_err(to_actix)?;
3008        }
3009    }
3010
3011    let mut rsp = HttpResponse::Created().finish();
3012    if let Ok(loc) = header::HeaderValue::from_str(&dest) {
3013        rsp.headers_mut().insert(header::LOCATION, loc);
3014    }
3015    Ok(rsp)
3016}
3017
3018// ---------------------------------------------------------------------------
3019// Glob GET (JSS parity: handlers/get.mjs globHandler)
3020// ---------------------------------------------------------------------------
3021
3022async fn handle_glob_get(
3023    req: HttpRequest,
3024    state: web::Data<AppState>,
3025) -> Result<HttpResponse, ActixError> {
3026    let raw_path = req.uri().path().to_string();
3027    // JSS only supports the pattern `{folder}/*`
3028    if !raw_path.ends_with("/*") {
3029        return Ok(HttpResponse::NotFound().body("unsupported glob pattern"));
3030    }
3031    let folder = &raw_path[..raw_path.len() - 1]; // strip trailing `*`
3032    let folder = if folder.ends_with('/') {
3033        folder.to_string()
3034    } else {
3035        format!("{folder}/")
3036    };
3037
3038    // P0-1: the glob handler merges every RDF child in `folder` — gate it
3039    // on `acl:Read` of the folder so `GET /private/*` cannot bypass the
3040    // read-authz check applied to plain container GETs.
3041    let auth_pk = extract_pubkey(&req).await;
3042    let agent = agent_uri(auth_pk.as_ref());
3043    let origin = req_origin(&req);
3044    let audience = enforce_read_ctx(&state, &folder, agent.as_deref(), origin).await?;
3045
3046    let children = state.storage.list(&folder).await.map_err(to_actix)?;
3047    let mut merged = String::new();
3048    let mut audience = audience;
3049
3050    for child in &children {
3051        if child.ends_with('/')
3052            || child.ends_with(".acl")
3053            || child.ends_with(".meta")
3054            || child.ends_with(".prov.ttl")
3055        {
3056            continue;
3057        }
3058        let child_path = format!("{folder}{child}");
3059        // Each child needs its own `acl:Read`; one that is refused (or is
3060        // pay-per-read, which a glob must not bill once per child) is left out.
3061        match enforce_read_inner(&state, &child_path, agent.as_deref(), origin, false).await {
3062            Ok(ResponseAudience::Private) => audience = ResponseAudience::Private,
3063            Ok(ResponseAudience::Public) => {}
3064            Err(_) => continue,
3065        }
3066        if let Ok((body, meta)) = state.storage.get(&child_path).await {
3067            if meta.content_type.contains("turtle")
3068                || meta.content_type.contains("n-triples")
3069                || meta.content_type.contains("n3")
3070            {
3071                if let Ok(text) = std::str::from_utf8(&body) {
3072                    merged.push_str(text);
3073                    merged.push('\n');
3074                }
3075            }
3076        }
3077    }
3078
3079    if merged.is_empty() {
3080        return Ok(HttpResponse::NotFound().body("no matching RDF resources"));
3081    }
3082
3083    let mut rsp = HttpResponse::Ok().content_type("text/turtle").body(merged);
3084    set_cache_policy(&mut rsp, "text/turtle", audience);
3085    Ok(rsp)
3086}
3087
3088// ---------------------------------------------------------------------------
3089// Login + password reset (JSS parity: wired to IdP crate)
3090// ---------------------------------------------------------------------------
3091
3092#[derive(Debug, Deserialize)]
3093struct LoginPasswordRequest {
3094    username: String,
3095    password: String,
3096}
3097
3098/// Password login is **not implemented** in this build. Returning a synthetic
3099/// `200 { "message": "login endpoint active" }` (the previous behaviour) is a
3100/// security hazard: a client cannot distinguish it from a genuine successful
3101/// authentication and may treat the caller as logged in. Until a real
3102/// credential verifier is wired to the IdP crate, this returns
3103/// `501 Not Implemented` so no caller mistakes the stub for success.
3104async fn handle_login_password(body: web::Json<LoginPasswordRequest>) -> HttpResponse {
3105    let _ = (&body.username, &body.password);
3106    HttpResponse::NotImplemented().json(serde_json::json!({
3107        "error": "password login is not implemented on this pod"
3108    }))
3109}
3110
3111#[derive(Debug, Deserialize)]
3112struct PasswordResetRequest {
3113    username: String,
3114}
3115
3116/// Password reset is **not implemented**. The prior stub returned a plausible
3117/// "a reset link has been sent" success; that falsely signals a working reset
3118/// flow. Return `501 Not Implemented` instead of faking success.
3119async fn handle_password_reset_request(body: web::Json<PasswordResetRequest>) -> HttpResponse {
3120    let _ = &body.username;
3121    HttpResponse::NotImplemented().json(serde_json::json!({
3122        "error": "password reset is not implemented on this pod"
3123    }))
3124}
3125
3126#[derive(Debug, Deserialize)]
3127struct PasswordChangeRequest {
3128    token: String,
3129    new_password: String,
3130}
3131
3132/// Password change is **not implemented**. The prior stub returned
3133/// `200 { "message": "password changed" }` without changing anything — a
3134/// caller could believe a new password is in effect. Return
3135/// `501 Not Implemented` rather than fake success.
3136async fn handle_password_change(body: web::Json<PasswordChangeRequest>) -> HttpResponse {
3137    let _ = (&body.token, &body.new_password);
3138    HttpResponse::NotImplemented().json(serde_json::json!({
3139        "error": "password change is not implemented on this pod"
3140    }))
3141}
3142
3143// ---------------------------------------------------------------------------
3144// Payment endpoint (JSS parity: GET /pay/.info)
3145// ---------------------------------------------------------------------------
3146
3147async fn handle_pay_info(state: web::Data<AppState>) -> HttpResponse {
3148    let body = solid_pod_rs::payments::pay_info(&state.pay_config);
3149    HttpResponse::Ok()
3150        .content_type("application/json")
3151        .json(body)
3152}
3153
3154// ---------------------------------------------------------------------------
3155// WAC-gated CORS proxy endpoint — GET /proxy?url=<url>
3156//
3157// Proxies HTTP requests to external URLs after WAC authentication and
3158// SSRF validation. Defence-in-depth:
3159//   1. WAC auth required (reuses existing NIP-98 auth).
3160//   2. Target URL validated against SSRF blocklist (no private/loopback IPs).
3161//   3. Byte cap enforced (default 50 MB).
3162//   4. Redirect targets re-validated against SSRF blocklist.
3163//   5. Sensitive response headers stripped (Set-Cookie, Authorization).
3164//   6. X-Upstream-Authorization header forwarded if present.
3165// ---------------------------------------------------------------------------
3166
3167/// Default byte cap for proxied responses (50 MiB).
3168pub const DEFAULT_PROXY_BYTE_CAP: usize = 50 * 1024 * 1024;
3169
3170/// Query parameters for the proxy endpoint.
3171#[derive(Debug, Deserialize)]
3172struct ProxyQuery {
3173    url: String,
3174}
3175
3176/// Headers that are stripped from the proxied response for security.
3177const STRIPPED_RESPONSE_HEADERS: &[&str] = &[
3178    "set-cookie",
3179    "set-cookie2",
3180    "authorization",
3181    "www-authenticate",
3182    "proxy-authenticate",
3183    "proxy-authorization",
3184];
3185
3186/// Validate that a URL target is safe for proxying (SSRF protection) and
3187/// return the URL together with the **resolved** IP the connection must be
3188/// pinned to.
3189///
3190/// Layered defence, in order:
3191///   1. scheme allowlist (`http`/`https` only);
3192///   2. literal-host fast reject (IP literals + known cloud-metadata names) —
3193///      [`solid_pod_rs::security::is_safe_url`];
3194///   3. textual `localhost` / unspecified-address variants;
3195///   4. **DNS resolution** via [`solid_pod_rs::security::resolve_and_check`],
3196///      which rejects any hostname resolving to private/loopback/link-local/
3197///      reserved space. The returned `IpAddr` MUST be pinned on the outbound
3198///      client (`ClientBuilder::resolve`) so the socket connects to exactly
3199///      the address that was vetted — closing the DNS-rebinding window between
3200///      this check and the connect, and re-checked on every redirect hop.
3201async fn validate_proxy_target(target: &str) -> Result<(url::Url, IpAddr), HttpResponse> {
3202    let parsed = match url::Url::parse(target) {
3203        Ok(u) => u,
3204        Err(_) => {
3205            return Err(
3206                HttpResponse::BadRequest().json(serde_json::json!({"error": "invalid target URL"}))
3207            );
3208        }
3209    };
3210
3211    // Only HTTP(S) schemes are allowed.
3212    match parsed.scheme() {
3213        "http" | "https" => {}
3214        scheme => {
3215            return Err(HttpResponse::BadRequest()
3216                .json(serde_json::json!({"error": format!("unsupported scheme: {scheme}")})));
3217        }
3218    }
3219
3220    // SSRF guard: reject URLs with private/loopback/link-local IP hosts
3221    // (literal-host + metadata-hostname fast path, no DNS).
3222    if solid_pod_rs::security::is_safe_url(target).is_err() {
3223        return Err(HttpResponse::Forbidden()
3224            .json(serde_json::json!({"error": "target URL blocked by SSRF policy"})));
3225    }
3226
3227    // Additional hostname-based checks for common SSRF bypass patterns.
3228    let host = match parsed.host_str() {
3229        Some(h) => h.to_string(),
3230        None => {
3231            return Err(HttpResponse::BadRequest()
3232                .json(serde_json::json!({"error": "target URL has no host"})))
3233        }
3234    };
3235    let host_lower = host.to_ascii_lowercase();
3236    if host_lower == "localhost"
3237        || host_lower.ends_with(".localhost")
3238        || host_lower == "0.0.0.0"
3239        || host_lower == "[::1]"
3240        || host_lower == "[::0]"
3241    {
3242        return Err(HttpResponse::Forbidden()
3243            .json(serde_json::json!({"error": "target URL blocked by SSRF policy"})));
3244    }
3245
3246    // DNS-resolving check (rebinding guard): resolve the host and reject if
3247    // ANY resolved address is in blocked space. Returns the pinned IP.
3248    match solid_pod_rs::security::resolve_and_check(&host).await {
3249        Ok(ip) => Ok((parsed, ip)),
3250        Err(_) => Err(HttpResponse::Forbidden()
3251            .json(serde_json::json!({"error": "target URL blocked by SSRF policy"}))),
3252    }
3253}
3254
3255/// Build an outbound proxy client with redirects disabled and DNS pinned to
3256/// `ip` for `url`'s host — the connection targets exactly the vetted address.
3257fn build_pinned_proxy_client(url: &url::Url, ip: IpAddr) -> Result<reqwest::Client, ActixError> {
3258    let mut builder = reqwest::Client::builder()
3259        // Never follow redirects automatically — each hop is re-validated and
3260        // re-pinned by the caller.
3261        .redirect(reqwest::redirect::Policy::none());
3262    if let Some(host) = url.host_str() {
3263        // Port 0 ⇒ reqwest uses the URL's port (per its `resolve` docs).
3264        let port = url.port_or_known_default().unwrap_or(0);
3265        builder = builder.resolve(host, std::net::SocketAddr::new(ip, port));
3266    }
3267    builder
3268        .build()
3269        .map_err(|e| actix_web::error::ErrorInternalServerError(format!("proxy client: {e}")))
3270}
3271
3272async fn handle_proxy(
3273    req: HttpRequest,
3274    _state: web::Data<AppState>,
3275    query: web::Query<ProxyQuery>,
3276) -> Result<HttpResponse, ActixError> {
3277    // 1. WAC authentication — require an authenticated agent.
3278    let auth_pk = extract_pubkey(&req).await;
3279    let agent = agent_uri(auth_pk.as_ref());
3280    if agent.is_none() {
3281        return Ok(HttpResponse::Unauthorized()
3282            .json(serde_json::json!({"error": "authentication required"})));
3283    }
3284
3285    let mut current_url = query.url.clone();
3286    let mut redirect_count = 0u8;
3287    const MAX_REDIRECTS: u8 = 5;
3288    const TOTAL_TIMEOUT: Duration = Duration::from_secs(30);
3289    let started = Instant::now();
3290
3291    let byte_cap = std::env::var("PROXY_BYTE_CAP")
3292        .ok()
3293        .and_then(|v| {
3294            solid_pod_rs::config::sources::parse_size(&v)
3295                .map(|u| u as usize)
3296                .ok()
3297        })
3298        .unwrap_or(DEFAULT_PROXY_BYTE_CAP);
3299
3300    loop {
3301        let Some(remaining) = TOTAL_TIMEOUT.checked_sub(started.elapsed()) else {
3302            return Ok(HttpResponse::GatewayTimeout()
3303                .json(serde_json::json!({"error": "proxy operation timed out"})));
3304        };
3305        // Validate + DNS-resolve EVERY hop (initial request and each redirect
3306        // target), then pin the outbound client to the resolved IP so the
3307        // socket connects to exactly the vetted address (DNS-rebinding guard).
3308        let (target_url, pinned_ip) = match validate_proxy_target(&current_url).await {
3309            Ok(pair) => pair,
3310            Err(rsp) => return Ok(rsp),
3311        };
3312        let client = build_pinned_proxy_client(&target_url, pinned_ip)?;
3313
3314        let mut upstream_req = client.get(&current_url).timeout(remaining);
3315
3316        // Forward X-Upstream-Authorization if present.
3317        if let Some(auth_val) = req
3318            .headers()
3319            .get("x-upstream-authorization")
3320            .and_then(|v| v.to_str().ok())
3321        {
3322            upstream_req = upstream_req.header("Authorization", auth_val);
3323        }
3324
3325        let response = upstream_req
3326            .send()
3327            .await
3328            .map_err(|e| actix_web::error::ErrorBadGateway(format!("upstream error: {e}")))?;
3329
3330        // Handle redirects with SSRF re-validation.
3331        if response.status().is_redirection() {
3332            if redirect_count >= MAX_REDIRECTS {
3333                return Ok(HttpResponse::BadGateway()
3334                    .json(serde_json::json!({"error": "too many redirects"})));
3335            }
3336            if let Some(location) = response.headers().get("location") {
3337                let loc_str = location
3338                    .to_str()
3339                    .map_err(|_| actix_web::error::ErrorBadGateway("invalid redirect location"))?;
3340                // Resolve relative redirects against current URL.
3341                let base = url::Url::parse(&current_url)
3342                    .map_err(|_| actix_web::error::ErrorBadGateway("invalid current URL"))?;
3343                let resolved = base
3344                    .join(loc_str)
3345                    .map_err(|_| actix_web::error::ErrorBadGateway("invalid redirect URL"))?;
3346                current_url = resolved.to_string();
3347                redirect_count += 1;
3348                continue;
3349            }
3350            return Ok(HttpResponse::BadGateway()
3351                .json(serde_json::json!({"error": "redirect without location"})));
3352        }
3353
3354        // Read the response body with byte cap enforcement.
3355        let upstream_status = response.status().as_u16();
3356        let upstream_content_type = response
3357            .headers()
3358            .get("content-type")
3359            .and_then(|v| v.to_str().ok())
3360            .unwrap_or("application/octet-stream")
3361            .to_string();
3362        if response
3363            .content_length()
3364            .is_some_and(|length| length > byte_cap as u64)
3365        {
3366            return Ok(HttpResponse::PayloadTooLarge().json(serde_json::json!({
3367                "error": "proxied response exceeds byte cap",
3368                "limit": byte_cap
3369            })));
3370        }
3371
3372        // Collect response headers, stripping sensitive ones.
3373        let mut forwarded_headers: Vec<(String, String)> = Vec::new();
3374        for (name, value) in response.headers() {
3375            let name_lower = name.as_str().to_ascii_lowercase();
3376            if STRIPPED_RESPONSE_HEADERS.contains(&name_lower.as_str()) {
3377                continue;
3378            }
3379            // Skip hop-by-hop headers.
3380            if matches!(
3381                name_lower.as_str(),
3382                "transfer-encoding" | "connection" | "keep-alive" | "trailer" | "upgrade"
3383            ) {
3384                continue;
3385            }
3386            if let Ok(val_str) = value.to_str() {
3387                forwarded_headers.push((name_lower, val_str.to_string()));
3388            }
3389        }
3390
3391        let mut stream = response.bytes_stream();
3392        let mut body_bytes = Vec::with_capacity(byte_cap.min(64 * 1024));
3393        while let Some(chunk) = stream.next().await {
3394            let chunk =
3395                chunk.map_err(|e| actix_web::error::ErrorBadGateway(format!("body read: {e}")))?;
3396            if body_bytes.len().saturating_add(chunk.len()) > byte_cap {
3397                return Ok(HttpResponse::PayloadTooLarge().json(serde_json::json!({
3398                    "error": "proxied response exceeds byte cap",
3399                    "limit": byte_cap
3400                })));
3401            }
3402            body_bytes.extend_from_slice(&chunk);
3403        }
3404
3405        // Build the response.
3406        let mut rsp = HttpResponse::build(
3407            StatusCode::from_u16(upstream_status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR),
3408        );
3409        rsp.insert_header(("Content-Type", upstream_content_type.as_str()));
3410        rsp.insert_header(("X-Proxy-Status", upstream_status.to_string()));
3411
3412        // Forward non-sensitive headers.
3413        for (name, value) in &forwarded_headers {
3414            if let Ok(hname) = header::HeaderName::from_bytes(name.as_bytes()) {
3415                if let Ok(hval) = header::HeaderValue::from_str(value) {
3416                    rsp.insert_header((hname, hval));
3417                }
3418            }
3419        }
3420
3421        return Ok(rsp.body(body_bytes));
3422    }
3423}
3424
3425// ---------------------------------------------------------------------------
3426// Percent-decode + dotdot re-check middleware
3427// ---------------------------------------------------------------------------
3428
3429/// Actix middleware that rejects requests containing `..` path-traversal sequences.
3430pub struct PathTraversalGuard;
3431
3432impl<S, B> Transform<S, ServiceRequest> for PathTraversalGuard
3433where
3434    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = ActixError> + 'static,
3435    B: 'static,
3436{
3437    type Response = ServiceResponse<EitherBody<B, BoxBody>>;
3438    type Error = ActixError;
3439    type InitError = ();
3440    type Transform = PathTraversalGuardMiddleware<S>;
3441    type Future = Ready<Result<Self::Transform, Self::InitError>>;
3442
3443    fn new_transform(&self, service: S) -> Self::Future {
3444        ready(Ok(PathTraversalGuardMiddleware { service }))
3445    }
3446}
3447
3448/// Per-request service instance produced by [`PathTraversalGuard`].
3449pub struct PathTraversalGuardMiddleware<S> {
3450    service: S,
3451}
3452
3453impl<S, B> Service<ServiceRequest> for PathTraversalGuardMiddleware<S>
3454where
3455    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = ActixError> + 'static,
3456    B: 'static,
3457{
3458    type Response = ServiceResponse<EitherBody<B, BoxBody>>;
3459    type Error = ActixError;
3460    type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;
3461
3462    actix_web::dev::forward_ready!(service);
3463
3464    fn call(&self, req: ServiceRequest) -> Self::Future {
3465        // Decode the raw path twice so that `%252e%252e` → `%2e%2e` →
3466        // `..` can be caught even though NormalizePath already ran once.
3467        let raw = req.path().to_string();
3468        if path_is_traversal(&raw) {
3469            let rsp = HttpResponse::BadRequest().body("invalid path: traversal rejected");
3470            let sr = req.into_response(rsp.map_into_boxed_body());
3471            return Box::pin(async move { Ok(sr.map_into_right_body()) });
3472        }
3473        let fut = self.service.call(req);
3474        Box::pin(async move {
3475            let resp = fut.await?;
3476            Ok(resp.map_into_left_body())
3477        })
3478    }
3479}
3480
3481fn path_is_traversal(path: &str) -> bool {
3482    // Two passes of percent-decode catches double-encoding.
3483    let once: String = percent_decode_str(path).decode_utf8_lossy().into_owned();
3484    let twice: String = percent_decode_str(&once).decode_utf8_lossy().into_owned();
3485    for seg in once.split('/').chain(twice.split('/')) {
3486        if seg == ".." || seg == "." {
3487            return true;
3488        }
3489    }
3490    // Also flag any raw escape sequences that decode to a traversal
3491    // segment even when buried inside a component (e.g. `foo%2f..%2fbar`).
3492    twice.contains("/../") || twice.starts_with("../") || twice.ends_with("/..")
3493}
3494
3495// ---------------------------------------------------------------------------
3496// JSS-compatible CORS response headers
3497// ---------------------------------------------------------------------------
3498
3499/// Adds the same CORS envelope JSS emits from its global `onRequest` hook.
3500///
3501/// When `allowed_origins` is non-empty, the `Access-Control-Allow-Origin`
3502/// header is only reflected for origins in the list; requests from other
3503/// origins receive no ACAO header. When the list is empty (default), the
3504/// request `Origin` is echoed back (wildcard-equivalent, suitable for local dev).
3505pub struct CorsHeaders {
3506    pub allowed_origins: Arc<Vec<String>>,
3507}
3508
3509impl<S, B> Transform<S, ServiceRequest> for CorsHeaders
3510where
3511    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = ActixError> + 'static,
3512    B: 'static,
3513{
3514    type Response = ServiceResponse<B>;
3515    type Error = ActixError;
3516    type InitError = ();
3517    type Transform = CorsHeadersMiddleware<S>;
3518    type Future = Ready<Result<Self::Transform, Self::InitError>>;
3519
3520    fn new_transform(&self, service: S) -> Self::Future {
3521        ready(Ok(CorsHeadersMiddleware {
3522            service,
3523            allowed_origins: self.allowed_origins.clone(),
3524        }))
3525    }
3526}
3527
3528/// Per-request service instance produced by [`CorsHeaders`].
3529pub struct CorsHeadersMiddleware<S> {
3530    service: S,
3531    allowed_origins: Arc<Vec<String>>,
3532}
3533
3534impl<S, B> Service<ServiceRequest> for CorsHeadersMiddleware<S>
3535where
3536    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = ActixError> + 'static,
3537    B: 'static,
3538{
3539    type Response = ServiceResponse<B>;
3540    type Error = ActixError;
3541    type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;
3542
3543    actix_web::dev::forward_ready!(service);
3544
3545    fn call(&self, req: ServiceRequest) -> Self::Future {
3546        let origin = req
3547            .headers()
3548            .get(header::ORIGIN)
3549            .and_then(|v| v.to_str().ok())
3550            .map(str::to_string);
3551        let allowed = self.allowed_origins.clone();
3552        let fut = self.service.call(req);
3553        Box::pin(async move {
3554            let mut resp = fut.await?;
3555            add_cors_headers(resp.headers_mut(), origin.as_deref(), &allowed);
3556            Ok(resp)
3557        })
3558    }
3559}
3560
3561/// `Access-Control-Expose-Headers` value stamped on every pod response.
3562///
3563/// Matches JSS 0.0.221 `getCorsHeaders` (`src/ldp/headers.js`): the 0.0.221
3564/// delta (PR #629) adds `Accept-Query`, `Last-Modified` and `WWW-Authenticate`
3565/// so cross-origin clients can read the auth challenge, cache validators and
3566/// the query-format advertisement. `Accept-Query` is exposed for parity; this
3567/// server does not emit it yet (no QUERY method), so listing it is inert.
3568pub(crate) const CORS_EXPOSE_HEADERS: &str = "Accept-Patch, Accept-Post, Accept-Query, Accept-Ranges, Allow, Content-Length, Content-Range, Content-Type, ETag, Last-Modified, Link, Location, Updates-Via, WAC-Allow, WWW-Authenticate, X-Cost, X-Balance, X-Pay-Currency";
3569
3570fn add_cors_headers(headers: &mut header::HeaderMap, origin: Option<&str>, allowed: &[String]) {
3571    // Handler-authoritative CORS (JSS #548 parity): the git smart-HTTP and
3572    // forge surfaces stamp their own deliberate `*` CORS trio (those
3573    // protocols are anonymously clonable by design, and browser git clients
3574    // need the `WWW-Authenticate` challenge to be CORS-readable even when
3575    // the pod's app allowlist would block the origin). When a handler has
3576    // already set `Access-Control-Allow-Origin`, defer to it instead of
3577    // clobbering — previously this was mode-dependent (wildcard mode
3578    // overwrote, allowlist mode preserved), which made git/forge CORS
3579    // inconsistent across deployments.
3580    if headers.contains_key(header::ACCESS_CONTROL_ALLOW_ORIGIN) {
3581        return;
3582    }
3583    // Determine the effective ACAO value and whether credentials may be
3584    // allowed. The web platform forbids combining a credentialed response
3585    // (`Access-Control-Allow-Credentials: true`) with a reflected/wildcard
3586    // origin — doing so lets *any* site read authenticated responses. So:
3587    //
3588    //   * allowlist configured + origin in it  → reflect the origin AND allow
3589    //     credentials (the safe, intended cross-origin case);
3590    //   * allowlist configured + origin absent → emit no CORS headers (block);
3591    //   * no allowlist (dev/wildcard mode)      → emit `*` and DO NOT allow
3592    //     credentials — never reflect an arbitrary origin with credentials.
3593    let (origin_value, allow_credentials): (String, bool) = if allowed.is_empty() {
3594        ("*".to_string(), false)
3595    } else {
3596        match origin.filter(|o| allowed.iter().any(|a| a == *o)) {
3597            Some(o) => (o.to_string(), true),
3598            // Origin not in the allowlist — skip all CORS headers so the
3599            // browser's CORS check fails.
3600            None => return,
3601        }
3602    };
3603
3604    let mut pairs = vec![
3605        ("access-control-allow-origin", origin_value.as_str()),
3606        (
3607            "access-control-allow-methods",
3608            "GET, HEAD, POST, PUT, DELETE, PATCH, OPTIONS",
3609        ),
3610        (
3611            "access-control-allow-headers",
3612            "Accept, Authorization, Content-Type, DPoP, Git-Protocol, If-Match, If-None-Match, Link, Range, Slug, Origin",
3613        ),
3614        (
3615            "access-control-expose-headers",
3616            CORS_EXPOSE_HEADERS,
3617        ),
3618        ("access-control-max-age", "86400"),
3619    ];
3620    // Only advertise credentials support for an allowlisted, non-wildcard
3621    // origin. Never with `*`.
3622    if allow_credentials {
3623        pairs.push(("access-control-allow-credentials", "true"));
3624    }
3625
3626    for (name, value) in pairs {
3627        if let (Ok(name), Ok(value)) = (
3628            header::HeaderName::from_lowercase(name.as_bytes()),
3629            header::HeaderValue::from_str(value),
3630        ) {
3631            headers.insert(name, value);
3632        }
3633    }
3634}
3635
3636// ---------------------------------------------------------------------------
3637// Sprint 11 (row 158): top-level 5xx logging middleware.
3638//
3639// JSS ref: commit 5b34d72 (#312) — "Top-level Fastify error handler,
3640// full stack on 5xx". Mirror the behaviour in actix: intercept any
3641// response whose status is 5xx, emit a structured `tracing::error!`
3642// with the method, path, status, error chain, and (when
3643// `RUST_BACKTRACE=1`) a captured backtrace. The response body is not
3644// altered; we only observe.
3645// ---------------------------------------------------------------------------
3646
3647/// Observes outbound responses and logs 5xx results with the full
3648/// error chain. Pass-through on 2xx/3xx/4xx. Shaped as an actix
3649/// [`Transform`] so it slots into the middleware stack in
3650/// [`build_app`].
3651pub struct ErrorLoggingMiddleware;
3652
3653impl<S, B> Transform<S, ServiceRequest> for ErrorLoggingMiddleware
3654where
3655    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = ActixError> + 'static,
3656    B: 'static,
3657{
3658    type Response = ServiceResponse<B>;
3659    type Error = ActixError;
3660    type InitError = ();
3661    type Transform = ErrorLoggingMiddlewareService<S>;
3662    type Future = Ready<Result<Self::Transform, Self::InitError>>;
3663
3664    fn new_transform(&self, service: S) -> Self::Future {
3665        ready(Ok(ErrorLoggingMiddlewareService { service }))
3666    }
3667}
3668
3669/// Per-request service instance produced by [`ErrorLoggingMiddleware`].
3670pub struct ErrorLoggingMiddlewareService<S> {
3671    service: S,
3672}
3673
3674impl<S, B> Service<ServiceRequest> for ErrorLoggingMiddlewareService<S>
3675where
3676    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = ActixError> + 'static,
3677    B: 'static,
3678{
3679    type Response = ServiceResponse<B>;
3680    type Error = ActixError;
3681    type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;
3682
3683    actix_web::dev::forward_ready!(service);
3684
3685    fn call(&self, req: ServiceRequest) -> Self::Future {
3686        // Snapshot fields we need for the log line before the request
3687        // moves into the inner service.
3688        let method = req.method().as_str().to_string();
3689        let path = req.path().to_string();
3690
3691        let fut = self.service.call(req);
3692        Box::pin(async move {
3693            let response = fut.await?;
3694            let status = response.status();
3695            if status.is_server_error() {
3696                log_5xx(&method, &path, status, response.response().error());
3697            }
3698            Ok(response)
3699        })
3700    }
3701}
3702
3703/// Emit the structured 5xx log line. Captures a backtrace only when
3704/// `RUST_BACKTRACE=1` is set so production logs don't bloat unless the
3705/// operator opted in.
3706fn log_5xx(method: &str, path: &str, status: StatusCode, error: Option<&actix_web::Error>) {
3707    // Full error chain — include `source()` walk so downstream
3708    // `PodError` variants surface instead of being swallowed by
3709    // actix's top-level wrapper.
3710    let chain = match error {
3711        Some(e) => format_error_chain(e),
3712        None => "<no error attached to response>".to_string(),
3713    };
3714
3715    let backtrace = if std::env::var("RUST_BACKTRACE").ok().as_deref() == Some("1") {
3716        Some(std::backtrace::Backtrace::force_capture().to_string())
3717    } else {
3718        None
3719    };
3720
3721    tracing::error!(
3722        target: "solid_pod_rs_server::http",
3723        method = %method,
3724        path = %path,
3725        status = %status.as_u16(),
3726        error.chain = %chain,
3727        backtrace = backtrace.as_deref().unwrap_or(""),
3728        "5xx response"
3729    );
3730}
3731
3732/// Walk an actix `Error` + its `source()` chain into a single
3733/// human-readable string (one segment per cause, separated by ` -> `).
3734///
3735/// `actix_web::Error` does not expose a stable `source()` accessor,
3736/// and `ResponseError` in actix-web 4 does not extend
3737/// [`std::error::Error`]. We surface the `Display` form of the
3738/// response error (which captures the message operators care about
3739/// on 5xx) and append the actix `Debug` dump for deep diagnosis —
3740/// the dump already includes the inner cause chain that actix-http
3741/// preserves internally.
3742fn format_error_chain(e: &actix_web::Error) -> String {
3743    let summary = format!("{}", e.as_response_error());
3744    let debug = format!("{e:?}");
3745    if debug == summary || debug.is_empty() {
3746        summary
3747    } else {
3748        format!("{summary} -> {debug}")
3749    }
3750}
3751
3752// ---------------------------------------------------------------------------
3753// Dotfile allowlist middleware
3754// ---------------------------------------------------------------------------
3755
3756/// Actix middleware that blocks dotfile paths unless they appear on the allowlist.
3757pub struct DotfileGuard {
3758    allow: Arc<DotfileAllowlist>,
3759    hosts: Option<Arc<HostPolicy>>,
3760}
3761
3762/// `Host` allow-list enforced by [`DotfileGuard`] (security review M1).
3763///
3764/// A request whose effective host (the plain `Host` header, or the
3765/// forwarding headers behind `trust_proxy`) is not on the list is refused with
3766/// `421 Misdirected Request` before any handler runs, so a client cannot
3767/// address the server under a name it does not serve.
3768pub struct HostPolicy {
3769    /// Permitted hosts (`host` or `host:port`, case-insensitive).
3770    pub allowed: Vec<String>,
3771    /// Honour `X-Forwarded-Host` / `Forwarded` when computing the host.
3772    pub trust_proxy: bool,
3773}
3774
3775impl DotfileGuard {
3776    pub fn new(allow: Arc<DotfileAllowlist>) -> Self {
3777        Self { allow, hosts: None }
3778    }
3779
3780    /// Also enforce a `Host` allow-list; an empty list changes nothing.
3781    pub fn with_host_policy(mut self, policy: HostPolicy) -> Self {
3782        if !policy.allowed.is_empty() {
3783            self.hosts = Some(Arc::new(policy));
3784        }
3785        self
3786    }
3787}
3788
3789impl<S, B> Transform<S, ServiceRequest> for DotfileGuard
3790where
3791    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = ActixError> + 'static,
3792    B: 'static,
3793{
3794    type Response = ServiceResponse<EitherBody<B, BoxBody>>;
3795    type Error = ActixError;
3796    type InitError = ();
3797    type Transform = DotfileGuardMiddleware<S>;
3798    type Future = Ready<Result<Self::Transform, Self::InitError>>;
3799
3800    fn new_transform(&self, service: S) -> Self::Future {
3801        ready(Ok(DotfileGuardMiddleware {
3802            service,
3803            allow: self.allow.clone(),
3804            hosts: self.hosts.clone(),
3805        }))
3806    }
3807}
3808
3809/// Per-request service instance produced by [`DotfileGuard`].
3810pub struct DotfileGuardMiddleware<S> {
3811    service: S,
3812    allow: Arc<DotfileAllowlist>,
3813    hosts: Option<Arc<HostPolicy>>,
3814}
3815
3816impl<S, B> Service<ServiceRequest> for DotfileGuardMiddleware<S>
3817where
3818    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = ActixError> + 'static,
3819    B: 'static,
3820{
3821    type Response = ServiceResponse<EitherBody<B, BoxBody>>;
3822    type Error = ActixError;
3823    type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;
3824
3825    actix_web::dev::forward_ready!(service);
3826
3827    fn call(&self, req: ServiceRequest) -> Self::Future {
3828        if let Some(p) = &self.hosts {
3829            let host = scheme::host_with(req.request(), None, p.trust_proxy);
3830            if !scheme::host_allowed(&host, &p.allowed) {
3831                let rsp = HttpResponse::build(actix_web::http::StatusCode::MISDIRECTED_REQUEST)
3832                    .body("host not served here");
3833                let sr = req.into_response(rsp.map_into_boxed_body());
3834                return Box::pin(async move { Ok(sr.map_into_right_body()) });
3835            }
3836        }
3837        let path = req.path().to_string();
3838        // Whitelist the well-known discovery paths even though they
3839        // contain a dotfile component — they are part of Solid's stable
3840        // interop surface. `/pay/.*` is the same case: the payment control
3841        // surface (`.info`, `.balance`, `.deposit`, `.offers`, `.sell`,
3842        // `.swap`, `.pool`) is dot-prefixed protocol endpoints, not pod
3843        // dotfiles, so the dotfile allowlist must not shadow them.
3844        let allow_system_route =
3845            path.starts_with("/.well-known/") || path == "/.pods" || path.starts_with("/pay/");
3846        if !allow_system_route {
3847            let pb = PathBuf::from(&path);
3848            if !self.allow.is_allowed(Path::new(&pb)) {
3849                let rsp = HttpResponse::Forbidden().body("dotfile path denied by allowlist");
3850                let sr = req.into_response(rsp.map_into_boxed_body());
3851                return Box::pin(async move { Ok(sr.map_into_right_body()) });
3852            }
3853        }
3854        let fut = self.service.call(req);
3855        Box::pin(async move {
3856            let resp = fut.await?;
3857            Ok(resp.map_into_left_body())
3858        })
3859    }
3860}
3861
3862// ---------------------------------------------------------------------------
3863// Git control panel API helpers (feature = "git")
3864// ---------------------------------------------------------------------------
3865
3866#[cfg(feature = "git")]
3867pub(crate) fn pod_repo_path(state: &AppState, pubkey: &str) -> Option<PathBuf> {
3868    if pubkey.len() != 64 || !pubkey.bytes().all(|b| b.is_ascii_hexdigit()) {
3869        return None;
3870    }
3871    state.data_root.as_ref().map(|root| root.join(pubkey))
3872}
3873
3874/// Provenance composition hook (ADR-059 Phase 5): after a SUCCESSFUL LDP write
3875/// to a **git-backed** pod, record the write through the single canonical
3876/// [`ProvenanceLog::record`] path — the cheap, always-on git-mark **always**,
3877/// plus the expensive Bitcoin block-trail anchor **opt-in** when the resource's
3878/// ACL carries a `ProvenanceAnchor` condition. A PROV-O sidecar is persisted
3879/// at `<resource>.prov.ttl`.
3880///
3881/// **Single path — no parallel mark call.** This composes via
3882/// [`ProvenanceLog`]; it does *not* call `ShellGitMarker::mark_write` directly.
3883/// `ProvenanceLog::record` runs the git-mark, then conditionally the anchor
3884/// (per the resolved [`AnchorPolicy`]), binding the anchor's `state_hash` to
3885/// the git commit SHA (master-plan §2.3). The `Epoch` policy batches the SHA
3886/// into the per-pod epoch ([`handlers::prov::epoch_push_and_maybe_anchor`]) so
3887/// one Bitcoin tx notarises many commits (ADR-059 D5).
3888///
3889/// **Additive and best-effort by contract.** The LDP write has *already*
3890/// succeeded and the HTTP response is already determined when this runs. Every
3891/// failure — no git binary, a commit error, an anchor error, a sidecar-write
3892/// error — is logged at `warn` and swallowed: a provenance failure must NEVER
3893/// change the write's response status. A failed *anchor* never fails the write
3894/// and never suppresses the git-mark sidecar.
3895///
3896/// **git-backed-only.** A mark is produced only when `data_root` is configured
3897/// AND a git repository exists at `data_root/{pod}/.git`. Non-git / in-memory /
3898/// cloud-backed pods are skipped silently.
3899///
3900/// **No recursive marking.** Writes to ACL/meta/provenance sidecars
3901/// (`*.acl`, `*.meta`, `*.prov.ttl`) are skipped — marking a `.prov.ttl` would
3902/// recurse, and ACL/meta writes are control-plane, not content.
3903#[cfg(feature = "git")]
3904async fn git_mark_write(
3905    state: &AppState,
3906    resource_path: &str,
3907    agent: Option<&str>,
3908    message: &str,
3909) -> ProvenanceReceipt {
3910    use solid_pod_rs::provenance::{prov_ttl, AnchorPolicy, ProvenanceLog};
3911    use solid_pod_rs_git::mark::ShellGitMarker;
3912
3913    // Skip control-plane / provenance sidecars — never mark these, and never
3914    // recurse on our own `.prov.ttl` output.
3915    if resource_path.ends_with(".acl")
3916        || resource_path.ends_with(".meta")
3917        || resource_path.ends_with(".prov.ttl")
3918    {
3919        return ProvenanceReceipt::skipped(resource_path, ProvenanceSkip::ExcludedPath);
3920    }
3921    // Containers (trailing slash) are not file writes — nothing to commit.
3922    if resource_path.ends_with('/') {
3923        return ProvenanceReceipt::skipped(resource_path, ProvenanceSkip::Container);
3924    }
3925
3926    // data_root is required to locate the pod repo on disk.
3927    let Some(data_root) = state.data_root.as_ref() else {
3928        return ProvenanceReceipt::skipped(resource_path, ProvenanceSkip::NotConfigured);
3929    };
3930
3931    // The pod is the first path segment; the repo lives at data_root/{pod}.
3932    let trimmed = resource_path.trim_start_matches('/');
3933    let mut segments = trimmed.splitn(2, '/');
3934    let pod = segments.next().unwrap_or("");
3935    let rel = segments.next().unwrap_or("");
3936    if pod.is_empty() || rel.is_empty() {
3937        return ProvenanceReceipt::skipped(resource_path, ProvenanceSkip::UnresolvablePath);
3938    }
3939    let repo = data_root.join(pod);
3940
3941    // git-backed check: a `.git` dir must exist at the pod root. Non-git pods
3942    // are skipped silently — this is the runtime guard that keeps memory /
3943    // cloud pods unaffected even when the `git` feature is compiled in.
3944    if !repo.join(".git").is_dir() {
3945        return ProvenanceReceipt::skipped(resource_path, ProvenanceSkip::NotGitBacked);
3946    }
3947
3948    let agent_did = agent.unwrap_or("urn:solid:anonymous");
3949    let created = std::time::SystemTime::now()
3950        .duration_since(std::time::UNIX_EPOCH)
3951        .map(|d| d.as_secs())
3952        .unwrap_or(0);
3953
3954    // Resolve this resource's anchor policy from its effective ACL (the
3955    // `ProvenanceAnchor` condition → HighValue/Epoch; absent → Never).
3956    let (policy, ticker_override) =
3957        handlers::prov::resolve_anchor_policy(state, resource_path).await;
3958
3959    // Build the composition log: cheap git-marker ALWAYS; expensive anchorer
3960    // ONLY when the policy wants it AND the pod is configured for anchoring.
3961    // For `Epoch` the anchorer is still needed (to anchor the batch root on
3962    // close), so build it for any anchoring policy.
3963    let marker = std::sync::Arc::new(ShellGitMarker::new());
3964    let anchorer_bundle = if matches!(policy, AnchorPolicy::Never) {
3965        None
3966    } else {
3967        handlers::prov::build_anchorer(state, ticker_override.as_deref()).await
3968    };
3969    let (log, ticker, network) = match &anchorer_bundle {
3970        Some((anchorer, ticker, network)) => (
3971            ProvenanceLog::with_anchorer(marker.clone(), anchorer.clone()),
3972            ticker.clone(),
3973            network.clone(),
3974        ),
3975        // No anchorer available (or policy Never): git-mark-only log.
3976        None => (
3977            ProvenanceLog::new(marker.clone()),
3978            String::new(),
3979            String::new(),
3980        ),
3981    };
3982
3983    // `record()` anchors INLINE only for HighValue (high_value=true). Epoch
3984    // defers to the accumulator below, so we pass it as Never to `record` and
3985    // batch the SHA ourselves; HighValue/Never flow straight through.
3986    let record_policy = match policy {
3987        AnchorPolicy::Epoch => AnchorPolicy::Never,
3988        other => other,
3989    };
3990    let high_value = matches!(policy, AnchorPolicy::HighValue) && anchorer_bundle.is_some();
3991
3992    // SINGLE canonical path: compose via ProvenanceLog::record (git-mark always,
3993    // anchor opt-in). A git-mark failure is the only hard error (the write
3994    // already succeeded, so we just log + return).
3995    let write_record = solid_pod_rs::provenance::WriteRecord {
3996        repo: &repo,
3997        path: rel,
3998        agent_did,
3999        message,
4000        policy: record_policy,
4001        high_value,
4002        ticker: &ticker,
4003        network: &network,
4004        created,
4005    };
4006    // ADR-2004: `record_receipt` reports each tier separately instead of
4007    // collapsing a failed git-mark into an error the caller could only log and
4008    // discard. The write has already succeeded; what changes here is that the
4009    // caller now learns WHICH provenance tier it actually got.
4010    let mut receipt = log.record_receipt(write_record).await;
4011    // `record_receipt` only sees the repo-relative path; restore the full
4012    // pod-relative resource path (`/{pod}/{rel}`).
4013    receipt.resource = resource_path.to_string();
4014
4015    let Some(git) = receipt.mark.clone() else {
4016        // The bytes are stored but nothing records the write. Still not an
4017        // HTTP error (the LDP write succeeded), but no longer invisible: the
4018        // typed receipt goes back to the handler, which surfaces it.
4019        tracing::warn!(
4020            target: "solid_pod_rs_server::git_mark",
4021            resource = %resource_path,
4022            "provenance record failed (write already succeeded): {}",
4023            receipt.mark_error.as_deref().unwrap_or("unspecified")
4024        );
4025        return receipt;
4026    };
4027    if let Some(err) = &receipt.anchor_error {
4028        // A failed anchor never suppresses the git-mark, but it must not be
4029        // silently downgraded to "marked" either.
4030        tracing::warn!(
4031            target: "solid_pod_rs_server::git_mark",
4032            resource = %resource_path,
4033            commit = %git.commit_sha,
4034            "block-trail anchor failed (git-mark stands): {err}"
4035        );
4036    }
4037    let mark = solid_pod_rs::provenance::ProvenanceMark {
4038        resource: resource_path.to_string(),
4039        git: git.clone(),
4040        anchor: receipt.anchor.clone(),
4041        agent_did: agent_did.to_string(),
4042        created,
4043    };
4044
4045    // Epoch policy: batch the freshly-produced commit SHA; anchor the batch
4046    // root once when the epoch fills (best-effort — a failed batch anchor never
4047    // fails the write nor the git-mark).
4048    if matches!(policy, AnchorPolicy::Epoch) {
4049        if let Some((anchorer, _, _)) = &anchorer_bundle {
4050            match handlers::prov::epoch_push_and_maybe_anchor(
4051                state,
4052                anchorer,
4053                &ticker,
4054                &network,
4055                &mark.git.commit_sha,
4056            )
4057            .await
4058            {
4059                Ok(Some(closed)) => tracing::debug!(
4060                    target: "solid_pod_rs_server::git_mark",
4061                    root = %closed.root,
4062                    n = closed.commits.len(),
4063                    "epoch anchored (one tx notarises {} commits)", closed.commits.len()
4064                ),
4065                Ok(None) => {}
4066                Err(e) => tracing::warn!(
4067                    target: "solid_pod_rs_server::git_mark",
4068                    "epoch batch/anchor failed (swallowed): {e}"
4069                ),
4070            }
4071        }
4072    }
4073
4074    // Persist the PROV-O sidecar at <resource>.prov.ttl. This write also fires
4075    // the FS-watch StorageEvent the `Updates-via` notification stream relays,
4076    // so subscribers see the new mark. It ends in `.prov.ttl`, so the skip
4077    // guard above prevents any recursion.
4078    let ttl = prov_ttl(&mark);
4079    let sidecar = format!("{resource_path}.prov.ttl");
4080    if let Err(e) = state
4081        .storage
4082        .put(&sidecar, Bytes::from(ttl.into_bytes()), "text/turtle")
4083        .await
4084    {
4085        tracing::warn!(
4086            target: "solid_pod_rs_server::git_mark",
4087            sidecar = %sidecar,
4088            "provenance sidecar write failed: {e}"
4089        );
4090        // The commit stands, so the receipt keeps its `local-mark-committed`
4091        // stage; the sidecar fault is reported alongside it.
4092        receipt.mark_error = Some(format!("PROV-O sidecar write failed: {e}"));
4093        return receipt;
4094    }
4095
4096    tracing::debug!(
4097        target: "solid_pod_rs_server::git_mark",
4098        resource = %resource_path,
4099        commit = %mark.git.commit_sha,
4100        stage = %receipt.stage(),
4101        "provenance recorded"
4102    );
4103    receipt
4104}
4105
4106/// No-op shim when the `git` feature is disabled, so the write handlers can
4107/// call `git_mark_write(...)` unconditionally without per-call-site `cfg`.
4108#[cfg(not(feature = "git"))]
4109#[inline]
4110async fn git_mark_write(
4111    _state: &AppState,
4112    resource_path: &str,
4113    _agent: Option<&str>,
4114    _message: &str,
4115) -> ProvenanceReceipt {
4116    ProvenanceReceipt::skipped(resource_path, ProvenanceSkip::NotConfigured)
4117}
4118
4119#[cfg(feature = "git")]
4120pub(crate) async fn require_pod_owner(req: &HttpRequest, pod_pubkey: &str) -> Option<String> {
4121    require_pod_owner_with_body(req, pod_pubkey, None).await
4122}
4123
4124#[cfg(feature = "git")]
4125pub(crate) async fn require_pod_owner_with_body(
4126    req: &HttpRequest,
4127    pod_pubkey: &str,
4128    body: Option<&[u8]>,
4129) -> Option<String> {
4130    let caller = extract_pubkey_with_body(req, body).await?;
4131    if caller != pod_pubkey {
4132        return None;
4133    }
4134    Some(caller)
4135}
4136
4137#[cfg(feature = "git")]
4138fn git_json_err(msg: &str, status: u16) -> HttpResponse {
4139    HttpResponse::build(StatusCode::from_u16(status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR))
4140        .content_type("application/json")
4141        .body(format!(r#"{{"error":"{}"}}"#, msg.replace('"', "\\\"")))
4142}
4143
4144// Request body types for git control panel endpoints.
4145#[cfg(feature = "git")]
4146#[derive(serde::Deserialize)]
4147struct GitStageBody {
4148    paths: Option<Vec<String>>,
4149    all: Option<bool>,
4150}
4151
4152#[cfg(feature = "git")]
4153#[derive(serde::Deserialize)]
4154struct GitCommitBody {
4155    message: String,
4156    author_name: Option<String>,
4157    author_email: Option<String>,
4158}
4159
4160#[cfg(feature = "git")]
4161#[derive(serde::Deserialize)]
4162struct GitBranchBody {
4163    name: String,
4164}
4165
4166// ── Control panel handlers ──────────────────────────────────────────────────
4167
4168#[cfg(feature = "git")]
4169async fn handle_git_status(
4170    path: web::Path<String>,
4171    req: HttpRequest,
4172    state: web::Data<AppState>,
4173) -> HttpResponse {
4174    let pubkey = path.into_inner();
4175    if require_pod_owner(&req, &pubkey).await.is_none() {
4176        return git_json_err("Authentication required", 401);
4177    }
4178    let Some(repo) = pod_repo_path(&state, &pubkey) else {
4179        return git_json_err("Git not available (no FS backend)", 501);
4180    };
4181    match solid_pod_rs_git::api::git_status(&repo).await {
4182        Ok(s) => HttpResponse::Ok()
4183            .content_type("application/json")
4184            .body(serde_json::to_string(&s).unwrap_or_default()),
4185        Err(e) => git_json_err(&e.to_string(), e.status_code()),
4186    }
4187}
4188
4189#[cfg(feature = "git")]
4190async fn handle_git_log(
4191    path: web::Path<String>,
4192    req: HttpRequest,
4193    state: web::Data<AppState>,
4194    query: web::Query<std::collections::HashMap<String, String>>,
4195) -> HttpResponse {
4196    let pubkey = path.into_inner();
4197    if require_pod_owner(&req, &pubkey).await.is_none() {
4198        return git_json_err("Authentication required", 401);
4199    }
4200    let Some(repo) = pod_repo_path(&state, &pubkey) else {
4201        return git_json_err("Git not available (no FS backend)", 501);
4202    };
4203    let limit: u32 = query
4204        .get("limit")
4205        .and_then(|v| v.parse().ok())
4206        .unwrap_or(20);
4207    match solid_pod_rs_git::api::git_log(&repo, limit).await {
4208        Ok(entries) => HttpResponse::Ok()
4209            .content_type("application/json")
4210            .body(serde_json::to_string(&entries).unwrap_or_default()),
4211        Err(e) => git_json_err(&e.to_string(), e.status_code()),
4212    }
4213}
4214
4215#[cfg(feature = "git")]
4216async fn handle_git_diff(
4217    path: web::Path<String>,
4218    req: HttpRequest,
4219    state: web::Data<AppState>,
4220    query: web::Query<std::collections::HashMap<String, String>>,
4221) -> HttpResponse {
4222    let pubkey = path.into_inner();
4223    if require_pod_owner(&req, &pubkey).await.is_none() {
4224        return git_json_err("Authentication required", 401);
4225    }
4226    let Some(repo) = pod_repo_path(&state, &pubkey) else {
4227        return git_json_err("Git not available (no FS backend)", 501);
4228    };
4229    let file_path = query.get("path").map(String::as_str);
4230    let staged = query
4231        .get("staged")
4232        .map(|v| v == "true" || v == "1")
4233        .unwrap_or(false);
4234    match solid_pod_rs_git::api::git_diff(&repo, file_path, staged).await {
4235        Ok(diff) => HttpResponse::Ok().content_type("text/plain").body(diff),
4236        Err(e) => git_json_err(&e.to_string(), e.status_code()),
4237    }
4238}
4239
4240#[cfg(feature = "git")]
4241async fn handle_git_stage(
4242    path: web::Path<String>,
4243    req: HttpRequest,
4244    state: web::Data<AppState>,
4245    body: web::Bytes,
4246) -> HttpResponse {
4247    let pubkey = path.into_inner();
4248    if require_pod_owner(&req, &pubkey).await.is_none() {
4249        return git_json_err("Authentication required", 401);
4250    }
4251    let Some(repo) = pod_repo_path(&state, &pubkey) else {
4252        return git_json_err("Git not available (no FS backend)", 501);
4253    };
4254    let parsed: GitStageBody = match serde_json::from_slice(&body) {
4255        Ok(v) => v,
4256        Err(e) => return git_json_err(&format!("bad request: {e}"), 400),
4257    };
4258    let paths = parsed.paths.unwrap_or_default();
4259    let all = parsed.all.unwrap_or(false);
4260    match solid_pod_rs_git::api::git_add(&repo, &paths, all).await {
4261        Ok(()) => HttpResponse::Ok()
4262            .content_type("application/json")
4263            .body(r#"{"ok":true}"#),
4264        Err(e) => git_json_err(&e.to_string(), e.status_code()),
4265    }
4266}
4267
4268#[cfg(feature = "git")]
4269async fn handle_git_unstage(
4270    path: web::Path<String>,
4271    req: HttpRequest,
4272    state: web::Data<AppState>,
4273    body: web::Bytes,
4274) -> HttpResponse {
4275    let pubkey = path.into_inner();
4276    if require_pod_owner(&req, &pubkey).await.is_none() {
4277        return git_json_err("Authentication required", 401);
4278    }
4279    let Some(repo) = pod_repo_path(&state, &pubkey) else {
4280        return git_json_err("Git not available (no FS backend)", 501);
4281    };
4282    let parsed: GitStageBody = match serde_json::from_slice(&body) {
4283        Ok(v) => v,
4284        Err(e) => return git_json_err(&format!("bad request: {e}"), 400),
4285    };
4286    let paths = parsed.paths.unwrap_or_default();
4287    let all = parsed.all.unwrap_or(false);
4288    match solid_pod_rs_git::api::git_unstage(&repo, &paths, all).await {
4289        Ok(()) => HttpResponse::Ok()
4290            .content_type("application/json")
4291            .body(r#"{"ok":true}"#),
4292        Err(e) => git_json_err(&e.to_string(), e.status_code()),
4293    }
4294}
4295
4296#[cfg(feature = "git")]
4297async fn handle_git_commit(
4298    path: web::Path<String>,
4299    req: HttpRequest,
4300    state: web::Data<AppState>,
4301    body: web::Bytes,
4302) -> HttpResponse {
4303    let pubkey = path.into_inner();
4304    if require_pod_owner(&req, &pubkey).await.is_none() {
4305        return git_json_err("Authentication required", 401);
4306    }
4307    let Some(repo) = pod_repo_path(&state, &pubkey) else {
4308        return git_json_err("Git not available (no FS backend)", 501);
4309    };
4310    let parsed: GitCommitBody = match serde_json::from_slice(&body) {
4311        Ok(v) => v,
4312        Err(e) => return git_json_err(&format!("bad request: {e}"), 400),
4313    };
4314    let author_name = parsed.author_name.as_deref().unwrap_or("Pod Owner");
4315    let author_email = parsed
4316        .author_email
4317        .as_deref()
4318        .unwrap_or("pod@dreamlab-ai.com");
4319    match solid_pod_rs_git::api::git_commit(&repo, &parsed.message, author_name, author_email).await
4320    {
4321        Ok(result) => HttpResponse::Ok()
4322            .content_type("application/json")
4323            .body(serde_json::to_string(&result).unwrap_or_default()),
4324        Err(e) => git_json_err(&e.to_string(), e.status_code()),
4325    }
4326}
4327
4328#[cfg(feature = "git")]
4329async fn handle_git_branches(
4330    path: web::Path<String>,
4331    req: HttpRequest,
4332    state: web::Data<AppState>,
4333) -> HttpResponse {
4334    let pubkey = path.into_inner();
4335    if require_pod_owner(&req, &pubkey).await.is_none() {
4336        return git_json_err("Authentication required", 401);
4337    }
4338    let Some(repo) = pod_repo_path(&state, &pubkey) else {
4339        return git_json_err("Git not available (no FS backend)", 501);
4340    };
4341    match solid_pod_rs_git::api::git_branches(&repo).await {
4342        Ok(info) => HttpResponse::Ok()
4343            .content_type("application/json")
4344            .body(serde_json::to_string(&info).unwrap_or_default()),
4345        Err(e) => git_json_err(&e.to_string(), e.status_code()),
4346    }
4347}
4348
4349#[cfg(feature = "git")]
4350async fn handle_git_create_branch(
4351    path: web::Path<String>,
4352    req: HttpRequest,
4353    state: web::Data<AppState>,
4354    body: web::Bytes,
4355) -> HttpResponse {
4356    let pubkey = path.into_inner();
4357    if require_pod_owner(&req, &pubkey).await.is_none() {
4358        return git_json_err("Authentication required", 401);
4359    }
4360    let Some(repo) = pod_repo_path(&state, &pubkey) else {
4361        return git_json_err("Git not available (no FS backend)", 501);
4362    };
4363    let parsed: GitBranchBody = match serde_json::from_slice(&body) {
4364        Ok(v) => v,
4365        Err(e) => return git_json_err(&format!("bad request: {e}"), 400),
4366    };
4367    match solid_pod_rs_git::api::git_create_branch(&repo, &parsed.name).await {
4368        Ok(()) => HttpResponse::Ok()
4369            .content_type("application/json")
4370            .body(r#"{"ok":true}"#),
4371        Err(e) => git_json_err(&e.to_string(), e.status_code()),
4372    }
4373}
4374
4375#[cfg(feature = "git")]
4376async fn handle_git_discard(
4377    path: web::Path<String>,
4378    req: HttpRequest,
4379    state: web::Data<AppState>,
4380    body: web::Bytes,
4381) -> HttpResponse {
4382    let pubkey = path.into_inner();
4383    if require_pod_owner(&req, &pubkey).await.is_none() {
4384        return git_json_err("Authentication required", 401);
4385    }
4386    let Some(repo) = pod_repo_path(&state, &pubkey) else {
4387        return git_json_err("Git not available (no FS backend)", 501);
4388    };
4389    let parsed: GitStageBody = match serde_json::from_slice(&body) {
4390        Ok(v) => v,
4391        Err(e) => return git_json_err(&format!("bad request: {e}"), 400),
4392    };
4393    let paths = parsed.paths.unwrap_or_default();
4394    match solid_pod_rs_git::api::git_discard(&repo, &paths).await {
4395        Ok(()) => HttpResponse::Ok()
4396            .content_type("application/json")
4397            .body(r#"{"ok":true}"#),
4398        Err(e) => git_json_err(&e.to_string(), e.status_code()),
4399    }
4400}
4401
4402// ---------------------------------------------------------------------------
4403// OPTIONS preflight for /_git/{pubkey}/{tail:.*} — alpha.15
4404// ---------------------------------------------------------------------------
4405
4406/// Handles CORS preflight (OPTIONS) requests for the `/_git/` REST API
4407/// namespace. Returns 204 with full CORS headers, respecting the
4408/// `allowed_origins` allowlist from `AppState`.
4409async fn handle_git_panel_options(req: HttpRequest, state: web::Data<AppState>) -> HttpResponse {
4410    let origin = req
4411        .headers()
4412        .get(header::ORIGIN)
4413        .and_then(|v| v.to_str().ok())
4414        .map(str::to_string);
4415
4416    let mut rsp = HttpResponse::NoContent().finish();
4417    add_cors_headers(rsp.headers_mut(), origin.as_deref(), &state.allowed_origins);
4418    rsp
4419}
4420
4421// ---------------------------------------------------------------------------
4422// POST /_admin/provision/{pubkey} — alpha.15
4423// ---------------------------------------------------------------------------
4424
4425/// PSK-gated endpoint that provisions a pod for a given Nostr pubkey. Used by
4426/// the forum auth-worker to create native pods on behalf of users when the
4427/// "native pods" admin panel action is triggered.
4428///
4429/// On-disk layout (must match the `/pods/{pk}/` URL namespace the LDP
4430/// handlers serve, and the `podUrl` this endpoint returns):
4431/// * pod container: `data_root/pods/{pk}/`
4432/// * owner WAC ACL (sibling, the location the resolver reads):
4433///   `data_root/pods/{pk}.acl` (plus a courtesy inner `pods/{pk}/.acl`)
4434///
4435/// Protection: `X-Pod-Admin-Key` header must match `state.admin_key`.
4436/// When `state.admin_key` is `None` the endpoint always returns 403.
4437async fn handle_admin_provision(
4438    req: HttpRequest,
4439    state: web::Data<AppState>,
4440    path: web::Path<String>,
4441) -> HttpResponse {
4442    // --- PSK check -------------------------------------------------------
4443    let expected = match &state.admin_key {
4444        Some(k) => k.clone(),
4445        None => {
4446            return HttpResponse::Forbidden().json(serde_json::json!({
4447                "error": "admin key not configured on this server"
4448            }));
4449        }
4450    };
4451    let provided = req
4452        .headers()
4453        .get("x-pod-admin-key")
4454        .and_then(|v| v.to_str().ok())
4455        .unwrap_or("");
4456    // Constant-time comparison so the provisioning PSK cannot be
4457    // recovered via a response-timing side-channel. `ct_eq` returns a
4458    // `subtle::Choice`; differing lengths short-circuit to a `false`
4459    // choice without leaking the length via early return.
4460    use subtle::ConstantTimeEq;
4461    let key_match = provided.as_bytes().ct_eq(expected.as_bytes());
4462    if !bool::from(key_match) {
4463        return HttpResponse::Forbidden().json(serde_json::json!({"error": "invalid admin key"}));
4464    }
4465
4466    // --- Pubkey validation -----------------------------------------------
4467    let pubkey = path.into_inner();
4468    if pubkey.len() != 64 || !pubkey.chars().all(|c| c.is_ascii_hexdigit()) {
4469        return HttpResponse::BadRequest()
4470            .json(serde_json::json!({"error": "pubkey must be 64 lowercase hex characters"}));
4471    }
4472
4473    // --- Locate FS root --------------------------------------------------
4474    let data_root = match &state.data_root {
4475        Some(r) => r.clone(),
4476        None => {
4477            return HttpResponse::InternalServerError().json(serde_json::json!({
4478                "error": "server has no fs-backend storage configured"
4479            }));
4480        }
4481    };
4482
4483    // --- BUG 1: pod must live in the `/pods/{pk}/` URL namespace ----------
4484    // The LDP handlers (`handle_get`/`handle_put`) use `req.uri().path()`
4485    // verbatim as the storage key, and the FS backend maps that key under
4486    // `data_root` (stripping the leading '/'). A pod served at
4487    // `/pods/{pk}/…` therefore lives on disk at `data_root/pods/{pk}/…`, and
4488    // the `podUrl` this endpoint returns is `{base}/pods/{pk}/`. Provisioning
4489    // previously wrote the pod to `data_root/{pk}` (bare, no `pods/` segment),
4490    // so the freshly-provisioned pod was invisible to its own advertised URL:
4491    // every authenticated write to `/pods/{pk}/…` 403'd because no resource
4492    // (and, per BUG 2, no resolvable ACL) existed under that key. Provision
4493    // into `data_root/pods/{pk}` so the on-disk layout matches the contract
4494    // the response returns. `create_dir_all` creates the `pods/` parent too.
4495    let pods_root = data_root.join("pods");
4496    let pod_dir = pods_root.join(&pubkey);
4497
4498    // --- Create directory (idempotent) -----------------------------------
4499    if let Err(e) = tokio::fs::create_dir_all(&pod_dir).await {
4500        tracing::error!(pubkey = %pubkey, error = %e, "/_admin/provision: create_dir_all failed");
4501        return HttpResponse::InternalServerError()
4502            .json(serde_json::json!({"error": format!("failed to create pod directory: {e}")}));
4503    }
4504
4505    // --- Write owner-only WAC ACL ----------------------------------------
4506    // Grant the pod owner (`did:nostr:{pubkey}`) full Read/Write/Control over
4507    // the pod container and its whole subtree. Use the CONCRETE container
4508    // path `/pods/{pk}/` rather than a relative `<./>`: the WAC evaluator
4509    // normalises `./` to `/` (the server root), which — while incidentally
4510    // scoped by the resolver's walk-up — is semantically an over-grant. The
4511    // absolute path matches both `acl:accessTo` (container + direct children)
4512    // and `acl:default` (deep descendants) precisely, and mirrors the ACL
4513    // convention every other authz path/test in this crate uses.
4514    let acl_content = format!(
4515        "@prefix acl: <http://www.w3.org/ns/auth/acl#> .\n\
4516         <#owner> a acl:Authorization ;\n\
4517             acl:agent <did:nostr:{pubkey}> ;\n\
4518             acl:accessTo </pods/{pubkey}/> ;\n\
4519             acl:default </pods/{pubkey}/> ;\n\
4520             acl:mode acl:Read, acl:Write, acl:Control .\n"
4521    );
4522
4523    // --- BUG 2: write the ACL where the resolver actually reads it --------
4524    // `wac::resolver::find_effective_acl` walks a resource path up to the
4525    // root probing SIBLING sidecars: for container `/pods/{pk}/` it reads
4526    // `/pods/{pk}.acl` (trailing slash trimmed, then `.acl` appended), and
4527    // any descendant `/pods/{pk}/…` reaches the same sibling as the walk
4528    // climbs. It NEVER reads an inner `/pods/{pk}/.acl`. Provisioning
4529    // previously wrote ONLY that inner copy, so the owner grant was never
4530    // resolved and authenticated writes 403'd. Write the authoritative ACL
4531    // to the sibling location the resolver reads: `data_root/pods/{pk}.acl`.
4532    let sibling_acl_path = pods_root.join(format!("{pubkey}.acl"));
4533    if !sibling_acl_path.exists() {
4534        if let Err(e) = tokio::fs::write(&sibling_acl_path, acl_content.as_bytes()).await {
4535            tracing::error!(pubkey = %pubkey, error = %e, "/_admin/provision: write sibling .acl failed");
4536            return HttpResponse::InternalServerError()
4537                .json(serde_json::json!({"error": format!("failed to write .acl: {e}")}));
4538        }
4539    }
4540
4541    // Courtesy inner copy at `{pod_dir}/.acl`. This server's walk-up resolver
4542    // never reads it (it probes the sibling `{container}.acl`), but the
4543    // node-solid-server (NSS) convention stores a container's ACL INSIDE the
4544    // container as `<container>/.acl`; writing both keeps interop with tooling
4545    // that expects the inner convention. Harmless here — the sibling above is
4546    // authoritative — so a failure to write it is non-fatal.
4547    let inner_acl_path = pod_dir.join(".acl");
4548    if !inner_acl_path.exists() {
4549        if let Err(e) = tokio::fs::write(&inner_acl_path, acl_content.as_bytes()).await {
4550            tracing::warn!(pubkey = %pubkey, error = %e, "/_admin/provision: write inner .acl failed (non-fatal; sibling ACL governs)");
4551        }
4552    }
4553
4554    // --- Git init (feature-gated) ----------------------------------------
4555    #[cfg(feature = "git")]
4556    {
4557        // Only init if .git does not yet exist (idempotent).
4558        if !pod_dir.join(".git").exists() {
4559            let init_out = crate::hardened_git::hardened_git_async()
4560                .args(["init", "-b", "main", pod_dir.to_str().unwrap_or(".")])
4561                .output()
4562                .await;
4563
4564            match init_out {
4565                Ok(out) if out.status.success() => {}
4566                Ok(out) => {
4567                    let stderr = String::from_utf8_lossy(&out.stderr);
4568                    tracing::warn!(pubkey = %pubkey, stderr = %stderr, "git init returned non-zero");
4569                }
4570                Err(e) => {
4571                    tracing::warn!(pubkey = %pubkey, error = %e, "git init failed (git not in PATH?)");
4572                }
4573            }
4574
4575            // Configure receive.denyCurrentBranch=updateInstead so the forum
4576            // client can push directly into the working tree.
4577            let cfg_out = crate::hardened_git::hardened_git_async()
4578                .args([
4579                    "-C",
4580                    pod_dir.to_str().unwrap_or("."),
4581                    "config",
4582                    "receive.denyCurrentBranch",
4583                    "updateInstead",
4584                ])
4585                .output()
4586                .await;
4587
4588            if let Err(e) = cfg_out {
4589                tracing::warn!(pubkey = %pubkey, error = %e, "git config receive.denyCurrentBranch failed");
4590            }
4591        }
4592    }
4593
4594    // --- Build response --------------------------------------------------
4595    let base_url = state.nodeinfo.base_url.trim_end_matches('/');
4596    HttpResponse::Ok().json(serde_json::json!({
4597        "podUrl": format!("{base_url}/pods/{pubkey}/"),
4598        "ok": true,
4599    }))
4600}
4601
4602// ---------------------------------------------------------------------------
4603// /.well-known/apps  (JSS #464 Phase 2 — public app discovery)
4604// ---------------------------------------------------------------------------
4605
4606async fn handle_well_known_apps(state: web::Data<AppState>) -> HttpResponse {
4607    let Some(ref data_root) = state.data_root else {
4608        return HttpResponse::Ok()
4609            .content_type("application/json")
4610            .json(serde_json::json!({"apps": [], "count": 0}));
4611    };
4612
4613    let server_url = state.nodeinfo.base_url.clone();
4614
4615    // Collect pod directories (up to 1000).
4616    let mut read_dir = match tokio::fs::read_dir(data_root).await {
4617        Ok(rd) => rd,
4618        Err(_) => {
4619            return HttpResponse::Ok()
4620                .content_type("application/json")
4621                .json(serde_json::json!({"apps": [], "serverUrl": server_url, "count": 0}));
4622        }
4623    };
4624
4625    let mut apps: Vec<serde_json::Value> = Vec::new();
4626    let mut scanned = 0usize;
4627
4628    while scanned < 1000 {
4629        let entry = match read_dir.next_entry().await {
4630            Ok(Some(e)) => e,
4631            Ok(None) => break,
4632            Err(_) => break,
4633        };
4634
4635        let file_type = match entry.file_type().await {
4636            Ok(ft) => ft,
4637            Err(_) => continue,
4638        };
4639        if !file_type.is_dir() {
4640            continue;
4641        }
4642
4643        scanned += 1;
4644
4645        let manifest_path = entry.path().join("apps").join("manifest.json");
4646        let contents = match tokio::fs::read(&manifest_path).await {
4647            Ok(c) => c,
4648            Err(_) => continue,
4649        };
4650
4651        let mut manifest: serde_json::Value = match serde_json::from_slice(&contents) {
4652            Ok(v) => v,
4653            Err(_) => continue,
4654        };
4655
4656        // Inject podOwner from the directory name (pubkey).
4657        if let Some(pod_name) = entry.file_name().to_str() {
4658            if manifest.get("podOwner").is_none() {
4659                manifest["podOwner"] = serde_json::Value::String(pod_name.to_string());
4660            }
4661        }
4662
4663        apps.push(manifest);
4664    }
4665
4666    let count = apps.len();
4667    HttpResponse::Ok()
4668        .content_type("application/json")
4669        .json(serde_json::json!({
4670            "apps": apps,
4671            "serverUrl": server_url,
4672            "count": count,
4673        }))
4674}
4675
4676// ---------------------------------------------------------------------------
4677// Git HTTP backend handler (JSS #466/#469/#471, feature = "git")
4678// ---------------------------------------------------------------------------
4679
4680/// Returns `true` if `path` is a git smart-HTTP protocol request.
4681///
4682/// Mirrors JSS `src/handlers/git.js` `isGitRequest`:
4683/// ```text
4684/// return urlPath.includes('/info/refs') ||
4685///   urlPath.includes('/git-upload-pack') ||
4686///   urlPath.includes('/git-receive-pack');
4687/// ```
4688#[allow(dead_code)]
4689fn is_git_request(path: &str) -> bool {
4690    path.contains("/info/refs")
4691        || path.contains("/git-upload-pack")
4692        || path.contains("/git-receive-pack")
4693}
4694
4695/// Returns `true` if `path` targets `.git/` internals directly — always
4696/// blocked (security, matches JSS lines 52-68).
4697#[allow(dead_code)]
4698fn is_dot_git_path(path: &str) -> bool {
4699    path.contains("/.git/") || path.ends_with("/.git")
4700}
4701
4702#[cfg(feature = "git")]
4703async fn handle_git(
4704    req: HttpRequest,
4705    body: web::Bytes,
4706    state: web::Data<AppState>,
4707) -> HttpResponse {
4708    use solid_pod_rs_git::auth::{BasicNostrExtractor, GitAuth};
4709    use solid_pod_rs_git::service::GitRequest;
4710
4711    let path = req.uri().path().to_string();
4712
4713    // Locate the pod's FS root: the first path segment after "/" is the
4714    // pod name (username/pubkey). The FS root is data_root/{pod_name}/.
4715    let pod_name = path
4716        .trim_start_matches('/')
4717        .split('/')
4718        .next()
4719        .unwrap_or("")
4720        .to_string();
4721    let Some(ref data_root) = state.data_root else {
4722        return HttpResponse::NotImplemented().json(serde_json::json!({
4723            "error": "git requires fs-backend storage",
4724            "reason": "data_root_not_configured"
4725        }));
4726    };
4727    let repo_root = data_root.join(&pod_name);
4728    if !repo_root.exists() {
4729        return HttpResponse::NotFound().json(serde_json::json!({"error": "pod not found"}));
4730    }
4731
4732    let query = req.uri().query().unwrap_or("").to_string();
4733    let host_url = Some(scheme::request_origin(&req));
4734    let headers: Vec<(String, String)> = req
4735        .headers()
4736        .iter()
4737        .map(|(k, v)| (k.as_str().to_string(), v.to_str().unwrap_or("").to_string()))
4738        .collect();
4739
4740    let git_req = GitRequest {
4741        method: req.method().as_str().to_string(),
4742        path,
4743        query,
4744        headers,
4745        body,
4746        host_url,
4747    };
4748
4749    // Push is not served: `git-receive-pack` and its `info/refs` discovery
4750    // are refused for every caller, before any credential is read. The path
4751    // never worked (the service had no auth provider, so every push was
4752    // refused), and making it work would have needed per-path WAC on every
4753    // pushed file; the owner chose to delete it instead (ER-28).
4754    if git_req.is_write() {
4755        let mut builder = HttpResponse::Forbidden();
4756        for (k, v) in solid_pod_rs_git::service::GIT_CORS_HEADERS {
4757            builder.insert_header((k, v));
4758        }
4759        return builder.json(serde_json::json!({
4760            "error": "git push is not served by this server",
4761            "reason": "push_not_served"
4762        }));
4763    }
4764
4765    // WAC gate (mirrors JSS `server.js` checkAccess before git, ~498-530).
4766    // Git requests were previously handed straight to the CGI with no
4767    // authorisation: a private pod's history was anonymously clonable and
4768    // pushes were anonymous (R5 "No WAC" finding / ADR-059 D6). Resolve the
4769    // caller's `did:nostr` from the git `Basic nostr:`/`Nostr` NIP-98
4770    // credential — an absent or invalid credential resolves to anonymous,
4771    // and WAC then decides, fail-closed. Enforce Read for clone/fetch
4772    // against the pod-root container ACL; push was refused above.
4773    // `enforce_read` grants public pods to anonymous callers and replies 401
4774    // on a private pod so the git client knows to retry with credentials.
4775    let agent = match BasicNostrExtractor::new().authorise(&git_req).await {
4776        Ok(pk) => Some(format!("did:nostr:{pk}")),
4777        Err(_) => None,
4778    };
4779    let wac_path = format!("/{pod_name}/");
4780    let origin = req_origin(&req);
4781    // Only the denial matters on this path; discard the read gate's
4782    // cache-audience classification (ADR-2002), which is a response concern
4783    // the git transport does not have.
4784    let wac = enforce_read_ctx(&state, &wac_path, agent.as_deref(), origin)
4785        .await
4786        .map(|_audience| ());
4787    if let Err(e) = wac {
4788        // JSS #548: the WAC gate's 401/402/403 must carry the git CORS
4789        // headers, or browser-based git clients see a generic CORS/network
4790        // error instead of the status and `WWW-Authenticate` challenge.
4791        let mut resp = e.error_response();
4792        for (k, v) in solid_pod_rs_git::service::GIT_CORS_HEADERS {
4793            if let (Ok(name), Ok(value)) = (
4794                actix_web::http::header::HeaderName::from_bytes(k.as_bytes()),
4795                actix_web::http::header::HeaderValue::from_str(v),
4796            ) {
4797                resp.headers_mut().insert(name, value);
4798            }
4799        }
4800        return resp;
4801    }
4802
4803    let service = solid_pod_rs_git::service::GitHttpService::new(repo_root);
4804    match service.handle(git_req).await {
4805        Ok(git_resp) => {
4806            let mut builder = HttpResponse::build(
4807                actix_web::http::StatusCode::from_u16(git_resp.status)
4808                    .unwrap_or(actix_web::http::StatusCode::INTERNAL_SERVER_ERROR),
4809            );
4810            for (k, v) in &git_resp.headers {
4811                builder.insert_header((k.as_str(), v.as_str()));
4812            }
4813            builder.body(git_resp.body)
4814        }
4815        Err(e) => {
4816            let status = e.status_code();
4817            let mut builder = HttpResponse::build(
4818                actix_web::http::StatusCode::from_u16(status)
4819                    .unwrap_or(actix_web::http::StatusCode::INTERNAL_SERVER_ERROR),
4820            );
4821            for (k, v) in solid_pod_rs_git::service::GIT_CORS_HEADERS {
4822                builder.insert_header((k, v));
4823            }
4824            builder.json(serde_json::json!({"error": e.to_string()}))
4825        }
4826    }
4827}
4828
4829// ---------------------------------------------------------------------------
4830// Git forge (JSS `forge` plugin port) — mounted behind `feature = "forge"`.
4831// ---------------------------------------------------------------------------
4832
4833/// Derive the forge plugin data directory from the pod storage root. The
4834/// forge keeps its repos/spine/hosted/marks under a `.forge` sibling dir
4835/// so it never mixes with pod containers. Returns `None` when no
4836/// filesystem `data_root` is configured (in-memory/cloud storage).
4837#[cfg(feature = "forge")]
4838fn forge_plugin_dir(state: &AppState) -> Option<PathBuf> {
4839    state.data_root.as_ref().map(|r| r.join(".forge"))
4840}
4841
4842/// Reqwest-backed [`LoopbackFetch`](solid_pod_rs_forge::LoopbackFetch) for
4843/// verifying/re-fetching pod-hosted forge bodies. The forge's own-area URL
4844/// guard pins every fetch to the request's own origin, so this only ever
4845/// performs a same-origin loopback GET — the SSRF surface is closed at the
4846/// guard, not here.
4847#[cfg(feature = "forge")]
4848struct ServerLoopback {
4849    client: reqwest::Client,
4850}
4851
4852#[cfg(feature = "forge")]
4853#[async_trait::async_trait]
4854impl solid_pod_rs_forge::LoopbackFetch for ServerLoopback {
4855    async fn get(
4856        &self,
4857        url: &str,
4858        max_bytes: usize,
4859        timeout_secs: u64,
4860    ) -> solid_pod_rs_forge::bodies::FetchResult {
4861        use solid_pod_rs_forge::bodies::FetchResult;
4862        let resp = match self
4863            .client
4864            .get(url)
4865            .timeout(Duration::from_secs(timeout_secs.max(1)))
4866            .send()
4867            .await
4868        {
4869            Ok(r) => r,
4870            Err(e) => return FetchResult::Error(e.to_string()),
4871        };
4872        let code = resp.status().as_u16();
4873        if code == 404 || code == 410 {
4874            return FetchResult::Removed;
4875        }
4876        if !resp.status().is_success() {
4877            return FetchResult::Error(format!("status {code}"));
4878        }
4879        if resp
4880            .content_length()
4881            .is_some_and(|length| length > max_bytes as u64)
4882        {
4883            return FetchResult::TooLarge;
4884        }
4885        let mut stream = resp.bytes_stream();
4886        let mut body = Vec::with_capacity(max_bytes.min(16 * 1024));
4887        while let Some(chunk) = stream.next().await {
4888            match chunk {
4889                Ok(chunk) if body.len().saturating_add(chunk.len()) <= max_bytes => {
4890                    body.extend_from_slice(&chunk);
4891                }
4892                Ok(_) => return FetchResult::TooLarge,
4893                Err(error) => return FetchResult::Error(error.to_string()),
4894            }
4895        }
4896        FetchResult::Body(body)
4897    }
4898}
4899
4900/// A comma-separated environment list, trimmed, empties dropped.
4901#[cfg(feature = "forge")]
4902fn env_list(name: &str) -> Vec<String> {
4903    std::env::var(name)
4904        .ok()
4905        .map(|v| {
4906            v.split(',')
4907                .map(str::trim)
4908                .filter(|s| !s.is_empty())
4909                .map(str::to_string)
4910                .collect()
4911        })
4912        .unwrap_or_default()
4913}
4914
4915/// The forge configuration: the `FORGE_CONFIG` JSON file (if any) under the
4916/// `FORGE_*` environment overrides. Everything is optional; with nothing set
4917/// the defaults hold (testnet chain, mainnet refused, no announce relays,
4918/// no private repos).
4919#[cfg(feature = "forge")]
4920fn forge_config() -> solid_pod_rs_forge::ForgeConfig {
4921    use serde_json::{json, Map, Value};
4922    let mut o = Map::new();
4923    let flag = |n: &str| {
4924        std::env::var(n)
4925            .ok()
4926            .map(|v| matches!(v.to_ascii_lowercase().as_str(), "1" | "true" | "yes" | "on"))
4927    };
4928    if let Some(b) = flag("FORGE_PRIVATE_REPOS") {
4929        o.insert("privateRepos".into(), json!(b));
4930    }
4931    if let Some(b) = flag("FORGE_ALLOW_MAINNET") {
4932        o.insert("allowMainnet".into(), json!(b));
4933    }
4934    if let Some(b) = flag("FORGE_OPEN_EDIT") {
4935        o.insert("openEdit".into(), json!(b));
4936    }
4937    if let Some(b) = flag("FORGE_ANCHORING_UI") {
4938        o.insert("anchoringUi".into(), json!(b));
4939    }
4940    if let Some(b) = flag("FORGE_SPARSE_MARKS") {
4941        o.insert("sparseMarks".into(), json!(b));
4942    }
4943    if let Ok(c) = std::env::var("FORGE_CHAIN") {
4944        if !c.trim().is_empty() {
4945            o.insert("chain".into(), Value::String(c.trim().to_string()));
4946        }
4947    }
4948    if let Ok(u) = std::env::var("FORGE_BASE_URL") {
4949        if !u.trim().is_empty() {
4950            o.insert("baseUrl".into(), Value::String(u.trim().to_string()));
4951        }
4952    }
4953    let relays = env_list("FORGE_ANNOUNCE_RELAYS");
4954    if !relays.is_empty() {
4955        o.insert("announceRelays".into(), json!(relays));
4956    }
4957    solid_pod_rs_forge::ForgeConfig::from_env(Value::Object(o))
4958}
4959
4960/// The mirror configuration from `FORGE_MIRROR_RELAYS` (comma-separated
4961/// `ws(s)://` URLs), `FORGE_MIRROR_FOLLOW` (comma-separated
4962/// `<64-hex pubkey>/<repo>`) and `FORGE_MIRROR_MIN_INTERVAL_MS`. `None` (the
4963/// mirror stays off) unless at least one relay and one valid entry survive.
4964#[cfg(feature = "forge-mirror")]
4965fn mirror_config() -> Option<solid_pod_rs_forge::mirror::MirrorConfig> {
4966    use serde_json::json;
4967    let relays = env_list("FORGE_MIRROR_RELAYS");
4968    let follow: Vec<serde_json::Value> = env_list("FORGE_MIRROR_FOLLOW")
4969        .iter()
4970        .filter_map(|e| e.split_once('/'))
4971        .map(|(pk, name)| json!({"pubkey": pk.trim(), "name": name.trim()}))
4972        .collect();
4973    let mut cfg = json!({"relays": relays, "follow": follow});
4974    if let Some(ms) = std::env::var("FORGE_MIRROR_MIN_INTERVAL_MS")
4975        .ok()
4976        .and_then(|v| v.trim().parse::<u64>().ok())
4977    {
4978        cfg["minIntervalMs"] = json!(ms);
4979    }
4980    solid_pod_rs_forge::mirror::parse_mirror_config(&cfg)
4981}
4982
4983/// A forge service plus the running mirror (kept alive with it).
4984#[cfg(feature = "forge")]
4985struct ForgeRuntime {
4986    service: Arc<solid_pod_rs_forge::ForgeService>,
4987    #[cfg(feature = "forge-mirror")]
4988    _mirror: Option<solid_pod_rs_forge::mirror::MirrorHandle>,
4989}
4990
4991/// One long-lived forge service per forge data directory. It owns state that
4992/// must outlive a request (the per-repository locks, the mirror's relay
4993/// sessions and its inbox), so it is built once and shared.
4994#[cfg(feature = "forge")]
4995fn forge_service(
4996    plugin_dir: PathBuf,
4997) -> Result<Arc<solid_pod_rs_forge::ForgeService>, solid_pod_rs_forge::ForgeError> {
4998    use std::collections::HashMap;
4999    use std::sync::{Mutex, OnceLock};
5000    static REGISTRY: OnceLock<Mutex<HashMap<PathBuf, Arc<ForgeRuntime>>>> = OnceLock::new();
5001    let reg = REGISTRY.get_or_init(|| Mutex::new(HashMap::new()));
5002    let mut reg = reg
5003        .lock()
5004        .unwrap_or_else(std::sync::PoisonError::into_inner);
5005    if let Some(rt) = reg.get(&plugin_dir) {
5006        return Ok(Arc::clone(&rt.service));
5007    }
5008    let cfg = forge_config();
5009    #[cfg(feature = "forge-announce")]
5010    let relay_policy: Arc<dyn solid_pod_rs_forge::publish::SsrfCheck> = Arc::new(
5011        solid_pod_rs_forge::publish::OperatorRelays::new(&cfg.announce_relays),
5012    );
5013    let loopback: Arc<dyn solid_pod_rs_forge::LoopbackFetch> = Arc::new(ServerLoopback {
5014        client: reqwest::Client::new(),
5015    });
5016    let svc =
5017        solid_pod_rs_forge::ForgeService::new(cfg, plugin_dir.clone())?.with_loopback(loopback);
5018    #[cfg(feature = "forge-announce")]
5019    let svc = svc.with_announce_ssrf(relay_policy);
5020    let service = Arc::new(svc);
5021    #[cfg(feature = "forge-mirror")]
5022    let mirror = mirror_config().map(|mcfg| {
5023        use solid_pod_rs_forge::mirror::{GitCli, Mirror, MirrorStore};
5024        let git = Arc::new(GitCli::new(plugin_dir.join("repos")));
5025        let engine = Arc::new(Mirror::new(mcfg, MirrorStore::new(&plugin_dir), git));
5026        tracing::info!("forge: mirror on kind-30618 started");
5027        engine.start()
5028    });
5029    reg.insert(
5030        plugin_dir,
5031        Arc::new(ForgeRuntime {
5032            service: Arc::clone(&service),
5033            #[cfg(feature = "forge-mirror")]
5034            _mirror: mirror,
5035        }),
5036    );
5037    Ok(service)
5038}
5039
5040/// Start the forge (and, with `forge-mirror`, its relay sessions) at boot
5041/// rather than on the first request, so a mirror follows its repositories
5042/// from the moment the server is up. A no-op without a filesystem data root.
5043#[cfg(feature = "forge")]
5044pub fn start_forge(state: &AppState) {
5045    if let Some(dir) = forge_plugin_dir(state) {
5046        match forge_service(dir) {
5047            Ok(_) => tracing::info!("forge: started"),
5048            Err(e) => tracing::error!("forge: could not start: {e}"),
5049        }
5050    }
5051}
5052
5053/// Single actix handler for every `/forge/*` path. Translates actix →
5054/// `ForgeRequest`, resolves the caller identity, and dispatches to the
5055/// forge service. WAC/namespace authorization is enforced inside the
5056/// service (namespace-write guard) and, for git push, by the git CGI's
5057/// own auth provider (wired in the tokens phase).
5058#[cfg(feature = "forge")]
5059async fn handle_forge(
5060    req: HttpRequest,
5061    body: web::Bytes,
5062    state: web::Data<AppState>,
5063) -> HttpResponse {
5064    use solid_pod_rs_forge::ForgeRequest;
5065
5066    let Some(plugin_dir) = forge_plugin_dir(&state) else {
5067        return HttpResponse::NotImplemented().json(serde_json::json!({
5068            "error": "forge requires fs-backend storage",
5069            "reason": "data_root_not_configured"
5070        }));
5071    };
5072
5073    let service = match forge_service(plugin_dir) {
5074        Ok(s) => s,
5075        Err(e) => {
5076            return HttpResponse::InternalServerError()
5077                .json(serde_json::json!({"error": e.to_string()}));
5078        }
5079    };
5080
5081    let path = req.uri().path().to_string();
5082    let query = req.uri().query().unwrap_or("").to_string();
5083    let host_url = Some(scheme::request_origin(&req));
5084    let headers: Vec<(String, String)> = req
5085        .headers()
5086        .iter()
5087        .map(|(k, v)| (k.as_str().to_string(), v.to_str().unwrap_or("").to_string()))
5088        .collect();
5089
5090    let forge_req = ForgeRequest {
5091        method: req.method().as_str().to_string(),
5092        path,
5093        query,
5094        headers,
5095        raw_body: body,
5096        host_url,
5097    };
5098
5099    // Identity resolution: the forge's own resolver handles the forge push
5100    // token (`Bearer f1.…`) and NIP-98 (`Nostr …`). An unresolved caller
5101    // is Anonymous and the service's guards decide, fail-closed. (A pod
5102    // session, when present, would be injected as a `Pod` agent instead.)
5103    let agent = service.resolve_agent(&forge_req).await;
5104
5105    // Kept for the optional Jev rerank (SP-08-S1-01); unused otherwise.
5106    #[cfg(feature = "jev")]
5107    let jev_ctx = (
5108        forge_req.method.clone(),
5109        forge_req.path.clone(),
5110        forge_req.query.clone(),
5111    );
5112
5113    match service.handle(forge_req, agent).await {
5114        Ok(resp) => {
5115            let mut builder = HttpResponse::build(
5116                StatusCode::from_u16(resp.status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR),
5117            );
5118            for (k, v) in &resp.headers {
5119                // A reranked body has a different length; drop the stale one.
5120                #[cfg(feature = "jev")]
5121                if k.eq_ignore_ascii_case("content-length") {
5122                    continue;
5123                }
5124                builder.insert_header((k.as_str(), v.as_str()));
5125            }
5126            // SP-08-S1-01 (forge): the forge has already applied its own
5127            // authorisation to `resp`; only that output is ever reranked, and
5128            // any fallback serves the forge's bytes untouched.
5129            #[cfg(feature = "jev")]
5130            if jev::enabled_in_process_env() {
5131                let rt = jev::JevRuntime::from_process_env();
5132                if let Some(body) = jev::rerank_forge_listing(
5133                    &rt,
5134                    &jev_ctx.0,
5135                    &jev_ctx.1,
5136                    &jev_ctx.2,
5137                    resp.status,
5138                    &resp.body,
5139                )
5140                .await
5141                {
5142                    return builder.body(body);
5143                }
5144            }
5145            builder.body(resp.body)
5146        }
5147        Err(e) => {
5148            let status = e.status_code();
5149            HttpResponse::build(
5150                StatusCode::from_u16(status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR),
5151            )
5152            .json(serde_json::json!({"error": e.to_string()}))
5153        }
5154    }
5155}
5156
5157// ---------------------------------------------------------------------------
5158// Public app builder
5159// ---------------------------------------------------------------------------
5160
5161/// Build the complete actix `App` for the Solid Pod server. Both the
5162/// binary (`main.rs`) and the workspace integration tests call this.
5163///
5164/// The returned `App` is fully-configured: route table, normaliser,
5165/// path-traversal guard, dotfile allowlist, body cap, CORS middleware
5166/// (when available), rate-limit middleware (when available), and WAC
5167/// enforcement.
5168pub fn build_app(
5169    state: AppState,
5170) -> App<
5171    impl actix_web::dev::ServiceFactory<
5172        ServiceRequest,
5173        Config = (),
5174        Response = ServiceResponse<EitherBody<EitherBody<BoxBody>>>,
5175        Error = ActixError,
5176        InitError = (),
5177    >,
5178> {
5179    let body_cap = state.body_cap;
5180    let dotfiles = state.dotfiles.clone();
5181    let allowed_origins = Arc::new(state.allowed_origins.clone());
5182    let allowed_hosts = state.allowed_hosts.clone();
5183
5184    let mut app = App::new()
5185        .app_data(web::Data::new(state.clone()))
5186        .app_data(web::PayloadConfig::new(body_cap))
5187        // Sprint 11 (row 158): outermost layer so it observes every
5188        // response — including those that short-circuited in inner
5189        // guards. Wrapping first means `wrap()` applies it last in
5190        // actix's stack order.
5191        .wrap(ErrorLoggingMiddleware)
5192        .wrap(CorsHeaders { allowed_origins })
5193        // `MergeOnly` collapses duplicate slashes (//a → /a) without
5194        // stripping the trailing slash, which is the container/resource
5195        // discriminator in LDP.
5196        .wrap(NormalizePath::new(TrailingSlash::MergeOnly))
5197        .wrap(PathTraversalGuard)
5198        .wrap(DotfileGuard::new(dotfiles).with_host_policy(HostPolicy {
5199            allowed: allowed_hosts,
5200            trust_proxy: state.trust_proxy,
5201        }));
5202
5203    // CORS / rate-limit: middleware is driven by the library types from
5204    // S7-A. We register pass-through headers when the env-driven policy
5205    // permits. The middleware is a no-op today beyond emitting the
5206    // policy's `response_headers` on every response; full preflight
5207    // handling lives in the sibling S7-A work.
5208    app = app
5209        .route("/.well-known/solid", web::get().to(handle_well_known_solid))
5210        .route(
5211            "/.well-known/webfinger",
5212            web::get().to(handle_well_known_webfinger),
5213        )
5214        .route(
5215            "/.well-known/nodeinfo",
5216            web::get().to(handle_well_known_nodeinfo),
5217        )
5218        .route(
5219            "/.well-known/nodeinfo/2.1",
5220            web::get().to(handle_well_known_nodeinfo_2_1),
5221        );
5222
5223    #[cfg(feature = "did-nostr")]
5224    {
5225        app = app.route(
5226            "/.well-known/did/nostr/{pubkey}.json",
5227            web::get().to(handle_well_known_did_nostr),
5228        );
5229    }
5230
5231    // JSS v0.0.190 Phase 1 port (issue #437), parity row 197.
5232    // Pod-resident NIP-05 endpoint. `handle_well_known_nip05` is
5233    // implemented and routed (bodies landed in 0.4.0-alpha.11; no
5234    // `todo!()`). Feature `nip05-endpoint` (default-off).
5235    #[cfg(feature = "nip05-endpoint")]
5236    {
5237        app = app.route(
5238            "/.well-known/nostr.json",
5239            web::get().to(handle_well_known_nip05),
5240        );
5241    }
5242
5243    // JSS v0.0.190 Phase 1 port (issue #437), parity row 198. JSON-LD
5244    // time-chain pod export. Native-only (`export-jsonld`, default-off);
5245    // owner-WAC-gated inside the handler. Registered before the LDP
5246    // catch-all so `/api/exports/all` is never treated as a pod resource.
5247    #[cfg(feature = "export-jsonld")]
5248    {
5249        app = app.route("/api/exports/all", web::get().to(handle_export_all));
5250    }
5251
5252    // App discovery endpoint (JSS #464 Phase 2 — public, no auth required).
5253    app = app.route("/.well-known/apps", web::get().to(handle_well_known_apps));
5254
5255    // Payment endpoint (JSS parity: GET /pay/.info).
5256    app = app.route("/pay/.info", web::get().to(handle_pay_info));
5257
5258    // Phase 0 payment routing (master-plan §"Phase 0"): wire the orphaned
5259    // order-book / AMM / Web-Ledger logic. Registered with the SAME gating
5260    // as `/pay/.info` above — always-on, no payments feature flag — so the
5261    // whole `/pay/*` surface is consistent.
5262    app = app.configure(handlers::pay::register);
5263
5264    // WAC-gated CORS proxy endpoint.
5265    app = app.route("/proxy", web::get().to(handle_proxy));
5266
5267    // MCP (Model Context Protocol) endpoint — opt-in tool surface for
5268    // agents (JSS #490). Registered before the LDP catch-all so `/mcp` is
5269    // never treated as a pod resource. OFF unless `--mcp` / `JSS_MCP`.
5270    if state.mcp_enabled {
5271        app = app.route("/mcp", web::post().to(mcp::handle_mcp)).route(
5272            "/mcp",
5273            web::method(actix_web::http::Method::OPTIONS).to(mcp::handle_mcp_options),
5274        );
5275    }
5276
5277    // Admin provisioning endpoint (alpha.15). Must be before the LDP
5278    // catch-all so `_admin` is never treated as a pod name.
5279    app = app.route(
5280        "/_admin/provision/{pubkey}",
5281        web::post().to(handle_admin_provision),
5282    );
5283
5284    // Pod management API (JSS parity: /api/accounts/*)
5285    app = app
5286        .route("/.pods", web::post().to(handle_create_pod))
5287        .route("/api/accounts/new", web::post().to(handle_create_account))
5288        .route("/pods/check/{name}", web::get().to(handle_pod_check))
5289        .route("/login/password", web::post().to(handle_login_password))
5290        .route(
5291            "/account/password/reset",
5292            web::post().to(handle_password_reset_request),
5293        )
5294        .route(
5295            "/account/password/change",
5296            web::post().to(handle_password_change),
5297        );
5298
5299    // Git forge routes (JSS `forge` plugin port). Registered BEFORE the
5300    // pod-git smart-HTTP catch-all so `/forge/<o>/<n>.git/info/refs` is
5301    // handled by the forge (which forwards to its own CGI service) rather
5302    // than the pod-git handler. Gated by `feature = "forge"`.
5303    #[cfg(feature = "forge")]
5304    {
5305        app = app
5306            .route("/forge", web::route().to(handle_forge))
5307            .route("/forge/{tail:.*}", web::route().to(handle_forge));
5308    }
5309
5310    // Git smart-HTTP protocol routes (JSS #466/#469/#471).
5311    // Must be registered before the LDP catch-all. Direct .git/ access is
5312    // always blocked (security). Smart-HTTP paths are served by
5313    // GitHttpService when the `git` feature is enabled; otherwise 501.
5314    app = app
5315        .route(
5316            // Block direct .git/ access (JSS: "BLOCK: Direct access to .git contents")
5317            "/{tail:.*}/.git",
5318            web::route().to(|| async {
5319                HttpResponse::Forbidden()
5320                    .json(serde_json::json!({"error": "direct .git access is forbidden"}))
5321            }),
5322        )
5323        .route(
5324            "/{tail:.*}/.git/{rest:.*}",
5325            web::route().to(|| async {
5326                HttpResponse::Forbidden()
5327                    .json(serde_json::json!({"error": "direct .git access is forbidden"}))
5328            }),
5329        );
5330
5331    // OPTIONS preflight for /_git panel REST API (alpha.15). Registered
5332    // unconditionally (before the feature block) so browsers get a valid
5333    // CORS response regardless of whether the git feature is compiled in.
5334    app = app.route(
5335        "/pods/{pk}/_git/{tail:.*}",
5336        web::method(actix_web::http::Method::OPTIONS).to(handle_git_panel_options),
5337    );
5338
5339    #[cfg(feature = "git")]
5340    {
5341        // Git smart-HTTP: info/refs discovery + upload-pack (clone/fetch).
5342        // `git-receive-pack` stays routed here only so `handle_git` refuses
5343        // it: unrouted, the POST would fall through to the LDP catch-all and
5344        // create a resource named `git-receive-pack`. Push is not served
5345        // (estate register ER-28, owner decision 2026-10-18); agentbox serves
5346        // pod git push through its own owner-only route.
5347        app = app
5348            .route("/{tail:.*}/info/refs", web::get().to(handle_git))
5349            .route("/{tail:.*}/git-upload-pack", web::post().to(handle_git))
5350            .route("/{tail:.*}/git-receive-pack", web::post().to(handle_git));
5351
5352        // Git control panel REST API. Routes registered before the LDP
5353        // catch-all so `_git` segments are never treated as LDP resources.
5354        app = app
5355            .route(
5356                "/pods/{pubkey}/_git/status",
5357                web::get().to(handle_git_status),
5358            )
5359            .route("/pods/{pubkey}/_git/log", web::get().to(handle_git_log))
5360            .route("/pods/{pubkey}/_git/diff", web::get().to(handle_git_diff))
5361            .route(
5362                "/pods/{pubkey}/_git/stage",
5363                web::post().to(handle_git_stage),
5364            )
5365            .route(
5366                "/pods/{pubkey}/_git/unstage",
5367                web::post().to(handle_git_unstage),
5368            )
5369            .route(
5370                "/pods/{pubkey}/_git/commit",
5371                web::post().to(handle_git_commit),
5372            )
5373            .route(
5374                "/pods/{pubkey}/_git/branches",
5375                web::get().to(handle_git_branches),
5376            )
5377            .route(
5378                "/pods/{pubkey}/_git/branch",
5379                web::post().to(handle_git_create_branch),
5380            )
5381            .route(
5382                "/pods/{pubkey}/_git/discard",
5383                web::post().to(handle_git_discard),
5384            );
5385
5386        // Provenance `_prov` API (ADR-059 Phase 5, master-plan §2.4):
5387        // resolve a git-mark commit SHA, and the explicit (payment-gated)
5388        // git-mark → Bitcoin-anchor upgrade. Registered before the LDP
5389        // catch-all so `_prov` segments are never treated as pod resources.
5390        // The `.prov.ttl` sidecar GET is served by the ordinary LDP read path
5391        // (it is a stored resource).
5392        app = app.configure(handlers::prov::register);
5393    }
5394    #[cfg(not(feature = "git"))]
5395    {
5396        // Without the git feature: return 501 for git protocol paths so
5397        // callers get a clear "not compiled in" signal rather than falling
5398        // through to LDP.
5399        let git_501 = || async {
5400            HttpResponse::NotImplemented()
5401                .json(serde_json::json!({"error": "git feature not enabled in this build"}))
5402        };
5403        app = app
5404            .route("/{tail:.*}/info/refs", web::get().to(git_501))
5405            .route("/{tail:.*}/git-upload-pack", web::post().to(git_501))
5406            .route("/{tail:.*}/git-receive-pack", web::post().to(git_501));
5407    }
5408
5409    // Container POST and PUT (trailing slash) must register before the
5410    // catch-all so the trailing-slash variant wins.
5411    app.route("/{tail:.*}/", web::post().to(handle_post))
5412        .route("/{tail:.*}/", web::put().to(handle_put))
5413        .route("/{tail:.*}", web::get().to(handle_get))
5414        .route("/{tail:.*}", web::head().to(handle_get))
5415        .route("/{tail:.*}", web::put().to(handle_put))
5416        .route("/{tail:.*}", web::patch().to(handle_patch))
5417        .route("/{tail:.*}", web::delete().to(handle_delete))
5418        .route(
5419            "/{tail:.*}",
5420            web::method(actix_web::http::Method::from_bytes(b"COPY").unwrap()).to(handle_copy),
5421        )
5422        .route(
5423            "/{tail:.*}",
5424            web::method(actix_web::http::Method::OPTIONS).to(handle_options),
5425        )
5426}
5427
5428// ---------------------------------------------------------------------------
5429// Tests — sat-gating loop closure (PaymentCondition wired to real ledger)
5430// ---------------------------------------------------------------------------
5431
5432#[cfg(test)]
5433mod payment_gating_tests {
5434    use super::*;
5435    use solid_pod_rs::payments::WebLedger;
5436    use solid_pod_rs::storage::memory::MemoryBackend;
5437
5438    /// The paying principal's DID, spelt once so the ACL fixtures below
5439    /// cannot drift from [`PRINCIPAL`]. Teller's `accountOf` only accepts a
5440    /// `did:nostr:<64 hex>` account, so every ledger-seeding fixture uses one.
5441    macro_rules! principal {
5442        () => {
5443            "did:nostr:4f355bdcb7cc0af728ef3cceb9615d90684bb5b2ca5f859ab0f0b704075871aa"
5444        };
5445    }
5446
5447    const PRINCIPAL: &str = principal!();
5448
5449    /// A second, valid `did:nostr:<64 hex>` account that is not `PRINCIPAL`.
5450    const OTHER_PRINCIPAL: &str =
5451        "did:nostr:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";
5452
5453    /// Turtle ACL granting `PRINCIPAL` Write on `/premium/inbox`
5454    /// only when a `PaymentCondition` of 100 sats is satisfied.
5455    const PAID_WRITE_ACL: &str = concat!(
5456        r#"
5457@prefix acl: <http://www.w3.org/ns/auth/acl#> .
5458
5459<#paid-write> a acl:Authorization ;
5460    acl:agent <"#,
5461        principal!(),
5462        r#"> ;
5463    acl:accessTo </premium/inbox> ;
5464    acl:mode acl:Write ;
5465    acl:condition [
5466        a acl:PaymentCondition ;
5467        acl:costSats 100
5468    ] .
5469"#
5470    );
5471
5472    async fn seed_ledger(storage: &dyn Storage, did: &str, sats: u64) {
5473        let mut ledger = WebLedger::new("Test Pod Credits");
5474        if sats > 0 {
5475            ledger
5476                .credit_by_outpoint(did, "satoshi", &"ab".repeat(32), 0, sats)
5477                .unwrap();
5478        }
5479        let body = serde_json::to_vec(&ledger).unwrap();
5480        storage
5481            .put(WEBLEDGER_PATH, Bytes::from(body), "application/json")
5482            .await
5483            .unwrap();
5484    }
5485
5486    async fn seed_acl(storage: &dyn Storage) {
5487        storage
5488            .put(
5489                "/premium/inbox.acl",
5490                Bytes::from(PAID_WRITE_ACL),
5491                "text/turtle",
5492            )
5493            .await
5494            .unwrap();
5495    }
5496
5497    /// The resolver reads the principal's balance from the seeded ledger.
5498    #[actix_web::test]
5499    async fn resolve_balance_reads_ledger_entry() {
5500        let storage = MemoryBackend::new();
5501        seed_ledger(&storage, PRINCIPAL, 250).await;
5502        assert_eq!(
5503            resolve_balance_sats(&storage, Some(PRINCIPAL)).await,
5504            Some(250)
5505        );
5506    }
5507
5508    /// No ledger entry → authenticated principal resolves to zero balance.
5509    #[actix_web::test]
5510    async fn resolve_balance_zero_when_no_entry() {
5511        let storage = MemoryBackend::new();
5512        seed_ledger(&storage, OTHER_PRINCIPAL, 500).await;
5513        assert_eq!(
5514            resolve_balance_sats(&storage, Some(PRINCIPAL)).await,
5515            Some(0)
5516        );
5517    }
5518
5519    /// Regression guard for the fixtures themselves: every account the
5520    /// ledger is seeded with must be one teller's `accountOf` accepts
5521    /// (`did:nostr:<64 hex>`), and every ACL fixture that names the paying
5522    /// principal must name exactly `PRINCIPAL`. A short `did:nostr:bob`
5523    /// seed or an ACL left on `did:nostr:alice` panics or silently denies.
5524    #[test]
5525    fn fixtures_use_teller_accounts_and_grant_the_principal() {
5526        use solid_pod_rs::payments::account_of;
5527        for did in [PRINCIPAL, OTHER_PRINCIPAL] {
5528            assert_eq!(account_of(did).unwrap(), did, "{did} must be canonical");
5529        }
5530        assert_ne!(PRINCIPAL, OTHER_PRINCIPAL);
5531        assert!(account_of("did:nostr:bob").is_err());
5532        let agent = format!("acl:agent <{PRINCIPAL}>");
5533        for (name, acl) in [
5534            ("PAID_WRITE_ACL", PAID_WRITE_ACL),
5535            ("WRITE_NOT_CONTROL_ACL", WRITE_NOT_CONTROL_ACL),
5536        ] {
5537            assert!(acl.contains(&agent), "{name} must grant PRINCIPAL");
5538        }
5539        assert!(!WRITE_NOT_CONTROL_ACL.contains("did:nostr:alice"));
5540    }
5541
5542    /// A pay-per-read resource is debited once by a plain read, but refused
5543    /// (and never debited) by the uncharged check glob GET runs per child.
5544    #[actix_web::test]
5545    async fn uncharged_read_skips_pay_per_read_resource() {
5546        let storage = Arc::new(MemoryBackend::new());
5547        let acl = format!(
5548            "@prefix acl: <http://www.w3.org/ns/auth/acl#> .\n\
5549             <#paid> a acl:Authorization ; acl:agent <{PRINCIPAL}> ;\n\
5550               acl:accessTo </premium/doc> ; acl:mode acl:Read ;\n\
5551               acl:condition [ a acl:PaymentCondition ; acl:costSats 100 ] .\n"
5552        );
5553        storage
5554            .put("/premium/doc.acl", Bytes::from(acl), "text/turtle")
5555            .await
5556            .unwrap();
5557        seed_ledger(storage.as_ref(), PRINCIPAL, 500).await;
5558        let state = AppState::new(storage.clone());
5559
5560        let skipped =
5561            enforce_read_inner(&state, "/premium/doc", Some(PRINCIPAL), None, false).await;
5562        assert!(skipped.is_err(), "glob must not serve a pay-per-read child");
5563        assert_eq!(
5564            resolve_balance_sats(&*storage, Some(PRINCIPAL)).await,
5565            Some(500)
5566        );
5567
5568        enforce_read_ctx(&state, "/premium/doc", Some(PRINCIPAL), None)
5569            .await
5570            .expect("a direct read pays and is served");
5571        assert_eq!(
5572            resolve_balance_sats(&*storage, Some(PRINCIPAL)).await,
5573            Some(400)
5574        );
5575    }
5576
5577    /// Anonymous (no principal) → `None`, so a PaymentCondition fails closed.
5578    #[actix_web::test]
5579    async fn resolve_balance_none_when_anonymous() {
5580        let storage = MemoryBackend::new();
5581        seed_ledger(&storage, PRINCIPAL, 1_000).await;
5582        assert_eq!(resolve_balance_sats(&storage, None).await, None);
5583    }
5584
5585    /// End-to-end: a sat-priced resource is DENIED below balance.
5586    #[actix_web::test]
5587    async fn paid_write_denied_below_balance() {
5588        let storage = Arc::new(MemoryBackend::new());
5589        seed_acl(storage.as_ref()).await;
5590        seed_ledger(storage.as_ref(), PRINCIPAL, 50).await; // < 100 cost
5591        let state = AppState::new(storage);
5592
5593        let result =
5594            enforce_write(&state, "/premium/inbox", AccessMode::Write, Some(PRINCIPAL)).await;
5595        assert!(
5596            result.is_err(),
5597            "balance 50 < cost 100 must be denied — sat-gating loop closed"
5598        );
5599    }
5600
5601    /// End-to-end: a sat-priced resource is ALLOWED at the balance threshold.
5602    #[actix_web::test]
5603    async fn paid_write_allowed_at_balance() {
5604        let storage = Arc::new(MemoryBackend::new());
5605        seed_acl(storage.as_ref()).await;
5606        seed_ledger(storage.as_ref(), PRINCIPAL, 100).await; // == 100 cost
5607        let state = AppState::new(storage);
5608
5609        let result =
5610            enforce_write(&state, "/premium/inbox", AccessMode::Write, Some(PRINCIPAL)).await;
5611        assert!(
5612            result.is_ok(),
5613            "balance 100 >= cost 100 must be granted — sat-gating loop closed"
5614        );
5615    }
5616
5617    /// End-to-end: a sat-priced resource is ALLOWED above the threshold.
5618    #[actix_web::test]
5619    async fn paid_write_allowed_above_balance() {
5620        let storage = Arc::new(MemoryBackend::new());
5621        seed_acl(storage.as_ref()).await;
5622        seed_ledger(storage.as_ref(), PRINCIPAL, 5_000).await;
5623        let state = AppState::new(storage);
5624
5625        let result =
5626            enforce_write(&state, "/premium/inbox", AccessMode::Write, Some(PRINCIPAL)).await;
5627        assert!(result.is_ok(), "balance 5000 >= cost 100 must be granted");
5628    }
5629
5630    /// Regression guard: before this fix `payment_balance_sats` was
5631    /// hardcoded `None`, so even an over-funded principal was denied.
5632    /// An anonymous caller (no principal) must still be denied.
5633    #[actix_web::test]
5634    async fn paid_write_anonymous_denied() {
5635        let storage = Arc::new(MemoryBackend::new());
5636        seed_acl(storage.as_ref()).await;
5637        seed_ledger(storage.as_ref(), PRINCIPAL, 5_000).await;
5638        let state = AppState::new(storage);
5639
5640        let result = enforce_write(&state, "/premium/inbox", AccessMode::Write, None).await;
5641        assert!(
5642            result.is_err(),
5643            "anonymous caller has no ledger principal — PaymentCondition fails closed"
5644        );
5645    }
5646
5647    // -----------------------------------------------------------------
5648    // R-04: sat-gating is a DEBIT, not just a balance check. A granted
5649    // payment-gated request must consume the matched rule's cost from the
5650    // caller's Web Ledger exactly once.
5651    // -----------------------------------------------------------------
5652
5653    async fn read_balance(storage: &dyn Storage, did: &str) -> u64 {
5654        let (bytes, _) = storage.get(WEBLEDGER_PATH).await.unwrap();
5655        let ledger: WebLedger = serde_json::from_slice(&bytes).unwrap();
5656        ledger.get_balance(did)
5657    }
5658
5659    /// A granted paid WRITE debits the cost from the ledger.
5660    #[actix_web::test]
5661    async fn paid_write_debits_ledger() {
5662        let storage = Arc::new(MemoryBackend::new());
5663        seed_acl(storage.as_ref()).await;
5664        seed_ledger(storage.as_ref(), PRINCIPAL, 250).await; // cost 100
5665        let state = AppState::new(storage.clone());
5666
5667        let result =
5668            enforce_write(&state, "/premium/inbox", AccessMode::Write, Some(PRINCIPAL)).await;
5669        assert!(result.is_ok(), "balance 250 >= cost 100 must be granted");
5670        assert_eq!(
5671            read_balance(storage.as_ref(), PRINCIPAL).await,
5672            150,
5673            "250 - 100 cost: the grant must debit exactly the matched rule's cost"
5674        );
5675    }
5676
5677    /// A second granted paid WRITE debits again (no free re-read of the
5678    /// same resource once the balance is consumed).
5679    #[actix_web::test]
5680    async fn paid_write_debits_each_grant() {
5681        let storage = Arc::new(MemoryBackend::new());
5682        seed_acl(storage.as_ref()).await;
5683        seed_ledger(storage.as_ref(), PRINCIPAL, 250).await; // cost 100
5684        let state = AppState::new(storage.clone());
5685
5686        enforce_write(&state, "/premium/inbox", AccessMode::Write, Some(PRINCIPAL))
5687            .await
5688            .unwrap();
5689        enforce_write(&state, "/premium/inbox", AccessMode::Write, Some(PRINCIPAL))
5690            .await
5691            .unwrap();
5692        assert_eq!(
5693            read_balance(storage.as_ref(), PRINCIPAL).await,
5694            50,
5695            "250 - 2*100: each granted request debits, no unmetered re-use"
5696        );
5697
5698        // Third request: 50 < 100 — gate denies, balance unchanged.
5699        let third =
5700            enforce_write(&state, "/premium/inbox", AccessMode::Write, Some(PRINCIPAL)).await;
5701        assert!(third.is_err(), "balance 50 < cost 100 must now be denied");
5702        assert_eq!(
5703            read_balance(storage.as_ref(), PRINCIPAL).await,
5704            50,
5705            "a denied request must not debit"
5706        );
5707    }
5708
5709    /// A granted paid READ debits the cost from the ledger.
5710    #[actix_web::test]
5711    async fn paid_read_debits_ledger() {
5712        const PAID_READ_ACL: &str = r#"
5713@prefix acl: <http://www.w3.org/ns/auth/acl#> .
5714
5715<#paid-read> a acl:Authorization ;
5716    acl:agent <did:nostr:4f355bdcb7cc0af728ef3cceb9615d90684bb5b2ca5f859ab0f0b704075871aa> ;
5717    acl:accessTo </premium/feed> ;
5718    acl:mode acl:Read ;
5719    acl:condition [
5720        a acl:PaymentCondition ;
5721        acl:costSats 30
5722    ] .
5723"#;
5724        let storage = Arc::new(MemoryBackend::new());
5725        storage
5726            .put(
5727                "/premium/feed.acl",
5728                Bytes::from(PAID_READ_ACL),
5729                "text/turtle",
5730            )
5731            .await
5732            .unwrap();
5733        seed_ledger(storage.as_ref(), PRINCIPAL, 100).await;
5734        let state = AppState::new(storage.clone());
5735
5736        let result = enforce_read(&state, "/premium/feed", Some(PRINCIPAL)).await;
5737        assert!(result.is_ok(), "balance 100 >= cost 30 must be granted");
5738        assert_eq!(
5739            read_balance(storage.as_ref(), PRINCIPAL).await,
5740            70,
5741            "100 - 30 cost: a granted paid read must debit"
5742        );
5743    }
5744
5745    /// A granted FREE read (no PaymentCondition) leaves the ledger
5746    /// untouched.
5747    #[actix_web::test]
5748    async fn free_read_does_not_debit() {
5749        let storage = Arc::new(MemoryBackend::new());
5750        seed_private_read_acl(storage.as_ref()).await; // no PaymentCondition
5751        seed_ledger(storage.as_ref(), PRINCIPAL, 100).await;
5752        let state = AppState::new(storage.clone());
5753
5754        enforce_read(&state, "/private/secret", Some(PRINCIPAL))
5755            .await
5756            .unwrap();
5757        assert_eq!(
5758            read_balance(storage.as_ref(), PRINCIPAL).await,
5759            100,
5760            "a grant with no PaymentCondition must not debit"
5761        );
5762    }
5763
5764    // -----------------------------------------------------------------
5765    // P0-1: WAC read enforcement (enforce_read)
5766    // -----------------------------------------------------------------
5767
5768    /// ACL granting `alice` Read on `/private/` but NO public/`bob` read.
5769    const ALICE_ONLY_READ_ACL: &str = r#"
5770@prefix acl: <http://www.w3.org/ns/auth/acl#> .
5771
5772<#alice> a acl:Authorization ;
5773    acl:agent <did:nostr:4f355bdcb7cc0af728ef3cceb9615d90684bb5b2ca5f859ab0f0b704075871aa> ;
5774    acl:accessTo </private/secret> ;
5775    acl:default </private/> ;
5776    acl:mode acl:Read, acl:Write, acl:Control .
5777"#;
5778
5779    async fn seed_private_read_acl(storage: &dyn Storage) {
5780        // The resolver walks up from `/private/secret` and probes the
5781        // container sidecar at `/private.acl` (it trims the trailing
5782        // slash before appending `.acl`). The grant inherits down via
5783        // `acl:default </private/>`.
5784        storage
5785            .put(
5786                "/private.acl",
5787                Bytes::from(ALICE_ONLY_READ_ACL),
5788                "text/turtle",
5789            )
5790            .await
5791            .unwrap();
5792    }
5793
5794    /// Before the P0-1 fix `handle_get` served `storage.get()` verbatim
5795    /// with no read-authz, so any resource was world-readable. The owner
5796    /// must be granted Read…
5797    #[actix_web::test]
5798    async fn enforce_read_grants_owner() {
5799        let storage = Arc::new(MemoryBackend::new());
5800        seed_private_read_acl(storage.as_ref()).await;
5801        let state = AppState::new(storage);
5802        let result = enforce_read(&state, "/private/secret", Some(PRINCIPAL)).await;
5803        assert!(result.is_ok(), "owner alice must be granted Read");
5804    }
5805
5806    /// …and an unrelated authenticated principal must be DENIED Read on a
5807    /// private resource (no world-readable leak).
5808    #[actix_web::test]
5809    async fn enforce_read_denies_other_principal() {
5810        let storage = Arc::new(MemoryBackend::new());
5811        seed_private_read_acl(storage.as_ref()).await;
5812        let state = AppState::new(storage);
5813        let result = enforce_read(&state, "/private/secret", Some("did:nostr:bob")).await;
5814        assert!(
5815            result.is_err(),
5816            "bob has no Read grant — private resource must not be world-readable"
5817        );
5818    }
5819
5820    /// An anonymous reader is also denied (deny-by-default; no ACL grants
5821    /// public/foaf:Agent Read).
5822    #[actix_web::test]
5823    async fn enforce_read_denies_anonymous() {
5824        let storage = Arc::new(MemoryBackend::new());
5825        seed_private_read_acl(storage.as_ref()).await;
5826        let state = AppState::new(storage);
5827        let result = enforce_read(&state, "/private/secret", None).await;
5828        assert!(result.is_err(), "anonymous Read must be denied");
5829    }
5830
5831    // -----------------------------------------------------------------
5832    // P0-2: `.acl` write requires acl:Control on the protected resource
5833    // -----------------------------------------------------------------
5834
5835    /// ACL granting `writer` Write (but NOT Control) on `/shared/`, and
5836    /// the owner (`PRINCIPAL`) full Control. A Write-only principal must
5837    /// not be able to rewrite the ACL (privilege escalation).
5838    const WRITE_NOT_CONTROL_ACL: &str = concat!(
5839        r#"
5840@prefix acl: <http://www.w3.org/ns/auth/acl#> .
5841
5842<#owner> a acl:Authorization ;
5843    acl:agent <"#,
5844        principal!(),
5845        r#"> ;
5846    acl:accessTo </shared/doc> ;
5847    acl:default </shared/> ;
5848    acl:mode acl:Read, acl:Write, acl:Control .
5849
5850<#writer> a acl:Authorization ;
5851    acl:agent <did:nostr:writer> ;
5852    acl:accessTo </shared/doc> ;
5853    acl:default </shared/> ;
5854    acl:mode acl:Read, acl:Write .
5855"#
5856    );
5857
5858    async fn seed_shared_acl(storage: &dyn Storage) {
5859        // P0-2 resolves the protected resource `/shared/` and the
5860        // resolver probes its sidecar at `/shared.acl` (trailing slash
5861        // trimmed before `.acl`). Seed there so the Control evaluation
5862        // finds the grant.
5863        storage
5864            .put(
5865                "/shared.acl",
5866                Bytes::from(WRITE_NOT_CONTROL_ACL),
5867                "text/turtle",
5868            )
5869            .await
5870            .unwrap();
5871    }
5872
5873    /// A principal with Write but NOT Control on a container is denied PUT
5874    /// on its `.acl` — the check is elevated to acl:Control on the
5875    /// protected resource, closing the privilege-escalation path.
5876    #[actix_web::test]
5877    async fn acl_put_denied_for_writer_without_control() {
5878        let storage = Arc::new(MemoryBackend::new());
5879        seed_shared_acl(storage.as_ref()).await;
5880        let state = AppState::new(storage);
5881        // The request path is the `.acl` sidecar; before the fix this was
5882        // checked as Write on the sidecar (granted). Now it requires
5883        // Control on `/shared/`.
5884        let result = enforce_write(
5885            &state,
5886            "/shared/.acl",
5887            AccessMode::Write,
5888            Some("did:nostr:writer"),
5889        )
5890        .await;
5891        assert!(
5892            result.is_err(),
5893            "writer lacks Control — must not be able to PUT /shared/.acl"
5894        );
5895    }
5896
5897    /// The Control holder (owner) is still allowed to PUT the `.acl`.
5898    #[actix_web::test]
5899    async fn acl_put_allowed_for_control_holder() {
5900        let storage = Arc::new(MemoryBackend::new());
5901        seed_shared_acl(storage.as_ref()).await;
5902        let state = AppState::new(storage);
5903        let result =
5904            enforce_write(&state, "/shared/.acl", AccessMode::Write, Some(PRINCIPAL)).await;
5905        assert!(
5906            result.is_ok(),
5907            "the owner holds Control — must be allowed to PUT /shared/.acl"
5908        );
5909    }
5910
5911    /// The same elevation applies to `.meta` sidecars.
5912    #[actix_web::test]
5913    async fn meta_put_denied_for_writer_without_control() {
5914        let storage = Arc::new(MemoryBackend::new());
5915        seed_shared_acl(storage.as_ref()).await;
5916        let state = AppState::new(storage);
5917        let result = enforce_write(
5918            &state,
5919            "/shared/doc.meta",
5920            AccessMode::Write,
5921            Some("did:nostr:writer"),
5922        )
5923        .await;
5924        assert!(
5925            result.is_err(),
5926            "writer lacks Control — must not be able to PUT a .meta sidecar"
5927        );
5928    }
5929
5930    /// Trail secrets are Control-gated; their sidecars map to Control on the
5931    /// trail file; the public `blocktrails.json` and ordinary paths are not.
5932    #[test]
5933    fn canonical_pod_path_vectors() {
5934        let ok = [
5935            ("a/b", "/a/b"),
5936            ("", "/"),
5937            ("/", "/"),
5938            ("//a//b/", "/a/b/"),
5939            ("/%2ewell-known/x", "/.well-known/x"),
5940            ("/a%2fb", "/a/b"),
5941            ("/a%2520b", "/a%20b"),
5942        ];
5943        for (raw, want) in ok {
5944            assert_eq!(canonical_pod_path(raw).as_deref(), Some(want), "{raw}");
5945        }
5946        for bad in [
5947            "/a/./b",
5948            "/a/..",
5949            "../a",
5950            "/a\\b",
5951            "/a%00b",
5952            "/a%ffb",
5953            "/%2e%2e/x",
5954        ] {
5955            assert_eq!(canonical_pod_path(bad), None, "{bad}");
5956        }
5957    }
5958
5959    #[test]
5960    fn guarded_acl_target_vectors() {
5961        use AccessMode::{Control, Read, Write};
5962        let c = |p: &str, m| guarded_acl_target(p, m);
5963        assert_eq!(
5964            c("/.well-known/token/x.json", Read),
5965            ("/.well-known/token/x.json".into(), Control)
5966        );
5967        assert_eq!(
5968            c("/.well-known/gitmark/p.json", Write),
5969            ("/.well-known/gitmark/p.json".into(), Control)
5970        );
5971        assert_eq!(c("/.well-known/%74oken/x.json", Read).1, Control);
5972        assert_eq!(
5973            c("/.well-known/token/x.json.acl", Read),
5974            ("/.well-known/token/x.json".into(), Control)
5975        );
5976        assert_eq!(
5977            c("/.well-known/gitmark/p/blocktrails.json", Read),
5978            ("/.well-known/gitmark/p/blocktrails.json".into(), Read)
5979        );
5980        assert_eq!(
5981            c("/.well-known/webledgers/webledgers.json", Write),
5982            ("/.well-known/webledgers/webledgers.json".into(), Control)
5983        );
5984        assert_eq!(c("/.well-known/%57ebledgers/state.json", Read).1, Control);
5985        assert_eq!(c("/.well-known/webledgersx/y", Read).1, Read);
5986        assert_eq!(c("/pub/x", Read), ("/pub/x".into(), Read));
5987    }
5988
5989    /// Unit cover for the suffix-stripping helper.
5990    #[test]
5991    fn protected_resource_for_acl_strips_suffixes() {
5992        assert_eq!(
5993            protected_resource_for_acl("/victim/.acl").as_deref(),
5994            Some("/victim/")
5995        );
5996        assert_eq!(
5997            protected_resource_for_acl("/a/b.acl").as_deref(),
5998            Some("/a/b")
5999        );
6000        assert_eq!(protected_resource_for_acl("/.acl").as_deref(), Some("/"));
6001        assert_eq!(
6002            protected_resource_for_acl("/a/b.meta").as_deref(),
6003            Some("/a/b")
6004        );
6005        assert_eq!(protected_resource_for_acl("/a/b").as_deref(), None);
6006    }
6007}
6008
6009#[cfg(all(test, feature = "forge-mirror"))]
6010mod forge_env_tests {
6011    use super::*;
6012
6013    /// One test owns the `FORGE_MIRROR_*` variables, so there is no race.
6014    #[test]
6015    fn mirror_config_comes_from_the_environment() {
6016        let pk = "ab".repeat(32);
6017        std::env::remove_var("FORGE_MIRROR_RELAYS");
6018        std::env::remove_var("FORGE_MIRROR_FOLLOW");
6019        assert!(mirror_config().is_none(), "nothing configured: mirror off");
6020
6021        std::env::set_var(
6022            "FORGE_MIRROR_RELAYS",
6023            "ws://127.0.0.1:7777, wss://r.example , nope",
6024        );
6025        assert!(mirror_config().is_none(), "relays alone follow nothing");
6026
6027        std::env::set_var(
6028            "FORGE_MIRROR_FOLLOW",
6029            format!("{pk}/agent, bad/entry, {pk}/../x"),
6030        );
6031        std::env::set_var("FORGE_MIRROR_MIN_INTERVAL_MS", "1000");
6032        let cfg = mirror_config().expect("one relay and one valid entry");
6033        assert_eq!(cfg.relays, ["ws://127.0.0.1:7777", "wss://r.example"]);
6034        assert_eq!(cfg.follow.len(), 1);
6035        assert_eq!(cfg.follow[0].name, "agent");
6036        assert_eq!(cfg.min_interval_ms, 1000);
6037
6038        std::env::remove_var("FORGE_MIRROR_RELAYS");
6039        std::env::remove_var("FORGE_MIRROR_FOLLOW");
6040        std::env::remove_var("FORGE_MIRROR_MIN_INTERVAL_MS");
6041    }
6042
6043    #[test]
6044    fn the_forge_service_is_built_once_per_data_directory() {
6045        let td = tempfile::tempdir().unwrap();
6046        let a = forge_service(td.path().join(".forge")).unwrap();
6047        let b = forge_service(td.path().join(".forge")).unwrap();
6048        assert!(Arc::ptr_eq(&a, &b));
6049        let other = tempfile::tempdir().unwrap();
6050        let c = forge_service(other.path().join(".forge")).unwrap();
6051        assert!(!Arc::ptr_eq(&a, &c));
6052    }
6053}