pub struct HttpsServerBuilder { /* private fields */ }server only.Expand description
Builder for HttpsServer.
Implementations§
Source§impl HttpsServerBuilder
impl HttpsServerBuilder
Sourcepub fn local_vid(self, vid: impl Into<String>) -> Self
pub fn local_vid(self, vid: impl Into<String>) -> Self
Set the local party’s VID. Becomes local on the per-request
HttpsHandler and is what recipient-bearing documents are
cross-checked against under SPEC.md §7.2 item 5.
Sourcepub fn with_auth(self, auth: impl AsyncAuth) -> Self
pub fn with_auth(self, auth: impl AsyncAuth) -> Self
Plug in an authenticator. Defaults to a BearerAuth with no tokens
— every request is treated as unauthenticated and the framework falls
back entirely to in-band identity.
Takes any AsyncAuth, which every Auth is: a
synchronous lookup (a token map, a JWT signature check) is called
directly, and one that must await — a session store, an
introspection endpoint — implements AsyncAuth itself.
Sourcepub fn with_verifier<V>(self, verifier: V) -> Self
pub fn with_verifier<V>(self, verifier: V) -> Self
Plug in an in-band ProofVerifier. When configured, the
server verifies the proof member of every proof-bearing
document — over the request body as received — and rejects with
proofInvalid on failure; when absent, the server rejects
proof-bearing documents with malformedRequest (the
PROOF_NOT_ACCEPTED_BY_POLICY
rule — ProofPolicy::RejectIfPresentReceived).
The verifier is the last check before the per-spec policy and
the duplicate-execution claim: it is the only one that may egress,
so route lookup, transport auth and the attribution gate all run
ahead of it. See Self::allowed_did_methods for the pre-screen
that bounds where that egress can go.
Accepts any concrete ProofVerifier (e.g. from
trust-tasks-proof’s affinidi backend); the server stores it
behind trust_tasks_rs::DynProofVerifier for object-safe
dispatch.
Sourcepub fn with_payload_validator<W>(self, validator: W) -> Self
pub fn with_payload_validator<W>(self, validator: W) -> Self
Check every payload against its specification’s schema (SPEC §7.2
item 2) with validator — the residue deserialization cannot express
(minProperties, minItems on an optional array, conditional
subschemas); see PayloadPolicy. Without it the payload is accepted
on the strength of deserializing into the registered type.
The validate feature of trust-tasks-rs provides
validate::SchemaValidator.
Sourcepub fn max_body_bytes(self, limit: usize) -> Self
pub fn max_body_bytes(self, limit: usize) -> Self
Set the request-body limit HttpsServer::into_router applies,
outright, replacing the one derived from the registered types (see
MAX_BODY_BYTES). It is also then the bound held against a document
whose specification declares no maxDocumentBytes.
The body is buffered before authentication, so this is the memory an unauthenticated sender can make each request cost. A limit below a registered type’s declared bound refuses documents that specification says a consumer MUST NOT refuse on size alone.
Sourcepub fn on<P, F>(self, handler: F) -> Selfwhere
P: RequestPayload + Send + 'static,
P::Response: Serialize + 'static,
F: Fn(&TrustTask<P>, &RequestContext) -> Result<P::Response, RejectReason> + Send + Sync + 'static,
pub fn on<P, F>(self, handler: F) -> Selfwhere
P: RequestPayload + Send + 'static,
P::Response: Serialize + 'static,
F: Fn(&TrustTask<P>, &RequestContext) -> Result<P::Response, RejectReason> + Send + Sync + 'static,
Register a handler for the request payload type P. The handler
receives the typed request and a RequestContext; it returns
either the response payload (which the server wraps in a
#response-variant document via TrustTask::respond_with) or a
RejectReason (which the server wraps in a trust-task-error
document via TransportHandler::reject, applying SPEC §8.1
routing).
The handler is synchronous and may block — see the module docs,
Handlers and blocking: it runs to completion inside its request,
under block_in_place on a multi-threaded runtime, and the request
timeout does not bound it. A handler that does I/O is better written
with Self::on_async.
The handler also receives documents of a later version of P’s
specification that declares an extends chain reaching P’s, when
that version has no handler of its own (SPEC §5.2), with the payload
pruned to what P knows and type as received — so the response is
the received version’s #response.
Sourcepub fn on_async<P, F, Fut>(self, handler: F) -> Selfwhere
P: RequestPayload + Send + 'static,
P::Response: Serialize + 'static,
F: Fn(TrustTask<P>, RequestContext) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<P::Response, RejectReason>> + Send + 'static,
pub fn on_async<P, F, Fut>(self, handler: F) -> Selfwhere
P: RequestPayload + Send + 'static,
P::Response: Serialize + 'static,
F: Fn(TrustTask<P>, RequestContext) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<P::Response, RejectReason>> + Send + 'static,
Register an async handler for the request payload type P —
Self::on for a handler that awaits.
The handler takes the typed request and the RequestContext by
value and returns a future of the response payload or a
RejectReason. The future runs on the request’s task, so
Self::request_timeout bounds it.
A request abandoned mid-handler (the timeout, a client disconnect)
drops the future at whichever await it had reached. The effect may
already have committed, so the duplicate-execution claim is left in
flight rather than released: a bit-for-bit resend is answered
202 Accepted and does not run the handler again, until the record
expires with the acceptance window. The producer learns nothing more
about that execution, and a new attempt is a new id (SPEC §8.4). An
effect half-done at the cancellation point stays half-done: make it
atomic, or idempotent, across each await.
HttpsServer::builder()
.on_async::<grant::Payload, _, _>(move |req, ctx| {
let store = store.clone();
async move {
store.grant(&req.payload.entry, ctx.resolved.issuer.as_deref()).await?;
Ok(grant::Response { entry: req.payload.entry, ext: None })
}
})Sourcepub fn on_ack<P, F>(self, handler: F) -> Selfwhere
P: Payload + Send + 'static,
F: Fn(&TrustTask<P>, &RequestContext) -> Result<(), RejectReason> + Send + Sync + 'static,
pub fn on_ack<P, F>(self, handler: F) -> Selfwhere
P: Payload + Send + 'static,
F: Fn(&TrustTask<P>, &RequestContext) -> Result<(), RejectReason> + Send + Sync + 'static,
Register a handler for a fire-and-forget specification — one that defines no success response.
SPEC §4.4.1: such a specification’s consumer signals success by the
absence of a trust-task-error, and MUST NOT emit a
#response-variant document. There is therefore no response payload
for the handler to return, and Self::on cannot be used — those
specifications get no RequestPayload impl precisely so that the
mistake is a compile error rather than a runtime surprise.
The handler returns Ok(()) to acknowledge or a RejectReason to
refuse; an acknowledgement is answered 204 No Content, matching the
status the binding already uses for a duplicate of a completed
fire-and-forget execution (§5.1).
Synchronous, with Self::on’s blocking rules; see
Self::on_ack_async.
Sourcepub fn on_ack_async<P, F, Fut>(self, handler: F) -> Self
pub fn on_ack_async<P, F, Fut>(self, handler: F) -> Self
Self::on_ack for a handler that awaits, with
Self::on_async’s cancellation rules.
Sourcepub fn require_attribution(self, require: bool) -> Self
pub fn require_attribution(self, require: bool) -> Self
Reject any document that arrives with neither a transport-
authenticated peer nor a proof. Defaults to true.
§What this closes
Without it, an unauthenticated POST carrying
"issuer": "did:web:victim.example" and no proof reaches the
registered handler with RequestContext::resolved.issuer set
to the attacker’s string: with no transport peer the framework
falls back entirely to the document’s in-band issuer, and the
per-spec IS_PROOF_REQUIRED check only fires for specs whose front
matter declares proof REQUIRED — which most do not, mutating ones
included. The result is an unauthenticated, unattributable request
that a handler cannot tell apart from a genuine one.
The binding spec states plainly that “this binding does not permit
proof to be omitted” (bindings/https/0.2 §5). This flag is that
rule’s runtime representation. It is deliberately blanket — applied
to every registered spec, with no attempt to infer which ones are
consequential, because a per-spec derivation is one mis-classified
spec away from the same hole.
§Turning it off
require_attribution(false) restores the pre-0.11 behaviour, in
which any party that can reach the socket can assert any
issuer and have handlers act on it. Every authorization decision a
handler makes from ctx.resolved.issuer becomes attacker-controlled,
and nothing downstream can recover the distinction. Use it only for
local development and for tests that deliberately exercise the
unauthenticated path — never for a deployment reachable by anything
you do not already trust.
Sourcepub fn replay_protection(self, keep_record: bool) -> Self
pub fn replay_protection(self, keep_record: bool) -> Self
Keep the SPEC §7.2 item 11 duplicate-execution record. Defaults to
true.
§What it does
Item 11 is normative and unconditional for a consequential Trust
Task: a document already accepted under an id MUST NOT cause the
effect a second time, and a different document under the same id
MUST be rejected with idConflict. This binding provides no
transport freshness of its own — bindings/https/0.2 §5 — so the
record kept here is the only thing between a captured request body and
a repeated effect, and between an ordinary proxy or client retry and a
second ACL grant.
With no Self::with_replay_guard the server builds an
InMemoryReplayGuard with its default capacity. That is correct for
a single-process consumer and not correct behind a load balancer:
two replicas each hold their own map, so a document accepted by one is
Fresh at the other and the effect happens twice. A replicated
deployment MUST supply a shared-store guard.
§Turning it off
replay_protection(false) restores the pre-0.13 behaviour, in which
this server keeps no record of what it has executed. Every
consequential handler registered on it becomes replayable by anyone who
can re-send a request body — including any TLS-terminating intermediary
this binding cannot characterise (§5, Re-origination) — and a
duplicate delivery from an ordinary retry is executed a second time
with no signal that it was a duplicate. Nothing downstream can recover
the distinction, because nothing downstream is told. Use it only where
every registered specification “explicitly declares repeated execution
safe and intended” (the narrow disapplication item 11 allows), or for
local development.
Sourcepub fn with_replay_guard<G>(self, guard: G) -> Selfwhere
G: ReplayGuard + 'static,
pub fn with_replay_guard<G>(self, guard: G) -> Selfwhere
G: ReplayGuard + 'static,
Supply the ReplayGuard backing Self::replay_protection,
replacing the default InMemoryReplayGuard.
Use this for any deployment that is replicated, or that must survive a
process restart with its record intact: back the trait with Redis,
Postgres, DynamoDB, or whatever store every replica shares. The
implementation MUST make claim-and-record atomic across concurrent
calls — see ReplayGuard::claim.
Calling this does not by itself enable the record; it is enabled by
default and disabled only by replay_protection(false), which
suppresses this guard too.
Sourcepub fn freshness(self, policy: FreshnessPolicy) -> Self
pub fn freshness(self, policy: FreshnessPolicy) -> Self
The freshness bound applied to issuedAt / expiresAt (SPEC §7.2).
Defaults to FreshnessPolicy::consequential.
The default is the posture §7.2 (Bounding the record) describes:
issuedAt REQUIRED and a DEFAULT_MAX_AGE
acceptance window. It is not a separate feature from
Self::replay_protection but the other half of it —
FreshnessPolicy::record_expiry is what tells the guard how long to
retain each record, and SPEC makes the acceptance window and that
retention the same bound. There is deliberately no second TTL to
configure.
Widen max_age for a deployment whose intermediaries may hold a
request longer than five minutes — and understand that doing so widens
the replay record in lockstep, because it is one bound.
A policy with no max_age cannot place a document that carries no
expiresAt in any window; while the record is being kept, such a
document is refused with expired rather than executed on, per §7.2’s
“MUST NOT execute a consequential Trust Task on it”.
Sourcepub fn allowed_did_methods<I, S>(self, methods: I) -> Self
pub fn allowed_did_methods<I, S>(self, methods: I) -> Self
Restrict which DID methods may appear in proof.verificationMethod.
The check runs before the configured ProofVerifier is called.
Verifying a proof means resolving its verification method, and for
did:web that resolution is an outbound HTTPS request to a host the
sender chose — so an unscreened verifier turns this endpoint into
an SSRF and traffic-amplification primitive for anyone who can reach
it. Pinning the accepted methods (["key"], ["web", "webvh"], …)
bounds where that egress can go.
Default: with a verifier configured and neither this nor
Self::allow_any_did_method called, only
DEFAULT_ALLOWED_DID_METHODS (did:key) passes — a method that
resolves over the network is opt-in, never implied by plugging in a
resolving verifier. A server with no verifier screens nothing by
default: it refuses proof-bearing documents outright and never
egresses. A verificationMethod that is not a DID URL at all is
rejected whenever a restriction applies.
This is a coarse pre-screen at the binding boundary. Depth — resolved host allow-listing, redirect policy, per-resolution timeouts and caching — belongs in the resolver behind the verifier, not here.
Sourcepub fn allow_any_did_method(self) -> Self
pub fn allow_any_did_method(self) -> Self
Accept a proof.verificationMethod of any DID method, lifting the
did:key-only default described on Self::allowed_did_methods.
Only for a verifier that never resolves over the network, or whose resolver bounds where it goes (a host allow-list, private addresses refused, a deadline per resolution) — otherwise any caller can make this server fetch from a host it names.
Sourcepub fn public_discovery(self) -> Self
pub fn public_discovery(self) -> Self
Serve trust-task-discovery to unauthenticated callers.
By default the discovery handler installed by Self::with_discovery
/ Self::enable_discovery requires a transport-authenticated
sender and answers everyone else with permissionDenied: a discovery
response enumerates the full route table, and SPEC §12 says a
responder SHOULD authenticate the discoverer before answering.
Call this when the supported-task set is genuinely public. Order does not matter — it applies to a discovery handler registered either side of this call.
Sourcepub fn request_timeout(self, timeout: Duration) -> Self
pub fn request_timeout(self, timeout: Duration) -> Self
Per-request wall-clock budget applied by HttpsServer::into_router.
Defaults to DEFAULT_REQUEST_TIMEOUT.
Sourcepub fn max_concurrent_requests(self, limit: usize) -> Self
pub fn max_concurrent_requests(self, limit: usize) -> Self
Ceiling on concurrently-executing requests, applied by
HttpsServer::into_router. Defaults to
DEFAULT_MAX_CONCURRENT_REQUESTS.
Sourcepub fn with_discovery(self, registry: DiscoveryRegistry) -> Self
pub fn with_discovery(self, registry: DiscoveryRegistry) -> Self
Register trust-task-discovery handlers that respond with the contents
of registry, each version in the version it was asked: 0.3, the
current version, and the superseded 0.2 and 0.1 until they are
withdrawn. 0.2 and 0.3 write frameworkVersion three-part (SPEC
§5.1.1), 0.1 MAJOR.MINOR; only 0.3 can carry the registry’s
acceptance window (DiscoveryRegistry::acceptance_window_from).
Combine with Self::on in any order; the registry is consulted
afresh on every inbound query.
Unless Self::public_discovery is set, the handler answers a
caller with no transport-authenticated sender with permissionDenied
rather than enumerating the route table (SPEC §12, discovery
privacy).
Use this when the server’s discoverable set differs from its
actually-handled set — for example, when the server delegates
some types downstream but wants to advertise them as supported.
For the common “advertise exactly what I handle” case, see
Self::enable_discovery.
Sourcepub fn enable_discovery(self) -> Self
pub fn enable_discovery(self) -> Self
Snapshot every Type URI currently registered via Self::on and
install trust-task-discovery handlers that advertise them (and
discovery itself), as Self::with_discovery does. Call this
after every other .on(...); URIs registered afterward will not
be included.
A 0.4 response also advertises the acceptance window this server
enforces — its Self::freshness policy, whenever that is set — so a
producer holding a document can tell whether it will still be
accepted. A policy with no max_age has no window to state, and none
is advertised.
let server = HttpsServer::builder()
.local_vid("did:web:server.example")
.with_auth(BearerAuth::from_pairs([("alice", "did:web:alice.example")]))
.on::<grant::Payload, _>(handle_grant)
.on::<revoke::Payload, _>(handle_revoke)
.enable_discovery() // ← advertises grant + revoke
.build();Sourcepub fn build(self) -> HttpsServer
pub fn build(self) -> HttpsServer
Build the server. Run it with HttpsServer::serve.
Note the default authenticator is a BearerAuth with an empty token
table, so every request is unauthenticated unless
Self::with_auth was called. That is survivable only because
Self::require_attribution defaults to true; read its
documentation before turning it off.