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