Skip to main content

trust_tasks_https/
server.rs

1//! Axum-based server: receives Trust Task documents over HTTP, dispatches
2//! them to per-spec handlers, and returns a typed response document or a
3//! `trust-task-error` document with the appropriate HTTP status code.
4//!
5//! Single endpoint: `POST /trust-tasks` accepts any document the server has
6//! a handler registered for. Bearer auth (`Authorization: Bearer <token>`)
7//! is consulted before framework validation; the resulting VID becomes the
8//! transport-authenticated sender for §4.8.1 precedence.
9//!
10//! ## Request pipeline order
11//!
12//! The order below is load-bearing, not incidental. Every step that can
13//! cost the server work an unauthenticated sender chose — above all DID
14//! resolution inside a configured [`ProofVerifier`], which for `did:web`
15//! is an outbound HTTPS request to a host named in the request body —
16//! runs **after** the cheap, local rejections:
17//!
18//! 1. `Content-Type` must be `application/json` (binding spec §2), else 415.
19//! 2. Body parses as a Trust Task document.
20//! 3. Bearer token → transport-authenticated peer (local lookup).
21//! 4. **Route lookup** — an unregistered `type` is `unsupportedType` here,
22//!    before anything else touches the network.
23//! 5. `validate_basic` (expiry, recipient), the **freshness bound** over
24//!    `issuedAt` / `expiresAt` (§7.2 item 13) — see
25//!    [`HttpsServerBuilder::freshness`] — and `resolve_parties` (§4.8.1), in
26//!    `consume_inbound`'s order. With no authenticated peer, `resolve_parties`
27//!    runs first, so a misaddressed document is suppressed (§8.1).
28//! 6. **Attribution gate** — see [`HttpsServerBuilder::require_attribution`].
29//! 7. `proof.verificationMethod` DID-method pre-screen — see
30//!    [`HttpsServerBuilder::allowed_did_methods`]. With a verifier
31//!    configured and no explicit choice, only `did:key` passes.
32//! 8. Proof verification (the only step that may egress).
33//! 9. **Duplicate-execution claim** (§7.2 item 11) — see
34//!    [`HttpsServerBuilder::replay_protection`].
35//! 10. Per-spec policy + the registered handler.
36//!
37//! ## Where the replay claim sits, and why
38//!
39//! Step 9 is the `validated → accepted` transition: the last instant at
40//! which the server can still refuse a document for a reason that has nothing
41//! to do with having seen it before, and the first at which it has committed
42//! to execute. Claiming any earlier would write a record for documents the
43//! server then refuses — burning the `id` of every malformed, stale,
44//! unattributable or badly-signed arrival, so that a corrected resend came
45//! back `idConflict` forever and a stranger could pre-burn an `id` it had
46//! merely observed. Claiming any later is not a claim at all: the effect
47//! would already have happened.
48//!
49//! The one check that runs *after* the claim is the per-spec policy inside
50//! the dispatch closure (`enforce_spec_policy`), which needs the typed
51//! payload the closure alone can produce. A refusal there releases the claim
52//! (see [`ReplayGuard::release`]), so nothing is burned by it either.
53
54use std::collections::{BTreeSet, HashMap};
55use std::sync::atomic::{AtomicBool, Ordering};
56use std::sync::{Arc, OnceLock};
57use std::time::Duration;
58
59use axum::body::Bytes;
60use axum::error_handling::HandleErrorLayer;
61use axum::extract::{DefaultBodyLimit, State};
62use axum::http::{header, HeaderMap, StatusCode};
63use axum::response::{IntoResponse, Response};
64use axum::routing::post;
65use axum::Router;
66use serde::Serialize;
67use serde_json::Value;
68use tower::limit::ConcurrencyLimitLayer;
69use tower::timeout::TimeoutLayer;
70use tower::ServiceBuilder;
71use trust_tasks_rs::{
72    discovery::DiscoveryRegistry, erase_verifier, received_document_digest,
73    specs::trust_task_discovery::v0_4 as discovery, DocumentDigest, DynProofVerifier, ErrorPayload,
74    ErrorResponse, FreshnessPolicy, InMemoryReplayGuard, Payload, ProofVerifier, RejectReason,
75    ReplayGuard, ReplayVerdict, RequestPayload, ResolvedParties, StaleReason, StandardCode,
76    TransportHandler, TrustTask, PROOF_NOT_ACCEPTED_BY_POLICY,
77};
78use uuid::Uuid;
79
80use crate::auth::{Auth, BearerAuth};
81
82// --- trust-task-discovery 0.1 / 0.2 / 0.3 (superseded) ----------------------
83// 0.1 and 0.2 are superseded by 0.3 and served until they are withdrawn; the
84// withdrawal batch deletes `server/superseded_discovery.rs` and every block
85// marked like this one.
86mod superseded_discovery;
87// --- end trust-task-discovery 0.1 / 0.2 / 0.3 (superseded) ------------------
88use crate::handler::HttpsHandler;
89use crate::status::status_for_code;
90
91/// Maximum accepted request-body size (SPEC §12.2), applied by
92/// [`HttpsServer::into_router`]. Trust Task payloads are small; 256 KiB is
93/// generous headroom while bounding pre-auth memory use. Callers needing a
94/// different bound can rebuild the router with their own
95/// [`DefaultBodyLimit`] layer — which is why the value is public: a caller
96/// replacing the layer wants to know what it is replacing.
97pub const MAX_BODY_BYTES: usize = 256 * 1024;
98
99/// Default per-request wall-clock budget applied by [`HttpsServer::into_router`].
100/// A Trust Task exchange is one small JSON round trip; a request still in
101/// flight after this is wedged, and holding the connection open is exactly
102/// what a slowloris wants. Override with
103/// [`HttpsServerBuilder::request_timeout`].
104pub const DEFAULT_REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
105
106/// Default ceiling on concurrently-executing requests, applied by
107/// [`HttpsServer::into_router`]. Bounds the memory a flood of slow senders
108/// can pin. Override with [`HttpsServerBuilder::max_concurrent_requests`].
109pub const DEFAULT_MAX_CONCURRENT_REQUESTS: usize = 512;
110
111/// Context handed to every spec handler — the transport-authenticated
112/// peer (when present), convenience accessors for the inbound
113/// document's metadata, and the SPEC §4.8.1-resolved party identities.
114#[derive(Debug, Clone)]
115pub struct RequestContext {
116    /// VID of the transport-authenticated sender, if any. Equivalent to
117    /// `resolved.issuer` when the in-band `issuer` is absent and the
118    /// transport authenticated a peer; preserved separately so handlers
119    /// can audit-log the distinction between in-band and derived.
120    pub authenticated_sender: Option<String>,
121    /// VID of the local party serving this request.
122    pub local: Option<String>,
123    /// SPEC §4.8.1-resolved party identities (in-band wins over
124    /// transport-derived; transport fills in absent in-band values).
125    /// Handlers can use this directly instead of re-running
126    /// [`TransportHandler::resolve_parties`].
127    pub resolved: ResolvedParties,
128}
129
130/// A spec-specific handler stored type-erased in the dispatch table.
131///
132/// Inputs: the parsed (but untyped) inbound document and the request
133/// context. Output: the JSON body of a success response (a fully-formed
134/// `#response` document); `None` where the specification defines no success
135/// response and the handler acknowledged instead; or a [`RejectReason`] the
136/// server converts into a `trust-task-error` response via §8.1 routing.
137///
138/// `Option` rather than an empty `Value`: SPEC §4.4.1 distinguishes "a
139/// `#response` document whose payload happens to be empty" from "this
140/// specification defines no response at all", and the two earn different
141/// statuses (200 with a body, 204 without). Collapsing them would make a
142/// fire-and-forget acknowledgement indistinguishable on the wire from a
143/// `#response` carrying `{}`.
144type DispatchFn = Box<
145    dyn Fn(TrustTask<Value>, &RequestContext) -> Result<Option<Value>, RejectReason> + Send + Sync,
146>;
147
148struct Route {
149    dispatch: DispatchFn,
150}
151
152/// Internal state shared by every axum request handler.
153struct ServerState {
154    local_vid: Option<String>,
155    auth: Box<dyn Auth>,
156    routes: HashMap<String, Route>,
157    verifier: Option<Arc<dyn DynProofVerifier>>,
158    require_attribution: bool,
159    allowed_did_methods: Option<BTreeSet<String>>,
160    /// `None` only when the deployment called
161    /// `replay_protection(false)` — see that method's warning.
162    replay_guard: Option<Arc<dyn ReplayGuard>>,
163    freshness: FreshnessPolicy,
164}
165
166/// Which DID methods `proof.verificationMethod` may name, as configured.
167enum DidMethodPolicy {
168    /// No explicit choice: `did:key` only when a verifier is configured
169    /// (see [`DEFAULT_ALLOWED_DID_METHODS`]); nothing to screen without one.
170    Default,
171    /// [`HttpsServerBuilder::allowed_did_methods`].
172    Only(BTreeSet<String>),
173    /// [`HttpsServerBuilder::allow_any_did_method`].
174    Any,
175}
176
177/// The DID methods a server with a verifier accepts in
178/// `proof.verificationMethod` when neither
179/// [`HttpsServerBuilder::allowed_did_methods`] nor
180/// [`HttpsServerBuilder::allow_any_did_method`] was called: `did:key`, whose
181/// key is in the identifier, so verifying it never leaves the process.
182pub const DEFAULT_ALLOWED_DID_METHODS: &[&str] = &["key"];
183
184/// Builder for [`HttpsServer`].
185pub struct HttpsServerBuilder {
186    local_vid: Option<String>,
187    auth: Option<Box<dyn Auth>>,
188    routes: HashMap<String, Route>,
189    verifier: Option<Arc<dyn DynProofVerifier>>,
190    require_attribution: bool,
191    did_methods: DidMethodPolicy,
192    replay_protection: bool,
193    replay_guard: Option<Arc<dyn ReplayGuard>>,
194    freshness: FreshnessPolicy,
195    /// Shared with the discovery handler closure so `.public_discovery()`
196    /// can be called either side of `.enable_discovery()`.
197    public_discovery: Arc<AtomicBool>,
198    /// The freshness policy the built server applies, filled in by
199    /// [`Self::build`] and read by the discovery handler
200    /// [`Self::enable_discovery`] installs, so the acceptance window it
201    /// advertises is the one enforced however the builder calls are ordered.
202    applied_freshness: Arc<OnceLock<FreshnessPolicy>>,
203    request_timeout: Option<Duration>,
204    max_concurrent_requests: Option<usize>,
205}
206
207impl HttpsServerBuilder {
208    /// Set the local party's VID. Becomes `local` on the per-request
209    /// [`HttpsHandler`] and is what `recipient`-bearing documents are
210    /// cross-checked against under SPEC.md §7.2 item 5.
211    pub fn local_vid(mut self, vid: impl Into<String>) -> Self {
212        self.local_vid = Some(vid.into());
213        self
214    }
215
216    /// Plug in an [`Auth`] implementation. Defaults to a [`BearerAuth`]
217    /// with no tokens — every request is treated as unauthenticated and
218    /// the framework falls back entirely to in-band identity.
219    pub fn with_auth(mut self, auth: impl Auth) -> Self {
220        self.auth = Some(Box::new(auth));
221        self
222    }
223
224    /// Plug in an in-band [`ProofVerifier`]. When configured, the
225    /// server verifies the `proof` member of every proof-bearing
226    /// document and rejects with `proofInvalid` on failure; when
227    /// absent, the server rejects proof-bearing documents with
228    /// `malformedRequest` (the
229    /// [`PROOF_NOT_ACCEPTED_BY_POLICY`](trust_tasks_rs::PROOF_NOT_ACCEPTED_BY_POLICY)
230    /// rule — matches `consume_inbound` under
231    /// [`ProofPolicy::RejectIfPresent`](trust_tasks_rs::ProofPolicy::RejectIfPresent)).
232    ///
233    /// The verifier is invoked between identity resolution (§7.2 item
234    /// 6) and the per-spec dispatch closure (`IS_PROOF_REQUIRED` check
235    /// and audience binding), so a failed signature short-circuits
236    /// before the user handler runs. It is deliberately the **last**
237    /// step before dispatch: it is the only one that may egress, so
238    /// route lookup, transport auth and the attribution gate all run
239    /// ahead of it. See [`Self::allowed_did_methods`] for the pre-screen
240    /// that bounds where that egress can go.
241    ///
242    /// Accepts any concrete [`ProofVerifier`] (e.g. from
243    /// `trust-tasks-proof`'s `affinidi` backend); the server stores it
244    /// behind [`trust_tasks_rs::DynProofVerifier`] for object-safe
245    /// dispatch.
246    pub fn with_verifier<V>(mut self, verifier: V) -> Self
247    where
248        V: ProofVerifier + Send + Sync + 'static,
249    {
250        self.verifier = Some(erase_verifier(verifier));
251        self
252    }
253
254    /// Register a handler for the request payload type `P`. The handler
255    /// receives the typed request and a [`RequestContext`]; it returns
256    /// either the response payload (which the server wraps in a
257    /// `#response`-variant document via [`TrustTask::respond_with`]) or a
258    /// [`RejectReason`] (which the server wraps in a `trust-task-error`
259    /// document via [`TransportHandler::reject`], applying SPEC §8.1
260    /// routing).
261    pub fn on<P, F>(mut self, handler: F) -> Self
262    where
263        P: RequestPayload + 'static,
264        P::Response: Serialize + 'static,
265        F: Fn(&TrustTask<P>, &RequestContext) -> Result<P::Response, RejectReason>
266            + Send
267            + Sync
268            + 'static,
269    {
270        let dispatch: DispatchFn = Box::new(move |doc: TrustTask<Value>, ctx: &RequestContext| {
271            // Downcast payload to P.
272            let typed = downcast::<P>(doc)?;
273
274            // SPEC §7.2 items 5b + 7A + 8 — the flag-driven per-spec checks
275            // (recipient-REQUIRED, proof-REQUIRED, audience binding). This is
276            // the first point where the typed payload (and its codegen-emitted
277            // flags) is available. It calls the SAME method as the library
278            // `consume_inbound` path (`TrustTask::enforce_spec_policy`) so the
279            // two pipelines cannot diverge on the check set. The non-typed
280            // checks (expiry, cross-check, proof verification) ran upstream in
281            // `dispatch_handler`.
282            typed.enforce_spec_policy()?;
283
284            // Invoke user handler.
285            let response_payload = handler(&typed, ctx)?;
286            let new_id = format!("urn:uuid:{}", Uuid::new_v4());
287            let response_doc = typed.respond_with(new_id, response_payload);
288            Ok(Some(
289                serde_json::to_value(&response_doc).expect("response serialises (typed structs)"),
290            ))
291        });
292
293        let key = P::type_uri().for_routing().to_string();
294        self.routes.insert(key, Route { dispatch });
295        self
296    }
297
298    /// Register a handler for a **fire-and-forget** specification — one that
299    /// defines no success response.
300    ///
301    /// SPEC §4.4.1: such a specification's consumer signals success by the
302    /// absence of a `trust-task-error`, and **MUST NOT** emit a
303    /// `#response`-variant document. There is therefore no response payload
304    /// for the handler to return, and [`Self::on`] cannot be used — those
305    /// specifications get no [`RequestPayload`] impl precisely so that the
306    /// mistake is a compile error rather than a runtime surprise.
307    ///
308    /// The handler returns `Ok(())` to acknowledge or a [`RejectReason`] to
309    /// refuse; an acknowledgement is answered `204 No Content`, matching the
310    /// status the binding already uses for a duplicate of a completed
311    /// fire-and-forget execution ([§5.1](https://trusttasks.org/binding/https/0.2)).
312    pub fn on_ack<P, F>(mut self, handler: F) -> Self
313    where
314        P: Payload + 'static,
315        F: Fn(&TrustTask<P>, &RequestContext) -> Result<(), RejectReason> + Send + Sync + 'static,
316    {
317        let dispatch: DispatchFn = Box::new(move |doc: TrustTask<Value>, ctx: &RequestContext| {
318            let typed = downcast::<P>(doc)?;
319            // Same §7.2 items 5b/7A/8 gate as `on`; a fire-and-forget task is
320            // no less consequential for having nothing to say back.
321            typed.enforce_spec_policy()?;
322            handler(&typed, ctx)?;
323            Ok(None)
324        });
325
326        let key = P::type_uri().for_routing().to_string();
327        self.routes.insert(key, Route { dispatch });
328        self
329    }
330
331    /// Reject any document that arrives with **neither** a transport-
332    /// authenticated peer **nor** a `proof`. Defaults to `true`.
333    ///
334    /// # What this closes
335    ///
336    /// Without it, an unauthenticated `POST` carrying
337    /// `"issuer": "did:web:victim.example"` and no `proof` reaches the
338    /// registered handler with [`RequestContext::resolved`]`.issuer` set
339    /// to the attacker's string: with no transport peer the framework
340    /// falls back entirely to the document's in-band `issuer`, and the
341    /// per-spec `IS_PROOF_REQUIRED` check only fires for specs whose front
342    /// matter declares `proof` REQUIRED — which most do not, mutating ones
343    /// included. The result is an unauthenticated, unattributable request
344    /// that a handler cannot tell apart from a genuine one.
345    ///
346    /// The binding spec states plainly that "this binding does not permit
347    /// `proof` to be omitted" (`bindings/https/0.2` §5). This flag is that
348    /// rule's runtime representation. It is deliberately blanket — applied
349    /// to every registered spec, with no attempt to infer which ones are
350    /// consequential, because a per-spec derivation is one mis-classified
351    /// spec away from the same hole.
352    ///
353    /// # Turning it off
354    ///
355    /// `require_attribution(false)` restores the pre-0.11 behaviour, in
356    /// which **any** party that can reach the socket can assert **any**
357    /// `issuer` and have handlers act on it. Every authorization decision a
358    /// handler makes from `ctx.resolved.issuer` becomes attacker-controlled,
359    /// and nothing downstream can recover the distinction. Use it only for
360    /// local development and for tests that deliberately exercise the
361    /// unauthenticated path — never for a deployment reachable by anything
362    /// you do not already trust.
363    pub fn require_attribution(mut self, require: bool) -> Self {
364        self.require_attribution = require;
365        self
366    }
367
368    /// Keep the SPEC §7.2 item 11 duplicate-execution record. Defaults to
369    /// `true`.
370    ///
371    /// # What it does
372    ///
373    /// Item 11 is normative and unconditional for a *consequential Trust
374    /// Task*: a document already accepted under an `id` **MUST NOT** cause the
375    /// effect a second time, and a *different* document under the same `id`
376    /// **MUST** be rejected with `idConflict`. This binding provides no
377    /// transport freshness of its own — `bindings/https/0.2` §5 — so the
378    /// record kept here is the only thing between a captured request body and
379    /// a repeated effect, and between an ordinary proxy or client retry and a
380    /// second ACL grant.
381    ///
382    /// With no [`Self::with_replay_guard`] the server builds an
383    /// [`InMemoryReplayGuard`] with its default capacity. That is correct for
384    /// a single-process consumer and **not** correct behind a load balancer:
385    /// two replicas each hold their own map, so a document accepted by one is
386    /// `Fresh` at the other and the effect happens twice. A replicated
387    /// deployment **MUST** supply a shared-store guard.
388    ///
389    /// # Turning it off
390    ///
391    /// `replay_protection(false)` restores the pre-0.13 behaviour, in which
392    /// this server keeps **no** record of what it has executed. Every
393    /// consequential handler registered on it becomes replayable by anyone who
394    /// can re-send a request body — including any TLS-terminating intermediary
395    /// this binding cannot characterise (§5, *Re-origination*) — and a
396    /// duplicate delivery from an ordinary retry is executed a second time
397    /// with no signal that it was a duplicate. Nothing downstream can recover
398    /// the distinction, because nothing downstream is told. Use it only where
399    /// every registered specification "explicitly declares repeated execution
400    /// safe and intended" (the narrow disapplication item 11 allows), or for
401    /// local development.
402    pub fn replay_protection(mut self, keep_record: bool) -> Self {
403        self.replay_protection = keep_record;
404        self
405    }
406
407    /// Supply the [`ReplayGuard`] backing [`Self::replay_protection`],
408    /// replacing the default [`InMemoryReplayGuard`].
409    ///
410    /// Use this for any deployment that is replicated, or that must survive a
411    /// process restart with its record intact: back the trait with Redis,
412    /// Postgres, DynamoDB, or whatever store every replica shares. The
413    /// implementation **MUST** make claim-and-record atomic across concurrent
414    /// calls — see [`ReplayGuard::claim`].
415    ///
416    /// Calling this does not by itself enable the record; it is enabled by
417    /// default and disabled only by `replay_protection(false)`, which
418    /// suppresses this guard too.
419    pub fn with_replay_guard<G>(mut self, guard: G) -> Self
420    where
421        G: ReplayGuard + 'static,
422    {
423        self.replay_guard = Some(Arc::new(guard));
424        self
425    }
426
427    /// The freshness bound applied to `issuedAt` / `expiresAt` (SPEC §7.2).
428    /// Defaults to [`FreshnessPolicy::consequential`].
429    ///
430    /// The default is the posture §7.2 (*Bounding the record*) describes:
431    /// `issuedAt` REQUIRED and a [`DEFAULT_MAX_AGE`](trust_tasks_rs::DEFAULT_MAX_AGE)
432    /// acceptance window. It is not a separate feature from
433    /// [`Self::replay_protection`] but the other half of it —
434    /// [`FreshnessPolicy::record_expiry`] is what tells the guard how long to
435    /// retain each record, and SPEC makes the acceptance window and that
436    /// retention *the same bound*. There is deliberately no second TTL to
437    /// configure.
438    ///
439    /// Widen `max_age` for a deployment whose intermediaries may hold a
440    /// request longer than five minutes — and understand that doing so widens
441    /// the replay record in lockstep, because it is one bound.
442    ///
443    /// A policy with no `max_age` cannot place a document that carries no
444    /// `expiresAt` in any window; while the record is being kept, such a
445    /// document is refused with `expired` rather than executed on, per §7.2's
446    /// "**MUST NOT** execute a *consequential Trust Task* on it".
447    pub fn freshness(mut self, policy: FreshnessPolicy) -> Self {
448        self.freshness = policy;
449        self
450    }
451
452    /// Restrict which DID methods may appear in `proof.verificationMethod`.
453    ///
454    /// The check runs **before** the configured [`ProofVerifier`] is called.
455    /// Verifying a proof means resolving its verification method, and for
456    /// `did:web` that resolution is an outbound HTTPS request to a host the
457    /// *sender* chose — so an unscreened verifier turns this endpoint into
458    /// an SSRF and traffic-amplification primitive for anyone who can reach
459    /// it. Pinning the accepted methods (`["key"]`, `["web", "webvh"]`, …)
460    /// bounds where that egress can go.
461    ///
462    /// **Default:** with a verifier configured and neither this nor
463    /// [`Self::allow_any_did_method`] called, only
464    /// [`DEFAULT_ALLOWED_DID_METHODS`] (`did:key`) passes — a method that
465    /// resolves over the network is opt-in, never implied by plugging in a
466    /// resolving verifier. A server with no verifier screens nothing by
467    /// default: it refuses proof-bearing documents outright and never
468    /// egresses. A `verificationMethod` that is not a DID URL at all is
469    /// rejected whenever a restriction applies.
470    ///
471    /// This is a coarse pre-screen at the binding boundary. Depth — resolved
472    /// host allow-listing, redirect policy, per-resolution timeouts and
473    /// caching — belongs in the resolver behind the verifier, not here.
474    pub fn allowed_did_methods<I, S>(mut self, methods: I) -> Self
475    where
476        I: IntoIterator<Item = S>,
477        S: Into<String>,
478    {
479        self.did_methods = DidMethodPolicy::Only(methods.into_iter().map(Into::into).collect());
480        self
481    }
482
483    /// Accept a `proof.verificationMethod` of any DID method, lifting the
484    /// `did:key`-only default described on [`Self::allowed_did_methods`].
485    ///
486    /// Only for a verifier that never resolves over the network, or whose
487    /// resolver bounds where it goes (a host allow-list, private addresses
488    /// refused, a deadline per resolution) — otherwise any caller can make
489    /// this server fetch from a host it names.
490    pub fn allow_any_did_method(mut self) -> Self {
491        self.did_methods = DidMethodPolicy::Any;
492        self
493    }
494
495    /// Serve `trust-task-discovery` to unauthenticated callers.
496    ///
497    /// By default the discovery handler installed by [`Self::with_discovery`]
498    /// / [`Self::enable_discovery`] requires a transport-authenticated
499    /// sender and answers everyone else with `permissionDenied`: a discovery
500    /// response enumerates the full route table, and SPEC §12 says a
501    /// responder **SHOULD** authenticate the discoverer before answering.
502    ///
503    /// Call this when the supported-task set is genuinely public. Order does
504    /// not matter — it applies to a discovery handler registered either side
505    /// of this call.
506    pub fn public_discovery(self) -> Self {
507        self.public_discovery.store(true, Ordering::Relaxed);
508        self
509    }
510
511    /// Per-request wall-clock budget applied by [`HttpsServer::into_router`].
512    /// Defaults to [`DEFAULT_REQUEST_TIMEOUT`].
513    pub fn request_timeout(mut self, timeout: Duration) -> Self {
514        self.request_timeout = Some(timeout);
515        self
516    }
517
518    /// Ceiling on concurrently-executing requests, applied by
519    /// [`HttpsServer::into_router`]. Defaults to
520    /// [`DEFAULT_MAX_CONCURRENT_REQUESTS`].
521    pub fn max_concurrent_requests(mut self, limit: usize) -> Self {
522        self.max_concurrent_requests = Some(limit);
523        self
524    }
525
526    /// Register `trust-task-discovery` handlers that respond with the contents
527    /// of `registry`, each version in the version it was asked: 0.3, the
528    /// current version, and the superseded 0.2 and 0.1 until they are
529    /// withdrawn. 0.2 and 0.3 write `frameworkVersion` three-part (SPEC
530    /// §5.1.1), 0.1 `MAJOR.MINOR`; only 0.3 can carry the registry's
531    /// acceptance window ([`DiscoveryRegistry::acceptance_window_from`]).
532    /// Combine with [`Self::on`] in any order; the registry is consulted
533    /// afresh on every inbound query.
534    ///
535    /// Unless [`Self::public_discovery`] is set, the handler answers a
536    /// caller with no transport-authenticated sender with `permissionDenied`
537    /// rather than enumerating the route table (SPEC §12, discovery
538    /// privacy).
539    ///
540    /// Use this when the server's discoverable set differs from its
541    /// actually-handled set — for example, when the server delegates
542    /// some types downstream but wants to advertise them as supported.
543    /// For the common "advertise exactly what I handle" case, see
544    /// [`Self::enable_discovery`].
545    pub fn with_discovery(self, registry: DiscoveryRegistry) -> Self {
546        self.install_discovery(registry, false)
547    }
548
549    /// Snapshot every Type URI currently registered via [`Self::on`] and
550    /// install `trust-task-discovery` handlers that advertise them (and
551    /// discovery itself), as [`Self::with_discovery`] does. Call this
552    /// **after** every other `.on(...)`; URIs registered afterward will not
553    /// be included.
554    ///
555    /// A 0.4 response also advertises the acceptance window this server
556    /// enforces — its [`Self::freshness`] policy, whenever that is set — so a
557    /// producer holding a document can tell whether it will still be
558    /// accepted. A policy with no `max_age` has no window to state, and none
559    /// is advertised.
560    ///
561    /// ```rust,ignore
562    /// let server = HttpsServer::builder()
563    ///     .local_vid("did:web:server.example")
564    ///     .with_auth(BearerAuth::from_pairs([("alice", "did:web:alice.example")]))
565    ///     .on::<grant::Payload, _>(handle_grant)
566    ///     .on::<revoke::Payload, _>(handle_revoke)
567    ///     .enable_discovery() // ← advertises grant + revoke
568    ///     .build();
569    /// ```
570    pub fn enable_discovery(self) -> Self {
571        let mut registry: DiscoveryRegistry = self.routes.keys().cloned().collect();
572        // Always advertise discovery itself — otherwise a discoverer who
573        // somehow guessed they could ask wouldn't see their own protocol
574        // listed back.
575        registry.register_payload::<discovery::Payload>();
576        // --- trust-task-discovery 0.1 / 0.2 / 0.3 (superseded) ----------------------
577        superseded_discovery::register(&mut registry);
578        // --- end trust-task-discovery 0.1 / 0.2 / 0.3 (superseded) ------------------
579        self.install_discovery(registry, true)
580    }
581
582    /// Install the discovery handlers. With `advertise_freshness`, a 0.4
583    /// (or 0.3) response states the window of the freshness policy the built server
584    /// applies.
585    fn install_discovery(self, registry: DiscoveryRegistry, advertise_freshness: bool) -> Self {
586        let public = Arc::clone(&self.public_discovery);
587        let applied_freshness = Arc::clone(&self.applied_freshness);
588        let this = self;
589        // --- trust-task-discovery 0.1 / 0.2 / 0.3 (superseded) ----------------------
590        let this = this.with_superseded_discovery(registry.clone(), advertise_freshness);
591        // --- end trust-task-discovery 0.1 / 0.2 / 0.3 (superseded) ------------------
592        this.on::<discovery::Payload, _>(move |req, ctx| {
593            refuse_unauthenticated_discovery(&public, ctx.authenticated_sender.is_none())?;
594            Ok(match applied_freshness.get() {
595                Some(policy) if advertise_freshness => registry
596                    .clone()
597                    .acceptance_window_from(policy)
598                    .respond_to_v0_4(&req.payload),
599                _ => registry.respond_to_v0_4(&req.payload),
600            })
601        })
602    }
603
604    /// Build the server. Run it with [`HttpsServer::serve`].
605    ///
606    /// Note the default [`Auth`] is a [`BearerAuth`] with an empty token
607    /// table, so every request is unauthenticated unless
608    /// [`Self::with_auth`] was called. That is survivable only because
609    /// [`Self::require_attribution`] defaults to `true`; read its
610    /// documentation before turning it off.
611    pub fn build(self) -> HttpsServer {
612        let auth = self.auth.unwrap_or_else(|| Box::new(BearerAuth::new()));
613        // A builder is built once, so this is the first and only `set`; the
614        // discovery handler reads the policy the server actually applies.
615        let _ = self.applied_freshness.set(self.freshness);
616        let allowed_did_methods = match self.did_methods {
617            DidMethodPolicy::Only(methods) => Some(methods),
618            DidMethodPolicy::Any => None,
619            DidMethodPolicy::Default => self.verifier.is_some().then(|| {
620                DEFAULT_ALLOWED_DID_METHODS
621                    .iter()
622                    .map(|m| (*m).to_string())
623                    .collect()
624            }),
625        };
626        HttpsServer {
627            state: Arc::new(ServerState {
628                local_vid: self.local_vid,
629                auth,
630                routes: self.routes,
631                verifier: self.verifier,
632                require_attribution: self.require_attribution,
633                allowed_did_methods,
634                // Secure by default: the record is kept unless the deployment
635                // said otherwise, and the default guard is the in-process one.
636                replay_guard: self.replay_protection.then(|| {
637                    self.replay_guard
638                        .unwrap_or_else(|| Arc::new(InMemoryReplayGuard::default()))
639                }),
640                freshness: self.freshness,
641            }),
642            request_timeout: self.request_timeout.unwrap_or(DEFAULT_REQUEST_TIMEOUT),
643            max_concurrent_requests: self
644                .max_concurrent_requests
645                .unwrap_or(DEFAULT_MAX_CONCURRENT_REQUESTS),
646        }
647    }
648}
649
650/// An HTTPS Trust Tasks server.
651///
652/// Build with [`HttpsServer::builder`], register handlers via
653/// [`HttpsServerBuilder::on`], then [`Self::serve`].
654pub struct HttpsServer {
655    state: Arc<ServerState>,
656    request_timeout: Duration,
657    max_concurrent_requests: usize,
658}
659
660impl HttpsServer {
661    /// Start a new builder.
662    pub fn builder() -> HttpsServerBuilder {
663        HttpsServerBuilder {
664            local_vid: None,
665            auth: None,
666            routes: HashMap::new(),
667            verifier: None,
668            // Secure by default: see `HttpsServerBuilder::require_attribution`.
669            require_attribution: true,
670            did_methods: DidMethodPolicy::Default,
671            // Secure by default: see `HttpsServerBuilder::replay_protection`.
672            replay_protection: true,
673            replay_guard: None,
674            freshness: FreshnessPolicy::consequential(),
675            public_discovery: Arc::new(AtomicBool::new(false)),
676            applied_freshness: Arc::new(OnceLock::new()),
677            request_timeout: None,
678            max_concurrent_requests: None,
679        }
680    }
681
682    /// Build the axum [`Router`] without starting a listener — useful for
683    /// integration tests that want to spawn the app inline.
684    ///
685    /// The router applies an explicit [`DefaultBodyLimit`] of
686    /// [`MAX_BODY_BYTES`] (256 KiB) as an audited DoS control (SPEC §12.2): the body is
687    /// buffered and parsed *before* authentication, so an unbounded body would
688    /// otherwise be a pre-auth memory-exhaustion vector. JSON nesting depth is
689    /// separately bounded by `serde_json`'s default 128-level recursion limit,
690    /// so a pathologically nested body within the size budget fails to parse
691    /// (→ `malformedRequest`) rather than overflowing the stack.
692    ///
693    /// It also applies two liveness controls, both configurable on the
694    /// builder ([`HttpsServerBuilder::request_timeout`],
695    /// [`HttpsServerBuilder::max_concurrent_requests`]):
696    ///
697    /// * a [`TimeoutLayer`] — a request that outlives its budget is
698    ///   abandoned with `408 Request Timeout` rather than holding a
699    ///   connection and a task open indefinitely (slowloris);
700    /// * a [`ConcurrencyLimitLayer`] — requests past the ceiling wait for a
701    ///   permit instead of each pinning a parse buffer, bounding the memory
702    ///   a flood can commit.
703    ///
704    /// Both sit **outside** the body limit, so they also bound the time and
705    /// concurrency spent reading a body that is still under the size cap.
706    pub fn into_router(self) -> Router {
707        let timeout = self.request_timeout;
708        let concurrency = self.max_concurrent_requests;
709        Router::new()
710            .route("/trust-tasks", post(dispatch_handler))
711            .layer(DefaultBodyLimit::max(MAX_BODY_BYTES))
712            .layer(
713                ServiceBuilder::new()
714                    // Outermost: the inner layers are fallible, axum's
715                    // `Router` is not. Anything that is not a timeout is a
716                    // middleware fault, not a client error, so it is a 500.
717                    .layer(HandleErrorLayer::new(|err: tower::BoxError| async move {
718                        if err.is::<tower::timeout::error::Elapsed>() {
719                            StatusCode::REQUEST_TIMEOUT
720                        } else {
721                            StatusCode::INTERNAL_SERVER_ERROR
722                        }
723                    }))
724                    .layer(ConcurrencyLimitLayer::new(concurrency))
725                    .layer(TimeoutLayer::new(timeout)),
726            )
727            .with_state(self.state)
728    }
729
730    /// Bind to `addr` and serve incoming requests. Returns when the
731    /// listener stops.
732    ///
733    /// The router returned by [`Self::into_router`] carries the body-size,
734    /// timeout and concurrency controls; this method adds nothing beyond
735    /// binding the listener, so a caller that builds its own listener gets
736    /// the same protections.
737    pub async fn serve(self, addr: impl tokio::net::ToSocketAddrs) -> std::io::Result<()> {
738        let listener = tokio::net::TcpListener::bind(addr).await?;
739        axum::serve(listener, self.into_router()).await
740    }
741}
742
743async fn dispatch_handler(
744    State(state): State<Arc<ServerState>>,
745    headers: HeaderMap,
746    body: Bytes,
747) -> Response {
748    // ─── 0. Content-Type. The binding spec (§2) makes
749    // `Content-Type: application/json` a MUST on the request. Enforcing it
750    // is not pedantry: `text/plain` is one of the three media types a
751    // cross-origin `fetch`/form POST can send *without* a preflight, so
752    // accepting it lets any web page in the victim's browser drive this
753    // endpoint. Requiring JSON forces the preflight, and the browser then
754    // refuses on our behalf. 415 is a transport-level answer, not a
755    // framework error document — nothing here has been parsed yet.
756    if !is_json_content_type(&headers) {
757        return StatusCode::UNSUPPORTED_MEDIA_TYPE.into_response();
758    }
759
760    // ─── 1. Parse the body into a TrustTask<Value>.
761    let doc: TrustTask<Value> = match serde_json::from_slice(&body) {
762        Ok(d) => d,
763        // `RejectReason::malformed_from_serde` rather than `format!("{e}")`:
764        // `serde_json`'s `Display` renders the member path and the byte offset
765        // it failed at ("missing field `subject` at line 1 column 214"), which
766        // on the wire describes this consumer's internal type layout and its
767        // framing of the body to anyone willing to POST malformed JSON — the
768        // §10.4 leak. The category is what a producer can act on; the detail
769        // belongs in the operator's log.
770        Err(e) => {
771            return reject_response(None, None, RejectReason::malformed_from_serde(&e));
772        }
773    };
774    // The same bytes as a plain `Value`, for step 8: a proof is verified over
775    // the document as received, not over `doc` re-serialised, which re-renders
776    // the framework timestamps. Parsed separately rather than `doc` being built
777    // from it, because the typed parse is the one that refuses a duplicated
778    // top-level member, which a `Value` silently resolves to the last.
779    let received: Value = match serde_json::from_slice(&body) {
780        Ok(v) => v,
781        Err(e) => {
782            return reject_response(None, None, RejectReason::malformed_from_serde(&e));
783        }
784    };
785
786    // ─── 2. Authenticate the bearer token (if any) into a peer VID. Purely
787    // local — an in-process map, a JWT signature check, a database lookup.
788    // No network egress the sender can steer.
789    let peer_vid = extract_bearer(&headers).and_then(|tok| state.auth.resolve(tok));
790
791    // ─── 3. Build the per-request HttpsHandler.
792    let handler = HttpsHandler::new(state.local_vid.clone(), peer_vid);
793
794    // ─── 4. Routing FIRST — deliberately ahead of every step that can cost
795    // this server work an unauthenticated sender chose. Proof verification
796    // (step 8) resolves the `verificationMethod` DID, which for `did:web` is
797    // an outbound HTTPS request to a host named in the request body. With
798    // routing last, a stranger could aim this endpoint at an arbitrary host
799    // by POSTing a document whose `type` we do not even implement, and get
800    // an amplifier for free. There is no rate limit here; the ordering is
801    // the control.
802    let routing_key = doc.type_uri.for_routing().to_string();
803    let Some(route) = state.routes.get(&routing_key) else {
804        return reject_response(
805            Some(&handler),
806            Some(&doc),
807            RejectReason::UnsupportedType {
808                type_uri: routing_key,
809            },
810        );
811    };
812
813    // ─── 5. The framework-level checks, in §7.2 order and so in
814    // `consume_inbound`'s: expiry + recipient (items 4 and 5a), freshness
815    // (item 4), then identity resolution (item 6). A document that fails two
816    // of them is refused for the same reason by every consumer.
817    //
818    // Except with no authenticated sender. Then the only identity that can
819    // disagree is the recipient, and §8.1 suppresses that refusal: there is
820    // nobody to address it to, and a `wrongRecipient` answer would tell an
821    // unauthenticated prober which VIDs this server is not. So identity runs
822    // first, and a misaddressed document stays indistinguishable from one that
823    // did not parse.
824    let mut resolved = None;
825    if handler.peer().is_none() {
826        match handler.resolve_parties(&doc) {
827            Ok(r) => resolved = Some(r),
828            Err(consistency) => {
829                return reject_response(Some(&handler), Some(&doc), consistency.into());
830            }
831        }
832    }
833    let now = chrono::Utc::now();
834    let my_vid = state.local_vid.as_deref().unwrap_or("");
835    if let Err(reason) = doc.validate_basic(now, my_vid) {
836        return reject_response(Some(&handler), Some(&doc), reason);
837    }
838
839    // ─── 5b. Freshness (§7.2 item 13). `validate_basic` honours `expiresAt`,
840    // which is optional and which a producer sets for its own reasons; on its
841    // own it leaves a document stamped years ago — or years hence — acceptable
842    // forever. This is also the bound the replay record at step 9 is retained
843    // for: §7.2 (*Bounding the record*) makes the acceptance window and the
844    // record's retention one bound, not two.
845    if let Err(reason) = doc.validate_freshness(now, &state.freshness) {
846        return reject_response(Some(&handler), Some(&doc), reason);
847    }
848
849    // ─── 5c. Identity resolution (§4.8.1, §7.2 item 6), unless step 5 ran it.
850    let resolved = match resolved {
851        Some(r) => r,
852        None => match handler.resolve_parties(&doc) {
853            Ok(r) => r,
854            Err(consistency) => {
855                return reject_response(Some(&handler), Some(&doc), consistency.into());
856            }
857        },
858    };
859
860    // ─── 6. Attribution gate. A document with neither a transport-
861    // authenticated peer nor a `proof` is attributable to nobody: the
862    // §4.8.1 fallback hands the handler whatever `issuer` string the sender
863    // typed. The binding spec does not permit `proof` to be omitted
864    // (`bindings/https/0.2` §5); this is that rule at runtime. See
865    // `HttpsServerBuilder::require_attribution`.
866    if state.require_attribution && handler.peer().is_none() && doc.proof.is_none() {
867        return reject_response(Some(&handler), Some(&doc), RejectReason::ProofRequired);
868    }
869
870    // ─── 7. DID-method pre-screen on `proof.verificationMethod`, ahead of
871    // the verifier so an unacceptable method never reaches a resolver.
872    if let (Some(allowed), Some(proof)) = (&state.allowed_did_methods, &doc.proof) {
873        if !did_method_allowed(&proof.verification_method, allowed) {
874            return reject_response(
875                Some(&handler),
876                Some(&doc),
877                RejectReason::ProofInvalid {
878                    // Does not name the accepted methods: that set is
879                    // deployment configuration, and echoing it would let a
880                    // probe fingerprint the fleet.
881                    reason: "verification method is not acceptable under this consumer's \
882                             proof policy"
883                        .to_string(),
884                },
885            );
886        }
887    }
888
889    // ─── 8. Proof handling (SPEC §7.2 item 7 + §4.7.1). The dispatch
890    // pipeline applies one of two policies based on builder
891    // configuration:
892    //
893    //   * Verifier configured (`HttpsServerBuilder::with_verifier`):
894    //     mirror `ProofPolicy::Verify` — proof-bearing documents are
895    //     verified, failure rejects `proofInvalid`. Proofless
896    //     documents proceed; the per-spec `IS_PROOF_REQUIRED` check in
897    //     the dispatch closure catches REQUIRED specs.
898    //
899    //   * No verifier (default): mirror `ProofPolicy::RejectIfPresent`
900    //     — proof-bearing documents are rejected `malformedRequest`
901    //     with the framework-shared `PROOF_NOT_ACCEPTED_BY_POLICY`
902    //     wire message. Silently dropping a producer's proof would
903    //     mislead them about the exchange's integrity guarantees, and
904    //     naming the server's configuration on the wire would let a
905    //     probe enumerate verifier coverage across a fleet.
906    if doc.proof.is_some() {
907        match &state.verifier {
908            Some(v) => {
909                if let Err(err) = v.verify_received(&received).await {
910                    return reject_response(
911                        Some(&handler),
912                        Some(&doc),
913                        RejectReason::ProofInvalid {
914                            reason: err.to_string(),
915                        },
916                    );
917                }
918            }
919            None => {
920                return reject_response(
921                    Some(&handler),
922                    Some(&doc),
923                    RejectReason::MalformedRequest {
924                        reason: PROOF_NOT_ACCEPTED_BY_POLICY.to_string(),
925                    },
926                );
927            }
928        }
929    }
930
931    // ─── 9. SPEC §7.2 item 11 — claim this document `id` for execution.
932    //
933    // This is the `validated → accepted` transition: every check that could
934    // still refuse the document for a reason unrelated to having seen it
935    // before has run, and the next thing that happens is the effect. See the
936    // module docs for why claiming earlier is wrong.
937    let mut claim: Option<DocumentDigest> = None;
938    if let Some(guard) = &state.replay_guard {
939        // Keyed on `id`, compared on a digest of the whole canonical document
940        // (`proof` included) — §7.2's *Keying and comparison*. An `id` alone
941        // cannot tell the §8.4 retry it must absorb from the conflict it must
942        // reject. Over `received`, the body as it arrived, not `doc`
943        // re-serialised: that re-renders `issuedAt` and `expiresAt`, so two
944        // bodies spelling one instant differently would compare equal.
945        let digest = received_document_digest(&received);
946
947        // §7.2 (*Bounding the record*): "A *consumer* that can establish
948        // neither an `expiresAt` nor an age for a document has no window in
949        // which to place it, and MUST NOT execute a *consequential Trust Task*
950        // on it." A guard asked to retain a record forever is not a guard.
951        let Some(retain_until) = state.freshness.record_expiry(&doc, now) else {
952            return reject_response(
953                Some(&handler),
954                Some(&doc),
955                RejectReason::Stale {
956                    detail: StaleReason::Unboundable,
957                },
958            );
959        };
960
961        match guard.claim(&doc.id, &digest, Some(retain_until), now).await {
962            // First sight. Execute, then record the result at step 10 so the
963            // next arrival is answered with it rather than re-executed.
964            Ok(ReplayVerdict::Fresh) => claim = Some(digest),
965
966            // Already executed, and the result was retained. §7.2
967            // (*Disposition of a duplicate*): "the consumer SHOULD return the
968            // previously determined result". Same 200, same body, no second
969            // dispatch — which is what makes a §8.4 bit-for-bit retry safe for
970            // the producer to send.
971            Ok(ReplayVerdict::Duplicate {
972                prior_response: Some(prior),
973                ..
974            }) => return success_response(prior),
975
976            // Already accepted; the original execution has not finished. SPEC:
977            // "the consumer SHOULD return or expose the existing execution
978            // state rather than begin another." HTTP's word for *accepted,
979            // outcome not yet available* is `202 Accepted`, and it is the
980            // honest one here: the document was accepted (it is being executed
981            // right now, by the first delivery), there is no result to return
982            // yet, and nothing failed. 200 would be a lie about having a
983            // result, 409 would claim a conflict that does not exist, and any
984            // error code would report a failure that did not happen.
985            Ok(ReplayVerdict::Duplicate {
986                in_flight: true, ..
987            }) => return StatusCode::ACCEPTED.into_response(),
988
989            // Already executed, and no result was retained — the
990            // fire-and-forget shape (§4.4.1), or a guard that keeps only the
991            // claim. §7.2: "where the specification defines no success
992            // response, silence is the correct disposition", and "in no case
993            // is a duplicate reported as `taskFailed`; the task did not fail,
994            // it already happened." `204 No Content` is silence with a status
995            // line, which is the most HTTP will allow.
996            Ok(ReplayVerdict::Duplicate { .. }) => return StatusCode::NO_CONTENT.into_response(),
997
998            // A different document under a reused `id`. §7.2 item 11 requires
999            // `idConflict` and forbids treating it as a retry of the original.
1000            Ok(ReplayVerdict::Conflict) => {
1001                return reject_response(Some(&handler), Some(&doc), RejectReason::IdConflict);
1002            }
1003
1004            // `ReplayVerdict` is `#[non_exhaustive]`. A verdict this binding
1005            // does not understand is not a licence to execute; fail closed on
1006            // the same `unavailable` path as a guard error.
1007            Ok(_) => {
1008                return reject_response(
1009                    Some(&handler),
1010                    Some(&doc),
1011                    RejectReason::Unavailable { retry_after: None },
1012                );
1013            }
1014
1015            // Fail closed. A consumer that cannot consult its record has not
1016            // satisfied item 11, and executing anyway is precisely the double
1017            // execution the rule forbids. `unavailable` is `retryable`, which
1018            // is the honest answer: the producer's bit-for-bit resend will be
1019            // absorbed correctly once the store is back. The store's identity
1020            // and failure mode stay in the log — `From<ReplayGuardError>`
1021            // discards them rather than putting them on the wire (§10.4).
1022            Err(e) => return reject_response(Some(&handler), Some(&doc), e.into()),
1023        }
1024    }
1025
1026    // ─── 10. Dispatch to the registered handler (which runs the per-spec
1027    // §7.2 policy checks first).
1028    let ctx = RequestContext {
1029        authenticated_sender: handler.peer().map(str::to_string),
1030        local: handler.local().map(str::to_string),
1031        resolved,
1032    };
1033    let dispatched = doc.clone();
1034    // A panicking handler must not leave the claim standing: the `id` would be
1035    // burned until `retain_until` and every honest resend absorbed in silence,
1036    // which is worse than the risk of re-running an effect whose completion
1037    // nobody can establish anyway. The panic itself is re-raised unchanged, so
1038    // this changes nothing a caller observes except the state of the record.
1039    let dispatch_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1040        (route.dispatch)(dispatched, &ctx)
1041    }));
1042    let dispatch_result = match dispatch_result {
1043        Ok(result) => result,
1044        Err(panic) => {
1045            release_claim(&state, &doc.id, claim.as_ref()).await;
1046            std::panic::resume_unwind(panic);
1047        }
1048    };
1049
1050    match dispatch_result {
1051        Ok(success_body) => {
1052            if claim.is_some() {
1053                if let Some(guard) = &state.replay_guard {
1054                    // Best-effort: the effect has already happened, so failing
1055                    // to cache the response cannot un-happen it. The claim —
1056                    // which is what item 11 needs — is already written, so a
1057                    // duplicate is still absorbed; all that is lost is the
1058                    // ability to hand back the same body.
1059                    // `None` records that the execution completed with no
1060                    // response to hand back — a later duplicate is absorbed
1061                    // and answered 204, not re-executed.
1062                    let _ = guard.record_response(&doc.id, success_body.as_ref()).await;
1063                }
1064            }
1065            match success_body {
1066                Some(body) => success_response(body),
1067                // SPEC §4.4.1 fire-and-forget: nothing to return, and the
1068                // absence of a `trust-task-error` is itself the success
1069                // signal. 204 is the same answer the binding gives a
1070                // duplicate of a completed fire-and-forget execution.
1071                None => StatusCode::NO_CONTENT.into_response(),
1072            }
1073        }
1074        Err(reason) => {
1075            // Nothing was executed, so nothing may be remembered as executed.
1076            // Holding the claim would answer a corrected — or merely
1077            // better-timed — resend under this `id` with silence or
1078            // `idConflict` for the whole retention window, which is a denial
1079            // of service manufactured out of a refusal.
1080            release_claim(&state, &doc.id, claim.as_ref()).await;
1081            reject_response(Some(&handler), Some(&doc), reason)
1082        }
1083    }
1084}
1085
1086/// Drop a claim whose execution produced no recorded response. Best-effort: a
1087/// guard that cannot release leaves the record standing until `retain_until`,
1088/// which is safe (item 11 still holds) but unkind to a legitimate retry.
1089///
1090/// Cancellation-safe: if the request future is dropped while the release is
1091/// awaited (a timeout layer, a client disconnect), [`AbandonedRelease`]
1092/// finishes it through [`ReplayGuard::release_abandoned`] rather than leaving
1093/// the claim in flight.
1094async fn release_claim(state: &ServerState, id: &str, digest: Option<&DocumentDigest>) {
1095    if let (Some(guard), Some(digest)) = (&state.replay_guard, digest) {
1096        release_with(guard.as_ref(), id, digest).await;
1097    }
1098}
1099
1100/// [`release_claim`]'s body, over the guard alone.
1101async fn release_with(guard: &dyn ReplayGuard, id: &str, digest: &DocumentDigest) {
1102    let pending = AbandonedRelease {
1103        guard,
1104        id,
1105        digest,
1106        armed: true,
1107    };
1108    let _ = guard.release(id, digest).await;
1109    pending.disarm();
1110}
1111
1112/// Releases a claim from its destructor unless disarmed — see [`release_claim`].
1113struct AbandonedRelease<'a> {
1114    guard: &'a dyn ReplayGuard,
1115    id: &'a str,
1116    digest: &'a DocumentDigest,
1117    armed: bool,
1118}
1119
1120impl AbandonedRelease<'_> {
1121    fn disarm(mut self) {
1122        self.armed = false;
1123    }
1124}
1125
1126impl Drop for AbandonedRelease<'_> {
1127    fn drop(&mut self) {
1128        if self.armed {
1129            // A guard that panics here loses only this release; a panic from a
1130            // destructor during another unwind would abort the process.
1131            let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1132                self.guard.release_abandoned(self.id, self.digest);
1133            }));
1134        }
1135    }
1136}
1137
1138/// `true` when the request declares `application/json` (parameters such as
1139/// `; charset=utf-8` are permitted and ignored). A missing header is *not*
1140/// acceptable: the binding spec makes `Content-Type` a MUST on the request,
1141/// and treating "absent" as "probably JSON" would re-open the simple-request
1142/// path this check exists to close.
1143fn is_json_content_type(headers: &HeaderMap) -> bool {
1144    let Some(value) = headers
1145        .get(header::CONTENT_TYPE)
1146        .and_then(|v| v.to_str().ok())
1147    else {
1148        return false;
1149    };
1150    let media_type = value.split(';').next().unwrap_or("").trim();
1151    media_type.eq_ignore_ascii_case("application/json")
1152}
1153
1154/// `true` when `verification_method` is a DID URL whose method is in
1155/// `allowed`. Anything that is not a DID URL (`did:<method>:<rest>`) fails —
1156/// an `https://…` verification method would hand the resolver an arbitrary
1157/// URL directly.
1158fn did_method_allowed(verification_method: &str, allowed: &BTreeSet<String>) -> bool {
1159    let Some(rest) = verification_method.strip_prefix("did:") else {
1160        return false;
1161    };
1162    let Some((method, remainder)) = rest.split_once(':') else {
1163        return false;
1164    };
1165    if method.is_empty() || remainder.is_empty() {
1166        return false;
1167    }
1168    allowed.contains(method)
1169}
1170
1171fn extract_bearer(headers: &HeaderMap) -> Option<&str> {
1172    let value = headers.get(header::AUTHORIZATION)?.to_str().ok()?;
1173    let token = value
1174        .strip_prefix("Bearer ")
1175        .or_else(|| value.strip_prefix("bearer "))?;
1176    Some(token.trim())
1177}
1178
1179fn downcast<P: Payload>(doc: TrustTask<Value>) -> Result<TrustTask<P>, RejectReason> {
1180    let TrustTask {
1181        id,
1182        thread_id,
1183        parent_thread_id,
1184        ceremony,
1185        type_uri,
1186        issuer,
1187        recipient,
1188        issued_at,
1189        expires_at,
1190        payload,
1191        context,
1192        proof,
1193        extra,
1194    } = doc;
1195    // Same §10.4 rule as the body parse above: the deserializer's rendering
1196    // names the missing or unexpected member and its offset. The Type URI the
1197    // sender itself chose is safe to omit, and the category is what it needs.
1198    let payload: P =
1199        serde_json::from_value(payload).map_err(|e| RejectReason::malformed_from_serde(&e))?;
1200    Ok(TrustTask {
1201        id,
1202        thread_id,
1203        parent_thread_id,
1204        ceremony,
1205        type_uri,
1206        issuer,
1207        recipient,
1208        issued_at,
1209        expires_at,
1210        payload,
1211        context,
1212        proof,
1213        extra,
1214    })
1215}
1216
1217fn success_response(body: Value) -> Response {
1218    let bytes = serde_json::to_vec(&body).expect("serialise success body");
1219    (
1220        StatusCode::OK,
1221        [(header::CONTENT_TYPE, "application/json")],
1222        bytes,
1223    )
1224        .into_response()
1225}
1226
1227fn reject_response(
1228    handler: Option<&HttpsHandler>,
1229    request: Option<&TrustTask<Value>>,
1230    reason: RejectReason,
1231) -> Response {
1232    // Status follows the error document actually emitted, not the inbound
1233    // reason. The suppressed identity-mismatch path rewrites the body to a
1234    // generic `malformedRequest` (SPEC §12.4); the status MUST match so it is
1235    // indistinguishable from a plain parse failure (no 403-vs-400 oracle for an
1236    // unauthenticated prober).
1237    let error_doc = build_error_response(handler, request, reason);
1238    let status = status_for_code(&error_doc.payload.code);
1239    let status = StatusCode::from_u16(status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
1240    let body = serde_json::to_vec(&error_doc).expect("serialise error response");
1241    (status, [(header::CONTENT_TYPE, "application/json")], body).into_response()
1242}
1243
1244fn build_error_response(
1245    handler: Option<&HttpsHandler>,
1246    request: Option<&TrustTask<Value>>,
1247    reason: RejectReason,
1248) -> ErrorResponse {
1249    let new_id = format!("urn:uuid:{}", Uuid::new_v4());
1250    match (handler, request) {
1251        (Some(h), Some(req)) => {
1252            // Apply §8.1 routing — identityMismatch goes to the
1253            // transport-authenticated peer (or is suppressed; we still
1254            // synthesise the document for the HTTP body, but route the
1255            // outbound recipient correctly).
1256            match h.reject(req, new_id.clone(), reason.clone()) {
1257                Some(resp) => resp,
1258                None => suppressed_error_response(&new_id),
1259            }
1260        }
1261        (_, Some(req)) => req.reject_with(new_id, reason),
1262        _ => {
1263            // No request context — synthesise a free-standing error doc.
1264            // This branch is hit when the body failed to deserialise into
1265            // a TrustTask at all.
1266            // `trust_task_error_type_uri()` rather than a version spelled out
1267            // here: this crate emitted `trust-task-error/0.2` on these two
1268            // fallback paths while `trust-tasks-rs` and the TypeScript runtime
1269            // both emitted `0.5`, so the version a producer saw depended on
1270            // which branch of this function it hit. One definition, one answer.
1271            let mut doc = TrustTask::new(
1272                new_id,
1273                trust_tasks_rs::trust_task_error_type_uri(),
1274                ErrorPayload::from(reason),
1275            );
1276            doc.issued_at = Some(trust_tasks_rs::issued_at_now());
1277            doc
1278        }
1279    }
1280}
1281
1282/// When `TransportHandler::reject` returns `None` (no transport-
1283/// authenticated sender under identityMismatch), the framework rule
1284/// (SPEC §8.1) is that the consumer SHOULD NOT emit a response. HTTP
1285/// gives us no way to "not emit" — the TCP connection already exists and
1286/// the peer is waiting for a status line. We therefore emit the *same*
1287/// generic `malformedRequest`/400 that a body parse failure produces.
1288///
1289/// Crucially we MUST NOT echo the `identityMismatch` code or status here
1290/// (SPEC §12.4): an unauthenticated prober who POSTs a spoofed in-band
1291/// identity would otherwise learn, from the code + 4xx, that this consumer
1292/// performs the cross-check and that the identity was contested — an
1293/// identity-probing oracle. Collapsing to the indistinguishable generic
1294/// rejection removes that signal; the diagnostic loss for honest peers is
1295/// the deliberate, safer trade.
1296fn suppressed_error_response(new_id: &str) -> ErrorResponse {
1297    let mut doc = TrustTask::new(
1298        new_id.to_string(),
1299        trust_tasks_rs::trust_task_error_type_uri(),
1300        ErrorPayload::from(RejectReason::MalformedRequest {
1301            reason: String::new(),
1302        }),
1303    );
1304    doc.issued_at = Some(trust_tasks_rs::issued_at_now());
1305    doc
1306}
1307
1308/// Make sure StandardCode → TrustTaskCode conversion is available where
1309/// we map status codes.
1310fn _verify_standard_code_into() {
1311    let _: trust_tasks_rs::TrustTaskCode = StandardCode::Expired.into();
1312}
1313
1314/// Unless discovery is public, refuse a caller with no transport-authenticated
1315/// sender rather than enumerating the route table (SPEC §12, discovery privacy).
1316///
1317/// Deliberately the same generic wording any other permission failure uses — a
1318/// discovery-specific message would itself confirm that discovery is installed
1319/// here.
1320fn refuse_unauthenticated_discovery(
1321    public: &AtomicBool,
1322    unauthenticated: bool,
1323) -> Result<(), RejectReason> {
1324    if !public.load(Ordering::Relaxed) && unauthenticated {
1325        return Err(RejectReason::PermissionDenied {
1326            reason: "discovery requires an authenticated sender".into(),
1327        });
1328    }
1329    Ok(())
1330}
1331
1332#[cfg(test)]
1333mod release_tests {
1334    use super::*;
1335    use std::future::Future;
1336    use trust_tasks_rs::{ReplayGuardError, ReplayVerdict};
1337
1338    /// `release` never completes, as a store round trip in progress when the
1339    /// request is cancelled; `release_abandoned` releases at once.
1340    struct StalledRelease(InMemoryReplayGuard);
1341
1342    #[async_trait::async_trait]
1343    impl ReplayGuard for StalledRelease {
1344        async fn claim(
1345            &self,
1346            id: &str,
1347            digest: &DocumentDigest,
1348            retain_until: Option<chrono::DateTime<chrono::Utc>>,
1349            now: chrono::DateTime<chrono::Utc>,
1350        ) -> Result<ReplayVerdict, ReplayGuardError> {
1351            self.0.claim(id, digest, retain_until, now).await
1352        }
1353        async fn release(&self, _: &str, _: &DocumentDigest) -> Result<(), ReplayGuardError> {
1354            std::future::pending().await
1355        }
1356        fn release_abandoned(&self, id: &str, digest: &DocumentDigest) {
1357            self.0.release_abandoned(id, digest);
1358        }
1359    }
1360
1361    /// A request dropped while its claim's release is awaited (a timeout
1362    /// layer, a client disconnect) still releases the claim.
1363    #[test]
1364    fn a_release_cancelled_mid_await_still_releases_the_claim() {
1365        let guard = StalledRelease(InMemoryReplayGuard::new(8));
1366        let digest = trust_tasks_rs::received_document_digest(&serde_json::json!({"id": "req-1"}));
1367        let now = chrono::Utc::now();
1368        let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
1369        let claimed = std::pin::pin!(guard.claim("req-1", &digest, None, now)).poll(&mut cx);
1370        assert!(matches!(
1371            claimed,
1372            std::task::Poll::Ready(Ok(ReplayVerdict::Fresh))
1373        ));
1374
1375        let released = std::pin::pin!(release_with(&guard, "req-1", &digest)).poll(&mut cx);
1376        assert!(released.is_pending());
1377        // The pinned future was dropped at the end of the statement above.
1378        assert_eq!(guard.0.len(), 0, "the claim was left in flight");
1379    }
1380}