trust-tasks-https 0.40.4

HTTPS transport binding for the Trust Tasks framework — typed client + axum-based server, secure by default (attribution, replay record, freshness bound), with pluggable bearer-token identity.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
//! Reqwest-based client for emitting Trust Task documents over the
//! HTTPS binding.
//!
//! ```rust,ignore
//! let client = HttpsClient::builder()
//!     .server_url("https://server.example")
//!     .server_vid("did:web:server.example")
//!     .my_vid("did:web:client.example")
//!     .my_token("alice-token")
//!     .build()?;
//!
//! let req = TrustTask::for_payload("urn:uuid:...", AclGrantPayload { ... });
//! let resp: TrustTask<AclGrantResponse> = client.send(req).await?;
//! ```
//!
//! The client serialises the request, attaches the configured bearer
//! token, and POSTs to `<server_url>/trust-tasks`. The response body is
//! deserialised either as the typed `#response`-variant document (HTTP
//! 2xx) or as a `trust-task-error` document (non-2xx); both surface
//! to the caller as [`ClientError`] variants for ergonomic `?` chains.

use std::sync::Arc;
use std::time::Duration;

use reqwest::{header, Client, ClientBuilder, Url};
use serde::de::DeserializeOwned;
use serde_json::Value;
use thiserror::Error;
use trust_tasks_rs::{
    erase_verifier, DynProofVerifier, ErrorResponse, Payload, ProofVerifier, RequestPayload,
    TransportHandler, TrustTask, TypeUri,
};

use crate::handler::HttpsHandler;

/// Default end-to-end request timeout. A trust-task exchange is one small
/// JSON round trip; a peer that takes longer than this is down or wedged.
pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);

/// Default connection-establishment timeout.
pub const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(10);

/// Default cap on a response body: 256 KiB, the request cap the bundled
/// server applies. A trust-task response is one small JSON document.
pub const DEFAULT_MAX_RESPONSE_BYTES: usize = 256 * 1024;

/// How much of a non-Trust-Task error body [`ClientError::HttpStatus`] keeps.
const MAX_ERROR_BODY_BYTES: usize = 512;

/// How many same-origin redirects [`HttpsClientBuilder::follow_redirects`]
/// allows.
const MAX_REDIRECTS: usize = 5;

/// Builder for [`HttpsClient`].
#[derive(Default)]
pub struct HttpsClientBuilder {
    server_url: Option<String>,
    server_vid: Option<String>,
    my_vid: Option<String>,
    my_token: Option<String>,
    strip_redundant_in_band: bool,
    timeout: Option<Duration>,
    connect_timeout: Option<Duration>,
    response_verifier: Option<Arc<dyn DynProofVerifier>>,
    max_response_bytes: Option<usize>,
    allow_insecure_http: bool,
    follow_redirects: bool,
}

impl HttpsClientBuilder {
    /// Base URL of the server, e.g. `"https://server.example"`. The client
    /// will POST to `<server_url>/trust-tasks`.
    ///
    /// It must be `https`. A plain `http` URL is accepted when its host is
    /// loopback (`localhost`, `127.0.0.0/8`, `[::1]` — local servers and
    /// tests), or elsewhere with [`Self::allow_insecure_http`]; a bearer
    /// token is never sent to a non-loopback `http` URL.
    pub fn server_url(mut self, url: impl Into<String>) -> Self {
        self.server_url = Some(url.into());
        self
    }

    /// VID of the server, used as the in-band `recipient` on outbound
    /// documents and cross-checked with what the transport identifies as
    /// the peer.
    pub fn server_vid(mut self, vid: impl Into<String>) -> Self {
        self.server_vid = Some(vid.into());
        self
    }

    /// VID of this client, used as the in-band `issuer`.
    pub fn my_vid(mut self, vid: impl Into<String>) -> Self {
        self.my_vid = Some(vid.into());
        self
    }

    /// Bearer token sent in `Authorization: Bearer <token>`. The server
    /// resolves the token to a VID and uses that as the transport-
    /// authenticated sender for §4.8.1 precedence.
    pub fn my_token(mut self, token: impl Into<String>) -> Self {
        self.my_token = Some(token.into());
        self
    }

    /// If `true`, the client strips in-band `issuer`/`recipient` when
    /// they match `my_vid`/`server_vid` respectively (SPEC §9.2 item 1).
    /// Defaults to `false`: the safe behavior is to leave the in-band
    /// members in place so the document remains self-contained at rest.
    pub fn strip_redundant_in_band(mut self, strip: bool) -> Self {
        self.strip_redundant_in_band = strip;
        self
    }

    /// End-to-end request timeout. Defaults to [`DEFAULT_TIMEOUT`].
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }

    /// Connection-establishment timeout. Defaults to
    /// [`DEFAULT_CONNECT_TIMEOUT`].
    pub fn connect_timeout(mut self, timeout: Duration) -> Self {
        self.connect_timeout = Some(timeout);
        self
    }

    /// The largest response body the client reads, in bytes. A larger one
    /// fails with [`ClientError::ResponseTooLarge`] as soon as it is
    /// detected, without buffering the rest. Defaults to
    /// [`DEFAULT_MAX_RESPONSE_BYTES`].
    pub fn max_response_bytes(mut self, limit: usize) -> Self {
        self.max_response_bytes = Some(limit);
        self
    }

    /// Accept a plain `http` [`Self::server_url`] whose host is not loopback.
    /// The document then crosses the network unencrypted. Even so, a
    /// configured [`Self::my_token`] is refused over it: [`Self::build`]
    /// fails rather than send the token in the clear.
    pub fn allow_insecure_http(mut self, allow: bool) -> Self {
        self.allow_insecure_http = allow;
        self
    }

    /// Follow redirects to the same origin (scheme, host and port), at most
    /// five. Off by default: a `3xx` is returned as
    /// [`ClientError::HttpStatus`], so a signed document is never re-posted
    /// to a URL other than the one configured. A redirect to another origin
    /// is never followed.
    pub fn follow_redirects(mut self, follow: bool) -> Self {
        self.follow_redirects = follow;
        self
    }

    /// Verify the `proof` on every response document.
    ///
    /// Off by default, and off is not the same as safe: with no verifier the
    /// client checks *nothing* cryptographic about what came back. The
    /// correlation checks [`HttpsClient::send`] performs — `threadId`,
    /// `type`, `issuer`, `recipient` — bind a response to its request, but
    /// they are all assertions by whoever answered the socket.
    ///
    /// Configuring a verifier expresses "I require signed responses": a
    /// proofless response is then rejected with
    /// [`ClientError::ResponseProofMissing`] rather than quietly accepted,
    /// because a downgrade that goes unnoticed is worth no more than no
    /// verification at all. Note the bundled [`HttpsServer`](crate::HttpsServer)
    /// does not sign its responses, so this is for peers that do.
    ///
    /// The proof is verified over the response body exactly as received,
    /// never a re-serialisation of it, so a peer's own spelling of a
    /// timestamp or member order does not break a valid signature.
    ///
    /// **Error responses are held to it too.** A `trust-task-error` is
    /// returned as [`ClientError::TrustTaskError`] only when its proof
    /// verifies and its `issuer` / `recipient` match the configured VIDs, as a
    /// success response's must. Anything else — an unsigned error, a bad
    /// proof, an error from another party — is returned as
    /// [`ClientError::UnverifiedErrorResponse`]: the body is kept for logging,
    /// but nothing about it is attested, and it must not be read as the
    /// server's answer.
    pub fn with_response_verifier<V>(mut self, verifier: V) -> Self
    where
        V: ProofVerifier + Send + Sync + 'static,
    {
        self.response_verifier = Some(erase_verifier(verifier));
        self
    }

    /// Build the [`HttpsClient`] or return a configuration error.
    pub fn build(self) -> Result<HttpsClient, ClientError> {
        let server_url = self
            .server_url
            .ok_or_else(|| ClientError::Config("server_url is required".into()))?;
        let base: Url = format!("{}/trust-tasks", server_url.trim_end_matches('/'))
            .parse()
            .map_err(|e| ClientError::Config(format!("server_url is not a valid URL: {e}")))?;
        let https = match base.scheme() {
            "https" => true,
            "http" if is_loopback(&base) => false,
            "http" if self.my_token.is_some() => {
                return Err(ClientError::Config(
                    "server_url is plain http: a bearer token is only sent over https \
                     (or to a loopback host)"
                        .into(),
                ))
            }
            "http" if self.allow_insecure_http => false,
            "http" => {
                return Err(ClientError::Config(
                    "server_url is plain http: use https, or allow_insecure_http(true)".into(),
                ))
            }
            other => {
                return Err(ClientError::Config(format!(
                    "server_url scheme {other:?} is not https"
                )))
            }
        };

        let redirects = if self.follow_redirects {
            reqwest::redirect::Policy::custom(|attempt| {
                let same_origin = attempt
                    .previous()
                    .first()
                    .is_some_and(|first| first.origin() == attempt.url().origin());
                if attempt.previous().len() > MAX_REDIRECTS {
                    attempt.error("too many redirects")
                } else if same_origin {
                    attempt.follow()
                } else {
                    attempt.stop()
                }
            })
        } else {
            reqwest::redirect::Policy::none()
        };

        // Finite timeouts always: an unresponsive peer must surface as an
        // error, never hang the caller. Callers with a genuinely long-running
        // exchange can raise the values explicitly.
        let http = ClientBuilder::new()
            .timeout(self.timeout.unwrap_or(DEFAULT_TIMEOUT))
            .connect_timeout(self.connect_timeout.unwrap_or(DEFAULT_CONNECT_TIMEOUT))
            .redirect(redirects)
            .https_only(https)
            .build()
            .map_err(|e| ClientError::Config(e.to_string()))?;

        Ok(HttpsClient {
            http,
            endpoint: base,
            server_vid: self.server_vid,
            my_vid: self.my_vid,
            my_token: self.my_token,
            strip_redundant_in_band: self.strip_redundant_in_band,
            response_verifier: self.response_verifier,
            max_response_bytes: self
                .max_response_bytes
                .unwrap_or(DEFAULT_MAX_RESPONSE_BYTES),
        })
    }
}

/// Whether `url`'s host is this machine: `localhost` (or a name under it) or
/// a loopback address.
fn is_loopback(url: &Url) -> bool {
    match url.host_str() {
        None => false,
        Some(host) => {
            let host = host.trim_start_matches('[').trim_end_matches(']');
            host.eq_ignore_ascii_case("localhost")
                || host.to_ascii_lowercase().ends_with(".localhost")
                || host
                    .parse::<std::net::IpAddr>()
                    .is_ok_and(|ip| ip.is_loopback())
        }
    }
}

/// Read `resp`'s body, refusing one over `limit` bytes as soon as its
/// declared length or the bytes read so far exceed it.
async fn read_capped(mut resp: reqwest::Response, limit: usize) -> Result<Vec<u8>, ClientError> {
    if resp
        .content_length()
        .is_some_and(|declared| declared > limit as u64)
    {
        return Err(ClientError::ResponseTooLarge { limit });
    }
    let mut body = Vec::new();
    while let Some(chunk) = resp.chunk().await? {
        if body.len() + chunk.len() > limit {
            return Err(ClientError::ResponseTooLarge { limit });
        }
        body.extend_from_slice(&chunk);
    }
    Ok(body)
}

/// At most [`MAX_ERROR_BODY_BYTES`] of `body`, cut at a character boundary.
fn error_body_excerpt(body: &[u8]) -> String {
    let text = String::from_utf8_lossy(body);
    if text.len() <= MAX_ERROR_BODY_BYTES {
        return text.into_owned();
    }
    let mut end = MAX_ERROR_BODY_BYTES;
    while !text.is_char_boundary(end) {
        end -= 1;
    }
    text[..end].to_string()
}

/// A decode failure without the body's content: serde's message can quote a
/// value from the document, so only its category and position are kept.
fn decode_error(e: serde_json::Error) -> ClientError {
    ClientError::ResponseDecode(format!(
        "{:?} error at line {} column {}",
        e.classify(),
        e.line(),
        e.column()
    ))
}

/// HTTPS Trust Tasks client.
pub struct HttpsClient {
    http: Client,
    endpoint: Url,
    server_vid: Option<String>,
    my_vid: Option<String>,
    my_token: Option<String>,
    strip_redundant_in_band: bool,
    response_verifier: Option<Arc<dyn DynProofVerifier>>,
    max_response_bytes: usize,
}

impl HttpsClient {
    /// Start a new builder.
    pub fn builder() -> HttpsClientBuilder {
        HttpsClientBuilder::default()
    }

    /// Send a typed Trust Task request to the configured server and
    /// receive a typed response.
    ///
    /// The client:
    ///
    /// 1. Populates `issuer` / `recipient` on the outbound document from
    ///    the configured VIDs if they are not already set.
    /// 2. Optionally strips redundant in-band members per
    ///    [`HttpsClientBuilder::strip_redundant_in_band`].
    /// 3. POSTs the JSON body with `Authorization: Bearer <my_token>` if
    ///    a token is configured.
    /// 4. On HTTP 2xx, deserialises the body as `TrustTask<Req::Response>` **and
    ///    binds it to the request** (see below).
    /// 5. On non-2xx, deserialises the body as an [`ErrorResponse`],
    ///    checks its `inResponseTo.id` where present, and returns it via
    ///    [`ClientError::TrustTaskError`] — or, with a response verifier
    ///    configured and the error not attested by it, via
    ///    [`ClientError::UnverifiedErrorResponse`].
    ///
    /// # Response binding
    ///
    /// A 2xx body that merely *deserialises* as `TrustTask<Req::Response>` proves
    /// nothing: it could answer a different request, be a different task
    /// type whose payload happens to be shape-compatible, come from a
    /// party that is not the configured server, or be addressed to someone
    /// else. HTTP's request/response pairing is not a security property —
    /// a proxy, a connection-reuse bug, or anything else in the path can
    /// substitute one body for another. So four equalities are enforced
    /// before the typed response is handed back:
    ///
    /// | Member       | Must equal                                   | On failure |
    /// |--------------|----------------------------------------------|------------|
    /// | `threadId`   | the request's `threadId`, or its `id`        | [`ClientError::ResponseThreadMismatch`] |
    /// | `type`       | the request's `type` with `#response`        | [`ClientError::ResponseTypeMismatch`] |
    /// | `issuer`     | the configured `server_vid`                   | [`ClientError::ResponseIssuerMismatch`] |
    /// | `recipient`  | the configured `my_vid`                       | [`ClientError::ResponseRecipientMismatch`] |
    ///
    /// The `issuer` / `recipient` checks are skipped for a VID the caller
    /// did not configure — there is nothing to compare against. When
    /// [`HttpsClientBuilder::strip_redundant_in_band`] is set, an absent
    /// member is accepted (the client asked for it to be stripped and the
    /// responder echoed the absence); otherwise absence is a mismatch.
    ///
    /// On an error response, `inResponseTo.id` — where the responder
    /// populated it — must be the request's `id`, else
    /// [`ClientError::ErrorResponseMismatch`]. It is legitimately absent
    /// under `identityMismatch` (SPEC §8.1 omits it), so absence is not an
    /// error.
    /// # Naming the response
    ///
    /// The response type is **not** a parameter: it is
    /// `<Req as RequestPayload>::Response`, which the codegen pairs with the
    /// request from the one schema. `send::<grant::Payload>(req)` therefore
    /// returns `TrustTask<grant::Response>` and nothing else, where the
    /// previous `send::<Req, Resp>` accepted a mismatched pair such as
    /// `send::<grant::Payload, revoke::Response>(req)` and turned it into a
    /// decode failure at run time.
    ///
    /// A specification defining no success response implements no
    /// [`RequestPayload`], so `send` does not compile for it — see the
    /// trait's docs.
    pub async fn send<Req>(
        &self,
        mut request: TrustTask<Req>,
    ) -> Result<TrustTask<Req::Response>, ClientError>
    where
        Req: RequestPayload + serde::Serialize,
        Req::Response: DeserializeOwned,
    {
        // Fill in identity defaults if the caller didn't already set them.
        if request.issuer.is_none() {
            request.issuer = self.my_vid.clone();
        }
        if request.recipient.is_none() {
            request.recipient = self.server_vid.clone();
        }
        if request.issued_at.is_none() {
            request.issued_at = Some(trust_tasks_rs::issued_at_now());
        }

        // Apply binding-specific outbound prep.
        if self.strip_redundant_in_band {
            HttpsHandler::new(self.my_vid.clone(), self.server_vid.clone())
                .prepare_outbound(&mut request);
        }

        // Build the HTTP request.
        let mut req = self
            .http
            .post(self.endpoint.clone())
            .header(header::CONTENT_TYPE, "application/json")
            .json(&request);
        if let Some(token) = &self.my_token {
            req = req.bearer_auth(token);
        }

        let resp = req.send().await?;
        let status = resp.status();
        let body = read_capped(resp, self.max_response_bytes).await?;

        if status.is_success() {
            // A 2xx with no body is the server absorbing this document as a
            // duplicate under SPEC §7.2 item 11 — `202` while the original
            // execution is still running, `204` where the specification
            // defines no success response. There is no document to correlate
            // or verify, and treating it as a decode failure would report a
            // parse error for a perfectly correct answer.
            if body.is_empty() {
                return Err(ClientError::DuplicateAbsorbed {
                    http_status: status.as_u16(),
                });
            }

            // Parse untyped first: the proof (if any) is verified over the
            // document as received, and the correlation checks below need
            // no payload types. Only then is the payload downcast to `Resp`.
            let received: Value = serde_json::from_slice(&body).map_err(decode_error)?;
            let untyped: TrustTask<Value> =
                serde_json::from_value(received.clone()).map_err(decode_error)?;

            self.check_response_binding(&request, &untyped)?;
            self.verify_response_proof(&untyped, &received).await?;

            let typed: TrustTask<Req::Response> =
                serde_json::from_value(received).map_err(decode_error)?;
            Ok(typed)
        } else {
            // Try to parse as a trust-task-error document; fall back to
            // a generic transport error if the body isn't one.
            let parsed = serde_json::from_slice::<Value>(&body)
                .ok()
                .and_then(|received| {
                    serde_json::from_value::<ErrorResponse>(received.clone())
                        .ok()
                        .map(|doc| (received, doc))
                });
            match parsed {
                Some((received, error_doc)) => {
                    // With a response verifier configured, an error is the
                    // server's answer only once it is attested as one: a
                    // valid proof, from the configured server, to this
                    // client. Otherwise anything on the path could answer
                    // every request with an unsigned refusal.
                    if let Err(reason) = self.verify_error_response(&error_doc, &received).await {
                        return Err(ClientError::UnverifiedErrorResponse {
                            http_status: status.as_u16(),
                            reason,
                            error: Box::new(error_doc),
                        });
                    }
                    // §8.2 `inResponseTo.id` names the document being
                    // reported on. Where the responder populated it, it must
                    // be *our* document — otherwise an error about some
                    // unrelated exchange would surface to this caller as the
                    // outcome of its own request. It is legitimately absent
                    // under `identityMismatch` (§8.1), so absence passes.
                    if let Some(reported) = error_doc
                        .payload
                        .in_response_to
                        .as_ref()
                        .and_then(|r| r.id.as_deref())
                    {
                        if reported != request.id {
                            return Err(ClientError::ErrorResponseMismatch {
                                expected: request.id.clone(),
                                actual: reported.to_string(),
                            });
                        }
                    }
                    Err(ClientError::TrustTaskError {
                        http_status: status.as_u16(),
                        error: Box::new(error_doc),
                    })
                }
                None => Err(ClientError::HttpStatus {
                    http_status: status.as_u16(),
                    body: error_body_excerpt(&body),
                }),
            }
        }
    }

    /// The four request/response equalities documented on [`Self::send`].
    fn check_response_binding<Req: Payload + serde::Serialize>(
        &self,
        request: &TrustTask<Req>,
        response: &TrustTask<Value>,
    ) -> Result<(), ClientError> {
        // 1. threadId — `respond_with` carries the request's threadId, or
        //    its id when the request opened the thread.
        let expected_thread = request
            .thread_id
            .clone()
            .unwrap_or_else(|| request.id.clone());
        if response.thread_id.as_deref() != Some(expected_thread.as_str()) {
            return Err(ClientError::ResponseThreadMismatch {
                expected: expected_thread,
                actual: response.thread_id.clone(),
            });
        }

        // 2. type — the `#response` variant of what we asked for (§4.4.1).
        let expected_type: TypeUri = request.type_uri.with_response();
        if response.type_uri != expected_type {
            return Err(ClientError::ResponseTypeMismatch {
                expected: expected_type.to_string(),
                actual: response.type_uri.to_string(),
            });
        }

        // 3/4. issuer and recipient — the response comes *from* the server
        //      we addressed and is *for* us. Skipped where the caller
        //      configured no VID to compare against.
        if let Some(expected) = self.server_vid.as_deref() {
            if !self.party_matches(response.issuer.as_deref(), expected) {
                return Err(ClientError::ResponseIssuerMismatch {
                    expected: expected.to_string(),
                    actual: response.issuer.clone(),
                });
            }
        }
        if let Some(expected) = self.my_vid.as_deref() {
            if !self.party_matches(response.recipient.as_deref(), expected) {
                return Err(ClientError::ResponseRecipientMismatch {
                    expected: expected.to_string(),
                    actual: response.recipient.clone(),
                });
            }
        }

        Ok(())
    }

    /// A party member matches when it is present and equal, or when it is
    /// absent and this client asked for redundant in-band members to be
    /// stripped (§9.2 item 1) — the responder then legitimately echoes the
    /// absence back.
    fn party_matches(&self, actual: Option<&str>, expected: &str) -> bool {
        match actual {
            Some(v) => v == expected,
            None => self.strip_redundant_in_band,
        }
    }

    /// Verify the response's `proof` when a response verifier is configured,
    /// over `received` — the body exactly as it arrived. A configured verifier
    /// makes a signed response mandatory — see
    /// [`HttpsClientBuilder::with_response_verifier`].
    async fn verify_response_proof(
        &self,
        response: &TrustTask<Value>,
        received: &Value,
    ) -> Result<(), ClientError> {
        let Some(verifier) = &self.response_verifier else {
            return Ok(());
        };
        if response.proof.is_none() {
            return Err(ClientError::ResponseProofMissing);
        }
        verifier
            .verify_received(received)
            .await
            .map_err(|e| ClientError::ResponseProofInvalid(e.to_string()))
    }

    /// With a response verifier configured, an error response must carry a
    /// proof that verifies over the body as received, and name the
    /// configured server as `issuer` and this client as `recipient` (each
    /// where configured). `Err` holds why it does not, for
    /// [`ClientError::UnverifiedErrorResponse`]. Without a verifier there is
    /// nothing to attest and every error passes.
    async fn verify_error_response(
        &self,
        error: &ErrorResponse,
        received: &Value,
    ) -> Result<(), String> {
        let Some(verifier) = &self.response_verifier else {
            return Ok(());
        };
        if error.proof.is_none() {
            return Err("the error response carried no proof".to_string());
        }
        if let Some(expected) = self.server_vid.as_deref() {
            if !self.party_matches(error.issuer.as_deref(), expected) {
                return Err("the error response's issuer is not the configured server".to_string());
            }
        }
        if let Some(expected) = self.my_vid.as_deref() {
            if !self.party_matches(error.recipient.as_deref(), expected) {
                return Err("the error response is not addressed to this client".to_string());
            }
        }
        verifier
            .verify_received(received)
            .await
            .map_err(|e| format!("the error response's proof did not verify: {e}"))
    }
}

/// Errors raised by [`HttpsClient::send`].
///
/// `#[non_exhaustive]`: match with a wildcard arm, so a variant added later
/// is not a breaking change.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum ClientError {
    /// The client was constructed with missing or invalid configuration.
    #[error("client configuration error: {0}")]
    Config(String),

    /// The HTTP request itself failed (DNS, connect, TLS, etc.).
    #[error("HTTP request failed: {0}")]
    Http(#[from] reqwest::Error),

    /// The response body was larger than
    /// [`HttpsClientBuilder::max_response_bytes`]. Reading stopped there and
    /// nothing was decoded.
    #[error("response body exceeds {limit} bytes")]
    ResponseTooLarge {
        /// The cap that was exceeded, in bytes.
        limit: usize,
    },

    /// The server returned a `trust-task-error` response document.
    /// `http_status` is the response's HTTP status code.
    #[error("server returned trust-task-error (HTTP {http_status}): {error}")]
    TrustTaskError {
        /// The HTTP status code accompanying the error response.
        http_status: u16,
        /// The parsed error-response document.
        error: Box<ErrorResponse>,
    },

    /// Non-2xx HTTP response that did not parse as a `trust-task-error`
    /// document (e.g. the server replied with plain text or an empty body,
    /// or a redirect the client did not follow).
    #[error("non-2xx HTTP response ({http_status}) with non-Trust-Task body")]
    HttpStatus {
        /// The HTTP status code.
        http_status: u16,
        /// The start of the response body (at most 512 bytes), lossy-decoded
        /// as UTF-8, for diagnostics. Not part of the `Display` text: it is
        /// whatever the peer chose to send.
        body: String,
    },

    /// 2xx response whose body did not decode as the expected
    /// `TrustTask<Req::Response>`.
    #[error("response body did not match expected type: {0}")]
    ResponseDecode(String),

    /// A 2xx response with an empty body: the consumer had already accepted
    /// this document under SPEC §7.2 item 11 and has no result to hand back —
    /// `202 Accepted` while the original execution is still in progress,
    /// `204 No Content` where the *Trust Task specification* defines no
    /// success response.
    ///
    /// **This is not a failure.** The effect happened; it did not happen
    /// twice, which is the guarantee item 11 exists to give. §7.2 is explicit
    /// that "in no case is a duplicate reported as `taskFailed`; the task did
    /// not fail, it already happened" — a caller that folds every `Err` into
    /// "the request failed" will misreport it. It arrives as an `Err` only
    /// because [`HttpsClient::send`] is typed to return a response document
    /// and there is none.
    #[error("consumer absorbed this document as a duplicate (HTTP {http_status}); no result body")]
    DuplicateAbsorbed {
        /// The 2xx status carried: `202` (original still in flight) or `204`.
        http_status: u16,
    },

    /// The response's `threadId` does not correlate with the request
    /// (SPEC §4.9). The response answers some other exchange.
    #[error("response threadId does not match the request: expected {expected}, got {actual:?}")]
    ResponseThreadMismatch {
        /// The request's `threadId`, or its `id` where the request opened
        /// the thread.
        expected: String,
        /// What the response carried, if anything.
        actual: Option<String>,
    },

    /// The response's `type` is not the `#response` variant of the
    /// request's `type` (SPEC §4.4.1).
    #[error("response type does not match the request: expected {expected}, got {actual}")]
    ResponseTypeMismatch {
        /// The request's Type URI with the `#response` fragment.
        expected: String,
        /// What the response carried.
        actual: String,
    },

    /// The response's `issuer` is not the configured `server_vid` — the
    /// answer did not come from the party this client addressed.
    #[error("response issuer is not the configured server: expected {expected}, got {actual:?}")]
    ResponseIssuerMismatch {
        /// The configured `server_vid`.
        expected: String,
        /// What the response carried, if anything.
        actual: Option<String>,
    },

    /// The response's `recipient` is not the configured `my_vid` — the
    /// answer is addressed to somebody else.
    #[error("response recipient is not this client: expected {expected}, got {actual:?}")]
    ResponseRecipientMismatch {
        /// The configured `my_vid`.
        expected: String,
        /// What the response carried, if anything.
        actual: Option<String>,
    },

    /// An error response named a different document in `inResponseTo.id`
    /// (SPEC §8.2) than the one this client sent.
    #[error("error response reports on a different document: expected {expected}, got {actual}")]
    ErrorResponseMismatch {
        /// The request's `id`.
        expected: String,
        /// The `inResponseTo.id` the error response carried.
        actual: String,
    },

    /// A response verifier is configured but the response carried no
    /// `proof`. See [`HttpsClientBuilder::with_response_verifier`].
    #[error("response carried no proof but this client requires signed responses")]
    ResponseProofMissing,

    /// The response's `proof` failed verification.
    #[error("response proof verification failed: {0}")]
    ResponseProofInvalid(String),

    /// A non-2xx response carried a `trust-task-error` document that this
    /// client, configured with a response verifier, could not attest: it had
    /// no proof, its proof did not verify, or its `issuer` / `recipient` did
    /// not match. See [`HttpsClientBuilder::with_response_verifier`].
    ///
    /// **Untrusted.** `error` is what arrived, kept for diagnostics; anything
    /// on the path could have written it. Do not act on its `code` as the
    /// server's verdict — treat the request's outcome as unknown.
    #[error("unverified error response (HTTP {http_status}): {reason}")]
    UnverifiedErrorResponse {
        /// The HTTP status code that accompanied it.
        http_status: u16,
        /// Why it could not be attested.
        reason: String,
        /// The document as received. Unverified.
        error: Box<ErrorResponse>,
    },
}