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