Skip to main content

trust_tasks_https/
client.rs

1//! Reqwest-based client for emitting Trust Task documents over the
2//! HTTPS binding.
3//!
4//! ```rust,ignore
5//! let client = HttpsClient::builder()
6//!     .server_url("https://server.example")
7//!     .server_vid("did:web:server.example")
8//!     .my_vid("did:web:client.example")
9//!     .my_token("alice-token")
10//!     .build()?;
11//!
12//! let req = TrustTask::for_payload("urn:uuid:...", AclGrantPayload { ... });
13//! let resp: TrustTask<AclGrantResponse> = client.send(req).await?;
14//! ```
15//!
16//! The client serialises the request, attaches the configured bearer
17//! token, and POSTs to `<server_url>/trust-tasks`. The response body is
18//! deserialised either as the typed `#response`-variant document (HTTP
19//! 2xx) or as a `trust-task-error` document (non-2xx); both surface
20//! to the caller as [`ClientError`] variants for ergonomic `?` chains.
21
22use std::sync::Arc;
23use std::time::Duration;
24
25use reqwest::{header, Client, ClientBuilder, Url};
26use serde::de::DeserializeOwned;
27use serde_json::Value;
28use thiserror::Error;
29use trust_tasks_rs::{
30    erase_verifier, DynProofVerifier, ErrorResponse, Payload, ProofVerifier, RequestPayload,
31    TransportHandler, TrustTask, TypeUri,
32};
33
34use crate::handler::HttpsHandler;
35
36/// Default end-to-end request timeout. A trust-task exchange is one small
37/// JSON round trip; a peer that takes longer than this is down or wedged.
38pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
39
40/// Default connection-establishment timeout.
41pub const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
42
43/// Default cap on a response body: 256 KiB, the request cap the bundled
44/// server applies. A trust-task response is one small JSON document.
45pub const DEFAULT_MAX_RESPONSE_BYTES: usize = 256 * 1024;
46
47/// How much of a non-Trust-Task error body [`ClientError::HttpStatus`] keeps.
48const MAX_ERROR_BODY_BYTES: usize = 512;
49
50/// How many same-origin redirects [`HttpsClientBuilder::follow_redirects`]
51/// allows.
52const MAX_REDIRECTS: usize = 5;
53
54/// Builder for [`HttpsClient`].
55#[derive(Default)]
56pub struct HttpsClientBuilder {
57    server_url: Option<String>,
58    server_vid: Option<String>,
59    my_vid: Option<String>,
60    my_token: Option<String>,
61    strip_redundant_in_band: bool,
62    timeout: Option<Duration>,
63    connect_timeout: Option<Duration>,
64    response_verifier: Option<Arc<dyn DynProofVerifier>>,
65    max_response_bytes: Option<usize>,
66    allow_insecure_http: bool,
67    follow_redirects: bool,
68}
69
70impl HttpsClientBuilder {
71    /// Base URL of the server, e.g. `"https://server.example"`. The client
72    /// will POST to `<server_url>/trust-tasks`.
73    ///
74    /// It must be `https`. A plain `http` URL is accepted when its host is
75    /// loopback (`localhost`, `127.0.0.0/8`, `[::1]` — local servers and
76    /// tests), or elsewhere with [`Self::allow_insecure_http`]; a bearer
77    /// token is never sent to a non-loopback `http` URL.
78    pub fn server_url(mut self, url: impl Into<String>) -> Self {
79        self.server_url = Some(url.into());
80        self
81    }
82
83    /// VID of the server, used as the in-band `recipient` on outbound
84    /// documents and cross-checked with what the transport identifies as
85    /// the peer.
86    pub fn server_vid(mut self, vid: impl Into<String>) -> Self {
87        self.server_vid = Some(vid.into());
88        self
89    }
90
91    /// VID of this client, used as the in-band `issuer`.
92    pub fn my_vid(mut self, vid: impl Into<String>) -> Self {
93        self.my_vid = Some(vid.into());
94        self
95    }
96
97    /// Bearer token sent in `Authorization: Bearer <token>`. The server
98    /// resolves the token to a VID and uses that as the transport-
99    /// authenticated sender for §4.8.1 precedence.
100    pub fn my_token(mut self, token: impl Into<String>) -> Self {
101        self.my_token = Some(token.into());
102        self
103    }
104
105    /// If `true`, the client strips in-band `issuer`/`recipient` when
106    /// they match `my_vid`/`server_vid` respectively (SPEC §9.2 item 1).
107    /// Defaults to `false`: the safe behavior is to leave the in-band
108    /// members in place so the document remains self-contained at rest.
109    pub fn strip_redundant_in_band(mut self, strip: bool) -> Self {
110        self.strip_redundant_in_band = strip;
111        self
112    }
113
114    /// End-to-end request timeout. Defaults to [`DEFAULT_TIMEOUT`].
115    pub fn timeout(mut self, timeout: Duration) -> Self {
116        self.timeout = Some(timeout);
117        self
118    }
119
120    /// Connection-establishment timeout. Defaults to
121    /// [`DEFAULT_CONNECT_TIMEOUT`].
122    pub fn connect_timeout(mut self, timeout: Duration) -> Self {
123        self.connect_timeout = Some(timeout);
124        self
125    }
126
127    /// The largest response body the client reads, in bytes. A larger one
128    /// fails with [`ClientError::ResponseTooLarge`] as soon as it is
129    /// detected, without buffering the rest. Defaults to
130    /// [`DEFAULT_MAX_RESPONSE_BYTES`].
131    pub fn max_response_bytes(mut self, limit: usize) -> Self {
132        self.max_response_bytes = Some(limit);
133        self
134    }
135
136    /// Accept a plain `http` [`Self::server_url`] whose host is not loopback.
137    /// The document then crosses the network unencrypted. Even so, a
138    /// configured [`Self::my_token`] is refused over it: [`Self::build`]
139    /// fails rather than send the token in the clear.
140    pub fn allow_insecure_http(mut self, allow: bool) -> Self {
141        self.allow_insecure_http = allow;
142        self
143    }
144
145    /// Follow redirects to the same origin (scheme, host and port), at most
146    /// five. Off by default: a `3xx` is returned as
147    /// [`ClientError::HttpStatus`], so a signed document is never re-posted
148    /// to a URL other than the one configured. A redirect to another origin
149    /// is never followed.
150    pub fn follow_redirects(mut self, follow: bool) -> Self {
151        self.follow_redirects = follow;
152        self
153    }
154
155    /// Verify the `proof` on every response document.
156    ///
157    /// Off by default, and off is not the same as safe: with no verifier the
158    /// client checks *nothing* cryptographic about what came back. The
159    /// correlation checks [`HttpsClient::send`] performs — `threadId`,
160    /// `type`, `issuer`, `recipient` — bind a response to its request, but
161    /// they are all assertions by whoever answered the socket.
162    ///
163    /// Configuring a verifier expresses "I require signed responses": a
164    /// proofless response is then rejected with
165    /// [`ClientError::ResponseProofMissing`] rather than quietly accepted,
166    /// because a downgrade that goes unnoticed is worth no more than no
167    /// verification at all. Note the bundled [`HttpsServer`](crate::HttpsServer)
168    /// does not sign its responses, so this is for peers that do.
169    ///
170    /// The proof is verified over the response body exactly as received,
171    /// never a re-serialisation of it, so a peer's own spelling of a
172    /// timestamp or member order does not break a valid signature.
173    ///
174    /// **Error responses are held to it too.** A `trust-task-error` is
175    /// returned as [`ClientError::TrustTaskError`] only when its proof
176    /// verifies and its `issuer` / `recipient` match the configured VIDs, as a
177    /// success response's must. Anything else — an unsigned error, a bad
178    /// proof, an error from another party — is returned as
179    /// [`ClientError::UnverifiedErrorResponse`]: the body is kept for logging,
180    /// but nothing about it is attested, and it must not be read as the
181    /// server's answer.
182    pub fn with_response_verifier<V>(mut self, verifier: V) -> Self
183    where
184        V: ProofVerifier + Send + Sync + 'static,
185    {
186        self.response_verifier = Some(erase_verifier(verifier));
187        self
188    }
189
190    /// Build the [`HttpsClient`] or return a configuration error.
191    pub fn build(self) -> Result<HttpsClient, ClientError> {
192        let server_url = self
193            .server_url
194            .ok_or_else(|| ClientError::Config("server_url is required".into()))?;
195        let base: Url = format!("{}/trust-tasks", server_url.trim_end_matches('/'))
196            .parse()
197            .map_err(|e| ClientError::Config(format!("server_url is not a valid URL: {e}")))?;
198        let https = match base.scheme() {
199            "https" => true,
200            "http" if is_loopback(&base) => false,
201            "http" if self.my_token.is_some() => {
202                return Err(ClientError::Config(
203                    "server_url is plain http: a bearer token is only sent over https \
204                     (or to a loopback host)"
205                        .into(),
206                ))
207            }
208            "http" if self.allow_insecure_http => false,
209            "http" => {
210                return Err(ClientError::Config(
211                    "server_url is plain http: use https, or allow_insecure_http(true)".into(),
212                ))
213            }
214            other => {
215                return Err(ClientError::Config(format!(
216                    "server_url scheme {other:?} is not https"
217                )))
218            }
219        };
220
221        let redirects = if self.follow_redirects {
222            reqwest::redirect::Policy::custom(|attempt| {
223                let same_origin = attempt
224                    .previous()
225                    .first()
226                    .is_some_and(|first| first.origin() == attempt.url().origin());
227                if attempt.previous().len() > MAX_REDIRECTS {
228                    attempt.error("too many redirects")
229                } else if same_origin {
230                    attempt.follow()
231                } else {
232                    attempt.stop()
233                }
234            })
235        } else {
236            reqwest::redirect::Policy::none()
237        };
238
239        // Finite timeouts always: an unresponsive peer must surface as an
240        // error, never hang the caller. Callers with a genuinely long-running
241        // exchange can raise the values explicitly.
242        let http = ClientBuilder::new()
243            .timeout(self.timeout.unwrap_or(DEFAULT_TIMEOUT))
244            .connect_timeout(self.connect_timeout.unwrap_or(DEFAULT_CONNECT_TIMEOUT))
245            .redirect(redirects)
246            .https_only(https)
247            .build()
248            .map_err(|e| ClientError::Config(e.to_string()))?;
249
250        Ok(HttpsClient {
251            http,
252            endpoint: base,
253            server_vid: self.server_vid,
254            my_vid: self.my_vid,
255            my_token: self.my_token,
256            strip_redundant_in_band: self.strip_redundant_in_band,
257            response_verifier: self.response_verifier,
258            max_response_bytes: self
259                .max_response_bytes
260                .unwrap_or(DEFAULT_MAX_RESPONSE_BYTES),
261        })
262    }
263}
264
265/// Whether `url`'s host is this machine: `localhost` (or a name under it) or
266/// a loopback address.
267fn is_loopback(url: &Url) -> bool {
268    match url.host_str() {
269        None => false,
270        Some(host) => {
271            let host = host.trim_start_matches('[').trim_end_matches(']');
272            host.eq_ignore_ascii_case("localhost")
273                || host.to_ascii_lowercase().ends_with(".localhost")
274                || host
275                    .parse::<std::net::IpAddr>()
276                    .is_ok_and(|ip| ip.is_loopback())
277        }
278    }
279}
280
281/// Read `resp`'s body, refusing one over `limit` bytes as soon as its
282/// declared length or the bytes read so far exceed it.
283async fn read_capped(mut resp: reqwest::Response, limit: usize) -> Result<Vec<u8>, ClientError> {
284    if resp
285        .content_length()
286        .is_some_and(|declared| declared > limit as u64)
287    {
288        return Err(ClientError::ResponseTooLarge { limit });
289    }
290    let mut body = Vec::new();
291    while let Some(chunk) = resp.chunk().await? {
292        if body.len() + chunk.len() > limit {
293            return Err(ClientError::ResponseTooLarge { limit });
294        }
295        body.extend_from_slice(&chunk);
296    }
297    Ok(body)
298}
299
300/// At most [`MAX_ERROR_BODY_BYTES`] of `body`, cut at a character boundary.
301fn error_body_excerpt(body: &[u8]) -> String {
302    let text = String::from_utf8_lossy(body);
303    if text.len() <= MAX_ERROR_BODY_BYTES {
304        return text.into_owned();
305    }
306    let mut end = MAX_ERROR_BODY_BYTES;
307    while !text.is_char_boundary(end) {
308        end -= 1;
309    }
310    text[..end].to_string()
311}
312
313/// A decode failure without the body's content: serde's message can quote a
314/// value from the document, so only its category and position are kept.
315fn decode_error(e: serde_json::Error) -> ClientError {
316    ClientError::ResponseDecode(format!(
317        "{:?} error at line {} column {}",
318        e.classify(),
319        e.line(),
320        e.column()
321    ))
322}
323
324/// HTTPS Trust Tasks client.
325pub struct HttpsClient {
326    http: Client,
327    endpoint: Url,
328    server_vid: Option<String>,
329    my_vid: Option<String>,
330    my_token: Option<String>,
331    strip_redundant_in_band: bool,
332    response_verifier: Option<Arc<dyn DynProofVerifier>>,
333    max_response_bytes: usize,
334}
335
336impl HttpsClient {
337    /// Start a new builder.
338    pub fn builder() -> HttpsClientBuilder {
339        HttpsClientBuilder::default()
340    }
341
342    /// Send a typed Trust Task request to the configured server and
343    /// receive a typed response.
344    ///
345    /// The client:
346    ///
347    /// 1. Populates `issuer` / `recipient` on the outbound document from
348    ///    the configured VIDs if they are not already set.
349    /// 2. Optionally strips redundant in-band members per
350    ///    [`HttpsClientBuilder::strip_redundant_in_band`].
351    /// 3. POSTs the JSON body with `Authorization: Bearer <my_token>` if
352    ///    a token is configured.
353    /// 4. On HTTP 2xx, deserialises the body as `TrustTask<Req::Response>` **and
354    ///    binds it to the request** (see below).
355    /// 5. On non-2xx, deserialises the body as an [`ErrorResponse`],
356    ///    checks its `inResponseTo.id` where present, and returns it via
357    ///    [`ClientError::TrustTaskError`] — or, with a response verifier
358    ///    configured and the error not attested by it, via
359    ///    [`ClientError::UnverifiedErrorResponse`].
360    ///
361    /// # Response binding
362    ///
363    /// A 2xx body that merely *deserialises* as `TrustTask<Req::Response>` proves
364    /// nothing: it could answer a different request, be a different task
365    /// type whose payload happens to be shape-compatible, come from a
366    /// party that is not the configured server, or be addressed to someone
367    /// else. HTTP's request/response pairing is not a security property —
368    /// a proxy, a connection-reuse bug, or anything else in the path can
369    /// substitute one body for another. So four equalities are enforced
370    /// before the typed response is handed back:
371    ///
372    /// | Member       | Must equal                                   | On failure |
373    /// |--------------|----------------------------------------------|------------|
374    /// | `threadId`   | the request's `threadId`, or its `id`        | [`ClientError::ResponseThreadMismatch`] |
375    /// | `type`       | the request's `type` with `#response`        | [`ClientError::ResponseTypeMismatch`] |
376    /// | `issuer`     | the configured `server_vid`                   | [`ClientError::ResponseIssuerMismatch`] |
377    /// | `recipient`  | the configured `my_vid`                       | [`ClientError::ResponseRecipientMismatch`] |
378    ///
379    /// The `issuer` / `recipient` checks are skipped for a VID the caller
380    /// did not configure — there is nothing to compare against. When
381    /// [`HttpsClientBuilder::strip_redundant_in_band`] is set, an absent
382    /// member is accepted (the client asked for it to be stripped and the
383    /// responder echoed the absence); otherwise absence is a mismatch.
384    ///
385    /// On an error response, `inResponseTo.id` — where the responder
386    /// populated it — must be the request's `id`, else
387    /// [`ClientError::ErrorResponseMismatch`]. It is legitimately absent
388    /// under `identityMismatch` (SPEC §8.1 omits it), so absence is not an
389    /// error.
390    /// # Naming the response
391    ///
392    /// The response type is **not** a parameter: it is
393    /// `<Req as RequestPayload>::Response`, which the codegen pairs with the
394    /// request from the one schema. `send::<grant::Payload>(req)` therefore
395    /// returns `TrustTask<grant::Response>` and nothing else, where the
396    /// previous `send::<Req, Resp>` accepted a mismatched pair such as
397    /// `send::<grant::Payload, revoke::Response>(req)` and turned it into a
398    /// decode failure at run time.
399    ///
400    /// A specification defining no success response implements no
401    /// [`RequestPayload`], so `send` does not compile for it — see the
402    /// trait's docs.
403    pub async fn send<Req>(
404        &self,
405        mut request: TrustTask<Req>,
406    ) -> Result<TrustTask<Req::Response>, ClientError>
407    where
408        Req: RequestPayload + serde::Serialize,
409        Req::Response: DeserializeOwned,
410    {
411        // Fill in identity defaults if the caller didn't already set them.
412        if request.issuer.is_none() {
413            request.issuer = self.my_vid.clone();
414        }
415        if request.recipient.is_none() {
416            request.recipient = self.server_vid.clone();
417        }
418        if request.issued_at.is_none() {
419            request.issued_at = Some(trust_tasks_rs::issued_at_now());
420        }
421
422        // Apply binding-specific outbound prep.
423        if self.strip_redundant_in_band {
424            HttpsHandler::new(self.my_vid.clone(), self.server_vid.clone())
425                .prepare_outbound(&mut request);
426        }
427
428        // Build the HTTP request.
429        let mut req = self
430            .http
431            .post(self.endpoint.clone())
432            .header(header::CONTENT_TYPE, "application/json")
433            .json(&request);
434        if let Some(token) = &self.my_token {
435            req = req.bearer_auth(token);
436        }
437
438        let resp = req.send().await?;
439        let status = resp.status();
440        let body = read_capped(resp, self.max_response_bytes).await?;
441
442        if status.is_success() {
443            // A 2xx with no body is the server absorbing this document as a
444            // duplicate under SPEC §7.2 item 11 — `202` while the original
445            // execution is still running, `204` where the specification
446            // defines no success response. There is no document to correlate
447            // or verify, and treating it as a decode failure would report a
448            // parse error for a perfectly correct answer.
449            if body.is_empty() {
450                return Err(ClientError::DuplicateAbsorbed {
451                    http_status: status.as_u16(),
452                });
453            }
454
455            // Parse untyped first: the proof (if any) is verified over the
456            // document as received, and the correlation checks below need
457            // no payload types. Only then is the payload downcast to `Resp`.
458            let received: Value = serde_json::from_slice(&body).map_err(decode_error)?;
459            let untyped: TrustTask<Value> =
460                serde_json::from_value(received.clone()).map_err(decode_error)?;
461
462            self.check_response_binding(&request, &untyped)?;
463            self.verify_response_proof(&untyped, &received).await?;
464
465            let typed: TrustTask<Req::Response> =
466                serde_json::from_value(received).map_err(decode_error)?;
467            Ok(typed)
468        } else {
469            // Try to parse as a trust-task-error document; fall back to
470            // a generic transport error if the body isn't one.
471            let parsed = serde_json::from_slice::<Value>(&body)
472                .ok()
473                .and_then(|received| {
474                    serde_json::from_value::<ErrorResponse>(received.clone())
475                        .ok()
476                        .map(|doc| (received, doc))
477                });
478            match parsed {
479                Some((received, error_doc)) => {
480                    // With a response verifier configured, an error is the
481                    // server's answer only once it is attested as one: a
482                    // valid proof, from the configured server, to this
483                    // client. Otherwise anything on the path could answer
484                    // every request with an unsigned refusal.
485                    if let Err(reason) = self.verify_error_response(&error_doc, &received).await {
486                        return Err(ClientError::UnverifiedErrorResponse {
487                            http_status: status.as_u16(),
488                            reason,
489                            error: Box::new(error_doc),
490                        });
491                    }
492                    // §8.2 `inResponseTo.id` names the document being
493                    // reported on. Where the responder populated it, it must
494                    // be *our* document — otherwise an error about some
495                    // unrelated exchange would surface to this caller as the
496                    // outcome of its own request. It is legitimately absent
497                    // under `identityMismatch` (§8.1), so absence passes.
498                    if let Some(reported) = error_doc
499                        .payload
500                        .in_response_to
501                        .as_ref()
502                        .and_then(|r| r.id.as_deref())
503                    {
504                        if reported != request.id {
505                            return Err(ClientError::ErrorResponseMismatch {
506                                expected: request.id.clone(),
507                                actual: reported.to_string(),
508                            });
509                        }
510                    }
511                    Err(ClientError::TrustTaskError {
512                        http_status: status.as_u16(),
513                        error: Box::new(error_doc),
514                    })
515                }
516                None => Err(ClientError::HttpStatus {
517                    http_status: status.as_u16(),
518                    body: error_body_excerpt(&body),
519                }),
520            }
521        }
522    }
523
524    /// The four request/response equalities documented on [`Self::send`].
525    fn check_response_binding<Req: Payload + serde::Serialize>(
526        &self,
527        request: &TrustTask<Req>,
528        response: &TrustTask<Value>,
529    ) -> Result<(), ClientError> {
530        // 1. threadId — `respond_with` carries the request's threadId, or
531        //    its id when the request opened the thread.
532        let expected_thread = request
533            .thread_id
534            .clone()
535            .unwrap_or_else(|| request.id.clone());
536        if response.thread_id.as_deref() != Some(expected_thread.as_str()) {
537            return Err(ClientError::ResponseThreadMismatch {
538                expected: expected_thread,
539                actual: response.thread_id.clone(),
540            });
541        }
542
543        // 2. type — the `#response` variant of what we asked for (§4.4.1).
544        let expected_type: TypeUri = request.type_uri.with_response();
545        if response.type_uri != expected_type {
546            return Err(ClientError::ResponseTypeMismatch {
547                expected: expected_type.to_string(),
548                actual: response.type_uri.to_string(),
549            });
550        }
551
552        // 3/4. issuer and recipient — the response comes *from* the server
553        //      we addressed and is *for* us. Skipped where the caller
554        //      configured no VID to compare against.
555        if let Some(expected) = self.server_vid.as_deref() {
556            if !self.party_matches(response.issuer.as_deref(), expected) {
557                return Err(ClientError::ResponseIssuerMismatch {
558                    expected: expected.to_string(),
559                    actual: response.issuer.clone(),
560                });
561            }
562        }
563        if let Some(expected) = self.my_vid.as_deref() {
564            if !self.party_matches(response.recipient.as_deref(), expected) {
565                return Err(ClientError::ResponseRecipientMismatch {
566                    expected: expected.to_string(),
567                    actual: response.recipient.clone(),
568                });
569            }
570        }
571
572        Ok(())
573    }
574
575    /// A party member matches when it is present and equal, or when it is
576    /// absent and this client asked for redundant in-band members to be
577    /// stripped (§9.2 item 1) — the responder then legitimately echoes the
578    /// absence back.
579    fn party_matches(&self, actual: Option<&str>, expected: &str) -> bool {
580        match actual {
581            Some(v) => v == expected,
582            None => self.strip_redundant_in_band,
583        }
584    }
585
586    /// Verify the response's `proof` when a response verifier is configured,
587    /// over `received` — the body exactly as it arrived. A configured verifier
588    /// makes a signed response mandatory — see
589    /// [`HttpsClientBuilder::with_response_verifier`].
590    async fn verify_response_proof(
591        &self,
592        response: &TrustTask<Value>,
593        received: &Value,
594    ) -> Result<(), ClientError> {
595        let Some(verifier) = &self.response_verifier else {
596            return Ok(());
597        };
598        if response.proof.is_none() {
599            return Err(ClientError::ResponseProofMissing);
600        }
601        verifier
602            .verify_received(received)
603            .await
604            .map_err(|e| ClientError::ResponseProofInvalid(e.to_string()))
605    }
606
607    /// With a response verifier configured, an error response must carry a
608    /// proof that verifies over the body as received, and name the
609    /// configured server as `issuer` and this client as `recipient` (each
610    /// where configured). `Err` holds why it does not, for
611    /// [`ClientError::UnverifiedErrorResponse`]. Without a verifier there is
612    /// nothing to attest and every error passes.
613    async fn verify_error_response(
614        &self,
615        error: &ErrorResponse,
616        received: &Value,
617    ) -> Result<(), String> {
618        let Some(verifier) = &self.response_verifier else {
619            return Ok(());
620        };
621        if error.proof.is_none() {
622            return Err("the error response carried no proof".to_string());
623        }
624        if let Some(expected) = self.server_vid.as_deref() {
625            if !self.party_matches(error.issuer.as_deref(), expected) {
626                return Err("the error response's issuer is not the configured server".to_string());
627            }
628        }
629        if let Some(expected) = self.my_vid.as_deref() {
630            if !self.party_matches(error.recipient.as_deref(), expected) {
631                return Err("the error response is not addressed to this client".to_string());
632            }
633        }
634        verifier
635            .verify_received(received)
636            .await
637            .map_err(|e| format!("the error response's proof did not verify: {e}"))
638    }
639}
640
641/// Errors raised by [`HttpsClient::send`].
642///
643/// `#[non_exhaustive]`: match with a wildcard arm, so a variant added later
644/// is not a breaking change.
645#[derive(Debug, Error)]
646#[non_exhaustive]
647pub enum ClientError {
648    /// The client was constructed with missing or invalid configuration.
649    #[error("client configuration error: {0}")]
650    Config(String),
651
652    /// The HTTP request itself failed (DNS, connect, TLS, etc.).
653    #[error("HTTP request failed: {0}")]
654    Http(#[from] reqwest::Error),
655
656    /// The response body was larger than
657    /// [`HttpsClientBuilder::max_response_bytes`]. Reading stopped there and
658    /// nothing was decoded.
659    #[error("response body exceeds {limit} bytes")]
660    ResponseTooLarge {
661        /// The cap that was exceeded, in bytes.
662        limit: usize,
663    },
664
665    /// The server returned a `trust-task-error` response document.
666    /// `http_status` is the response's HTTP status code.
667    #[error("server returned trust-task-error (HTTP {http_status}): {error}")]
668    TrustTaskError {
669        /// The HTTP status code accompanying the error response.
670        http_status: u16,
671        /// The parsed error-response document.
672        error: Box<ErrorResponse>,
673    },
674
675    /// Non-2xx HTTP response that did not parse as a `trust-task-error`
676    /// document (e.g. the server replied with plain text or an empty body,
677    /// or a redirect the client did not follow).
678    #[error("non-2xx HTTP response ({http_status}) with non-Trust-Task body")]
679    HttpStatus {
680        /// The HTTP status code.
681        http_status: u16,
682        /// The start of the response body (at most 512 bytes), lossy-decoded
683        /// as UTF-8, for diagnostics. Not part of the `Display` text: it is
684        /// whatever the peer chose to send.
685        body: String,
686    },
687
688    /// 2xx response whose body did not decode as the expected
689    /// `TrustTask<Req::Response>`.
690    #[error("response body did not match expected type: {0}")]
691    ResponseDecode(String),
692
693    /// A 2xx response with an empty body: the consumer had already accepted
694    /// this document under SPEC §7.2 item 11 and has no result to hand back —
695    /// `202 Accepted` while the original execution is still in progress,
696    /// `204 No Content` where the *Trust Task specification* defines no
697    /// success response.
698    ///
699    /// **This is not a failure.** The effect happened; it did not happen
700    /// twice, which is the guarantee item 11 exists to give. §7.2 is explicit
701    /// that "in no case is a duplicate reported as `taskFailed`; the task did
702    /// not fail, it already happened" — a caller that folds every `Err` into
703    /// "the request failed" will misreport it. It arrives as an `Err` only
704    /// because [`HttpsClient::send`] is typed to return a response document
705    /// and there is none.
706    #[error("consumer absorbed this document as a duplicate (HTTP {http_status}); no result body")]
707    DuplicateAbsorbed {
708        /// The 2xx status carried: `202` (original still in flight) or `204`.
709        http_status: u16,
710    },
711
712    /// The response's `threadId` does not correlate with the request
713    /// (SPEC §4.9). The response answers some other exchange.
714    #[error("response threadId does not match the request: expected {expected}, got {actual:?}")]
715    ResponseThreadMismatch {
716        /// The request's `threadId`, or its `id` where the request opened
717        /// the thread.
718        expected: String,
719        /// What the response carried, if anything.
720        actual: Option<String>,
721    },
722
723    /// The response's `type` is not the `#response` variant of the
724    /// request's `type` (SPEC §4.4.1).
725    #[error("response type does not match the request: expected {expected}, got {actual}")]
726    ResponseTypeMismatch {
727        /// The request's Type URI with the `#response` fragment.
728        expected: String,
729        /// What the response carried.
730        actual: String,
731    },
732
733    /// The response's `issuer` is not the configured `server_vid` — the
734    /// answer did not come from the party this client addressed.
735    #[error("response issuer is not the configured server: expected {expected}, got {actual:?}")]
736    ResponseIssuerMismatch {
737        /// The configured `server_vid`.
738        expected: String,
739        /// What the response carried, if anything.
740        actual: Option<String>,
741    },
742
743    /// The response's `recipient` is not the configured `my_vid` — the
744    /// answer is addressed to somebody else.
745    #[error("response recipient is not this client: expected {expected}, got {actual:?}")]
746    ResponseRecipientMismatch {
747        /// The configured `my_vid`.
748        expected: String,
749        /// What the response carried, if anything.
750        actual: Option<String>,
751    },
752
753    /// An error response named a different document in `inResponseTo.id`
754    /// (SPEC §8.2) than the one this client sent.
755    #[error("error response reports on a different document: expected {expected}, got {actual}")]
756    ErrorResponseMismatch {
757        /// The request's `id`.
758        expected: String,
759        /// The `inResponseTo.id` the error response carried.
760        actual: String,
761    },
762
763    /// A response verifier is configured but the response carried no
764    /// `proof`. See [`HttpsClientBuilder::with_response_verifier`].
765    #[error("response carried no proof but this client requires signed responses")]
766    ResponseProofMissing,
767
768    /// The response's `proof` failed verification.
769    #[error("response proof verification failed: {0}")]
770    ResponseProofInvalid(String),
771
772    /// A non-2xx response carried a `trust-task-error` document that this
773    /// client, configured with a response verifier, could not attest: it had
774    /// no proof, its proof did not verify, or its `issuer` / `recipient` did
775    /// not match. See [`HttpsClientBuilder::with_response_verifier`].
776    ///
777    /// **Untrusted.** `error` is what arrived, kept for diagnostics; anything
778    /// on the path could have written it. Do not act on its `code` as the
779    /// server's verdict — treat the request's outcome as unknown.
780    #[error("unverified error response (HTTP {http_status}): {reason}")]
781    UnverifiedErrorResponse {
782        /// The HTTP status code that accompanied it.
783        http_status: u16,
784        /// Why it could not be attested.
785        reason: String,
786        /// The document as received. Unverified.
787        error: Box<ErrorResponse>,
788    },
789}