vta-service 0.23.2

Service for Verifiable Trust Agents operating in Verifiable Trust Communities
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
// Helpers share the same `Result<_, Response>` shape as the slice
// handlers (see `vault.rs` for the same allow). The Response is owned
// and emitted on the same stack frame as the Err — boxing buys nothing.
#![allow(clippy::result_large_err)]

//! Shared helpers for the trust-task dispatcher and its per-slice
//! handler modules.
//!
//! Centralises:
//! - The `TRANSPORT_TRUST_TASK` audit-log channel label.
//! - Payload parsing (`parse_payload<T>`).
//! - `AppError` → reject-response mapping (`app_error_to_reject`).
//! - Reject + success document construction (`reject_with`,
//!   `success_response`, `error_response`).
//! - Wire-shape error helpers used by the dispatcher itself
//!   (`body_parse_error_response`, `method_not_found`).
//! - `not_implemented_yet` placeholder for Phase 3 slice stubs.
//!
//! All helpers are `pub(super)` — visible to the dispatcher (`mod.rs`)
//! and to the per-slice handler modules, but not to the wider crate.
//! Callers outside `routes::trust_tasks` should not depend on these
//! shapes; the entry point is `dispatch_trust_task` in `mod.rs`.

use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use serde_json::Value;
use trust_tasks_https::status_for_code;
use trust_tasks_rs::{
    ErrorPayload, ErrorResponse, RejectReason, TrustTask, TrustTaskCode, TypeUri,
};
use uuid::Uuid;

use crate::error::AppError;

/// Transport label passed to operations for audit-log discrimination
/// between the legacy REST path (`"rest"`) and the new trust-task
/// envelope (`"trust-task"`).
pub(super) const TRANSPORT_TRUST_TASK: &str = "trust-task";

/// The transport-neutral result of dispatching a Trust Task: the framework
/// HTTP status code plus the serialised result/error document bytes.
///
/// Both transports render from this one value — the REST route turns it into
/// an `axum::Response` via [`IntoResponse`]; the DIDComm `handle_trust_task`
/// reads [`body`](Self::body) straight as the reply envelope, with no
/// round-trip through an `axum::Response` to re-extract the JSON. The body
/// stays raw bytes (not a `serde_json::Value`) so the wire output is
/// byte-identical to direct document serialisation: serde_json has no
/// `preserve_order` feature here, so a `Value` round-trip would alphabetise
/// object keys and change the bytes.
pub(crate) struct TrustTaskOutcome {
    pub(crate) status: StatusCode,
    pub(crate) body: Vec<u8>,
}

impl IntoResponse for TrustTaskOutcome {
    fn into_response(self) -> Response {
        (
            self.status,
            [(axum::http::header::CONTENT_TYPE, "application/json")],
            self.body,
        )
            .into_response()
    }
}

/// Parse a trust-task document's `payload` field as the typed body
/// `T`, or return a `MalformedRequest` rejection response.
///
/// Consolidates the per-handler boilerplate where the only thing that
/// changes is the target type.
pub(super) fn parse_payload<T: serde::de::DeserializeOwned>(
    doc: &TrustTask<Value>,
) -> Result<T, TrustTaskOutcome> {
    serde_json::from_value::<T>(doc.payload.clone()).map_err(|e| {
        reject_with(
            doc,
            RejectReason::MalformedRequest {
                reason: format!("payload parse: {e}"),
            },
        )
    })
}

/// Map an `AppError` (the operation-layer error type) into a routed
/// trust-task error response with the appropriate framework reject
/// code:
///
/// - `Authentication` / `Unauthorized` / `Forbidden` → `permission_denied`
/// - `Validation` / `TrustTaskMalformed` / `InvalidCursor` → `malformed_request`
/// - `NotFound` / `Conflict` / `Gone` → `task_failed`
/// - everything else → `internal_error`
pub(super) fn app_error_to_reject(doc: &TrustTask<Value>, err: AppError) -> TrustTaskOutcome {
    let message = err.to_string();
    let reason = match err {
        AppError::Authentication(_) | AppError::Unauthorized(_) | AppError::Forbidden(_) => {
            RejectReason::PermissionDenied { reason: message }
        }
        // A rejected pagination cursor is a caller fault, not a server
        // one — REST already answers 400. Left in the `internal_error`
        // fallback it would tell a consumer to retry the same cursor,
        // when the correct response is to restart from the first page.
        AppError::Validation(_) | AppError::TrustTaskMalformed(_) | AppError::InvalidCursor => {
            RejectReason::MalformedRequest { reason: message }
        }
        // `Gone` rides with these rather than the `internal_error`
        // fallback. No task produces it today (its producers are REST-only),
        // but the fallback is the wrong default for it: a consumed single-use
        // resource is a terminal *caller-visible* outcome, and reporting it as
        // an internal error tells the client to retry something that can never
        // succeed again.
        AppError::NotFound(_) | AppError::Conflict(_) | AppError::Gone(_) => {
            RejectReason::TaskFailed {
                reason: message,
                details: None,
            }
        }
        // Framework 0.5.0, *What a `message` May Not Say*: a `message` MUST NOT
        // reveal consumer-internal state. That rule is now normative for every
        // code, and `internalError` is where this service leaked hardest — the
        // cause went out verbatim, so a caller learned things like "ATM not
        // configured — server cannot pack DIDComm envelopes" or "log entry has
        // no update_keys": the deployment's shape, its configuration, and which
        // internal invariant just broke.
        //
        // The producer needs one fact from an `internalError`: the failure was
        // not its doing, so re-sending an identical document may work. The
        // cause is what the *operator* needs, and it goes to the log where the
        // operator is.
        //
        // Every other arm above is safe to pass through: they describe the
        // caller's own request back to it (`not found`, `malformed`,
        // `permission denied`), which is not consumer-internal state.
        AppError::Internal(cause) => {
            tracing::error!(cause = %cause, "trust task failed with an internal error");
            RejectReason::InternalError {
                reason: OPAQUE_INTERNAL_ERROR.to_string(),
            }
        }
        other => {
            tracing::error!(cause = %other, "trust task failed with an internal error");
            RejectReason::InternalError {
                reason: OPAQUE_INTERNAL_ERROR.to_string(),
            }
        }
    };
    reject_with(doc, reason)
}

/// Build a routed rejection document for the given reason and wrap it
/// in an HTTP response. The framework computes the status code from
/// the reject's standard code.
/// What an `internalError` says on the wire.
///
/// Fixed text on purpose. Framework 0.5.0 forbids revealing consumer-internal
/// state in a `message`, and an internal failure's cause is nothing but that.
/// It tells the producer the one thing it can act on — the failure was not its
/// document's fault — and nothing an unauthenticated caller could probe with.
pub(super) const OPAQUE_INTERNAL_ERROR: &str =
    "the consumer could not complete this task; the request itself was accepted";

/// Framework 0.5.0, *Bounding `details`*: where a specification declares no
/// bound, 4096 bytes of JCS and 16 immediate members apply.
const DETAILS_MAX_JCS_BYTES: usize = 4096;
/// Companion to [`DETAILS_MAX_JCS_BYTES`].
const DETAILS_MAX_MEMBERS: usize = 16;

/// Drop a `details` that exceeds the framework's bound, keeping the `code`.
///
/// `details` was the one error-payload member with no size bound, and it
/// travels in the direction no producer-side bound reaches — the producer set
/// a body limit on what it *sent*, and nothing limits what comes back. This
/// service had a live instance: a policy denial puts the Rego module's
/// `explanation` on the wire, and that string is written by whoever authored
/// the policy, with no length anybody checked.
///
/// An oversized `details` is **ignored, never grounds to discard the `code`** —
/// the code is what the receiving party actually needs, and dropping the whole
/// rejection because its annex was too long would turn a verbose policy into an
/// unexplained failure.
fn bound_details(details: Option<Value>) -> Option<Value> {
    let details = details?;
    let too_many_members = details
        .as_object()
        .is_some_and(|o| o.len() > DETAILS_MAX_MEMBERS);
    let too_large = serde_json_canonicalizer::to_string(&details)
        .map(|jcs| jcs.len() > DETAILS_MAX_JCS_BYTES)
        // Uncanonicalisable is worse than oversized: it cannot be bounded, so
        // it does not go out.
        .unwrap_or(true);
    if too_many_members || too_large {
        tracing::warn!(
            members = details.as_object().map(serde_json::Map::len),
            "error `details` exceeds the framework bound and was dropped; the code still went out"
        );
        return None;
    }
    Some(details)
}

pub(super) fn reject_with(doc: &TrustTask<Value>, reason: RejectReason) -> TrustTaskOutcome {
    // Bound `details` here rather than at each of the thirty construction
    // sites: this is the one funnel every rejection passes through, so a new
    // site cannot be added that skips the check.
    let reason = match reason {
        RejectReason::TaskFailed { reason, details } => RejectReason::TaskFailed {
            reason,
            details: bound_details(details),
        },
        other => other,
    };
    let routed = doc.reject_with(format!("urn:uuid:{}", Uuid::new_v4()), reason);
    error_response(routed)
}

/// Reject with a **specification-extended** code (SPEC.md §8.5,
/// `<slug>:<local>`) rather than one of the framework's standard codes.
///
/// [`RejectReason`] cannot express one: every variant maps to a
/// [`StandardCode`](trust_tasks_rs::StandardCode), so a task whose own
/// specification declares an error code has no way to put it on the wire
/// through [`reject_with`] — the nearest fit, `TaskFailed`, says "attempted
/// and could not complete", which is the wrong thing to tell a producer whose
/// request was refused before anything was attempted. The framework itself is
/// not the limitation: `ErrorPayload::new` takes any [`TrustTaskCode`], and
/// `TrustTask::reject_with` takes a payload. This is the missing seam between
/// the two.
///
/// Use it only for a code the task's specification actually declares. A code
/// invented here is one no consumer can look up, which is worse than
/// `taskFailed` — that at least means something everywhere.
///
/// `details` passes through [`bound_details`] exactly as in [`reject_with`],
/// so this cannot become the construction site that skips the framework's
/// size bound.
pub(super) fn reject_with_code(
    doc: &TrustTask<Value>,
    code: TrustTaskCode,
    message: impl Into<String>,
    details: Option<Value>,
) -> TrustTaskOutcome {
    let mut payload = ErrorPayload::new(code).with_message(message);
    if let Some(d) = bound_details(details) {
        payload = payload.with_details(d);
    }
    let routed = doc.reject_with(format!("urn:uuid:{}", Uuid::new_v4()), payload);
    error_response(routed)
}

/// Build a routed success document with the given payload and wrap
/// it in an HTTP 200 response.
pub(super) fn success_response<R: serde::Serialize>(
    doc: &TrustTask<Value>,
    payload: R,
) -> TrustTaskOutcome {
    let response_doc = doc.respond_with(format!("urn:uuid:{}", Uuid::new_v4()), payload);
    let body = match serde_json::to_vec(&response_doc) {
        Ok(b) => b,
        Err(e) => {
            tracing::error!(error = %e, "failed to serialise success response doc");
            return reject_with(
                doc,
                RejectReason::InternalError {
                    reason: format!("response serialisation: {e}"),
                },
            );
        }
    };
    TrustTaskOutcome {
        status: StatusCode::OK,
        body,
    }
}

/// Build a routed `task_failed` rejection for a URI we know about but
/// haven't implemented yet. Kept available for Phase 3+ slices that
/// land their match arms before the handler body — each new slice can
/// stub via this helper, then replace with a real handler.
#[allow(dead_code)]
pub(super) fn not_implemented_yet(doc: TrustTask<Value>, reason: &str) -> TrustTaskOutcome {
    let reject = RejectReason::TaskFailed {
        reason: reason.to_string(),
        details: None,
    };
    let routed = doc.reject_with(format!("urn:uuid:{}", Uuid::new_v4()), reject);
    error_response(routed)
}

/// Build an `unsupported_type` rejection for an unrecognised type URI.
pub(super) fn method_not_found(doc: TrustTask<Value>, type_uri: &str) -> TrustTaskOutcome {
    let reject = RejectReason::UnsupportedType {
        type_uri: type_uri.to_string(),
    };
    let routed = doc.reject_with(format!("urn:uuid:{}", Uuid::new_v4()), reject);
    error_response(routed)
}

/// Wrap a routed `ErrorResponse` in an HTTP response with the right
/// status code per the framework's status table.
pub(super) fn error_response(err_doc: ErrorResponse) -> TrustTaskOutcome {
    let status = StatusCode::from_u16(status_for_code(&err_doc.payload.code))
        .unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
    let body = serde_json::to_vec(&err_doc).unwrap_or_else(|_| Vec::new());
    TrustTaskOutcome { status, body }
}

/// The framework's error-document Type URI — the one `TrustTask::reject_with`
/// stamps on every *routed* rejection this service emits.
///
/// Named here because `trust-tasks-rs` keeps `trust_task_error_type_uri()`
/// `pub(crate)`, so the only unrouted path — where there is no request document
/// to reject from — has to write the value out. It said `0.1` while every
/// routed reject went out as `0.3` (the framework has emitted `0.3` since its
/// own 0.3 release, for the §8.2 `inResponseTo` member that `0.2`'s
/// `additionalProperties: false` payload schema cannot admit). One service
/// emitting two versions is a trap for exactly the consumer that pins one of
/// them, which is not hypothetical: a client matching `0.1`/`0.2` by
/// enumeration read every `0.3` rejection as a *success*.
///
/// Now `0.5`, tracking `trust-tasks-rs` 0.9. The framework moved twice for the
/// same reason it moved to `0.3`: a new standard code that the older payload
/// schema's `code` enum does not list and whose extended-code pattern does not
/// match, so a document carrying it would fail to validate as the older
/// version. `0.4` carries `idConflict` (framework 0.4, SPEC §8.3) and `0.5`
/// carries `cancelled`. SPEC §5.2 forward-minor compatibility means a consumer
/// pinned to `0.3` SHOULD still accept these.
///
/// The constant is pinned by `unrouted_and_routed_errors_agree_on_the_type_uri`
/// below, which compares it against a real `reject_with`. When the framework
/// bumps the version, that test fails rather than this service silently
/// speaking two dialects again — which is exactly how this bump was caught.
fn framework_error_type_uri() -> TypeUri {
    "https://trusttasks.org/spec/trust-task-error/0.5"
        .parse()
        .expect("framework error Type URI parses")
}

/// Build a framework error document for a body-parse failure.
/// Unrouted (no issuer / recipient) — the framework permits this on
/// malformed-body failures since the producer can correlate on the
/// response `id`.
pub(super) fn body_parse_error_response(reason: &str) -> TrustTaskOutcome {
    let reject = RejectReason::MalformedRequest {
        reason: format!("body did not parse as a Trust Task document: {reason}"),
    };
    let payload: ErrorPayload = reject.into();
    let type_uri: TypeUri = framework_error_type_uri();
    let err = ErrorResponse {
        id: format!("urn:uuid:{}", Uuid::new_v4()),
        thread_id: None,
        // Unrouted: there is no parent thread to name either, for the same
        // reason there is no issuer — the body never parsed.
        parent_thread_id: None,
        type_uri,
        issuer: None,
        recipient: None,
        issued_at: Some(chrono::Utc::now()),
        expires_at: None,
        payload,
        context: None,
        // No ceremony, for the same reason as `parent_thread_id` above: SPEC
        // §7.1 carries the member forward from the request so a rejection stays
        // inside the enactment it belonged to, and here there is no request to
        // carry it from — the body never parsed into one. The *routed* rejects
        // get this right for free, because `reject_with` copies it.
        ceremony: None,
        proof: None,
        extra: Default::default(),
    };
    error_response(err)
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    fn doc() -> TrustTask<Value> {
        let uri: TypeUri = vta_sdk::trust_tasks::TASK_WEBVH_DIDS_UPDATE_1_0
            .parse()
            .expect("update uri");
        TrustTask::new("urn:uuid:test", uri, json!({}))
    }

    fn message_of(outcome: TrustTaskOutcome) -> String {
        let doc: Value = serde_json::from_slice(&outcome.body).expect("error doc parses");
        doc["payload"]["message"]
            .as_str()
            .expect("payload carries a message")
            .to_string()
    }

    /// An extended code reaches the wire in its `<slug>:<local>` spelling.
    ///
    /// `RejectReason` cannot express one — every variant maps to a standard
    /// code — so before `reject_with_code` a task whose own specification
    /// declared an error code had to render it as prose in `message` and let
    /// the caller string-match, which is the thing machine-readable codes
    /// exist to prevent.
    #[test]
    fn an_extended_code_survives_to_the_wire() {
        let code: TrustTaskCode = "provision/integration:contextRequired"
            .parse()
            .expect("a legal extended code");
        let outcome = reject_with_code(
            &doc(),
            code,
            "which context?",
            Some(json!({ "candidates": ["a", "b"] })),
        );
        let parsed: Value = serde_json::from_slice(&outcome.body).expect("error doc");
        assert_eq!(
            parsed["payload"]["code"],
            "provision/integration:contextRequired"
        );
        assert_eq!(parsed["payload"]["details"]["candidates"][1], "b");
    }

    /// The `details` bound is enforced on this path too.
    ///
    /// `reject_with`'s comment calls itself "the one funnel every rejection
    /// passes through, so a new site cannot be added that skips the check" —
    /// `reject_with_code` is a second funnel, and this is what keeps that
    /// sentence true.
    #[test]
    fn an_extended_code_rejection_bounds_its_details_too() {
        let code: TrustTaskCode = "provision/integration:contextRequired"
            .parse()
            .expect("a legal extended code");
        let huge = json!({ "explanation": "x".repeat(DETAILS_MAX_JCS_BYTES + 1) });
        let outcome = reject_with_code(&doc(), code, "which context?", Some(huge));
        let parsed: Value = serde_json::from_slice(&outcome.body).expect("error doc");
        assert_eq!(
            parsed["payload"]["code"], "provision/integration:contextRequired",
            "an oversized annex must never cost the code: {parsed}"
        );
        assert!(
            parsed["payload"]["details"].is_null(),
            "the oversized details should have been dropped: {parsed}"
        );
    }

    /// An oversized `details` is dropped, and the `code` still goes out.
    ///
    /// The live instance this bound exists for: a policy denial puts the Rego
    /// module's `explanation` on the wire, and that string is authored by
    /// whoever wrote the policy with no length anybody checks.
    #[test]
    fn an_oversized_details_is_dropped_but_the_code_survives() {
        let huge = serde_json::json!({ "explanation": "x".repeat(DETAILS_MAX_JCS_BYTES + 1) });
        let outcome = reject_with(
            &doc(),
            RejectReason::TaskFailed {
                reason: "policy denied".into(),
                details: Some(huge),
            },
        );
        let parsed: Value = serde_json::from_slice(&outcome.body).expect("error doc");
        assert_eq!(
            parsed["payload"]["code"], "taskFailed",
            "an oversized annex must never cost the code: {parsed}"
        );
        assert!(
            parsed["payload"].get("details").is_none_or(Value::is_null),
            "the oversized details must not go out: {parsed}"
        );
    }

    /// Too many members is the other half of the bound, and is not implied by
    /// the byte count — sixteen short members are small and still refused.
    #[test]
    fn a_details_with_too_many_members_is_dropped() {
        let mut wide = serde_json::Map::new();
        for i in 0..=DETAILS_MAX_MEMBERS {
            wide.insert(format!("k{i}"), serde_json::json!(1));
        }
        let outcome = reject_with(
            &doc(),
            RejectReason::TaskFailed {
                reason: "policy denied".into(),
                details: Some(Value::Object(wide)),
            },
        );
        let parsed: Value = serde_json::from_slice(&outcome.body).expect("error doc");
        assert_eq!(parsed["payload"]["code"], "taskFailed");
        assert!(parsed["payload"].get("details").is_none_or(Value::is_null));
    }

    /// A `details` inside the bound is untouched — the bound must not become a
    /// reason nothing useful is ever returned.
    #[test]
    fn a_small_details_still_goes_out() {
        let outcome = reject_with(
            &doc(),
            RejectReason::TaskFailed {
                reason: "policy denied".into(),
                details: Some(serde_json::json!({ "reason": "auth:consent_required" })),
            },
        );
        let parsed: Value = serde_json::from_slice(&outcome.body).expect("error doc");
        assert_eq!(
            parsed["payload"]["details"]["reason"], "auth:consent_required",
            "{parsed}"
        );
    }

    /// An `internalError` says nothing about the consumer's internals.
    ///
    /// Framework 0.5.0, *What a `message` May Not Say*: a `message` MUST NOT
    /// reveal consumer-internal state, now normative for every code. This
    /// service used to pass the cause through verbatim, so a caller — on the
    /// unauthenticated routes, not yet anybody — learned the deployment's
    /// shape from its failures.
    ///
    /// The earlier version of this test asserted the opposite, that the cause
    /// *was* on the wire; its subject was a doubled "internal error:" prefix,
    /// which the fixed text also settles.
    #[test]
    fn an_internal_error_reveals_no_internal_state() {
        let secret = "log entry has no update_keys";
        let message = message_of(app_error_to_reject(
            &doc(),
            AppError::Internal(secret.into()),
        ));
        assert!(
            !message.contains(secret),
            "the cause must reach the operator's log, never the wire: {message}"
        );
        assert!(
            message.contains(OPAQUE_INTERNAL_ERROR),
            "the producer still needs to be told the failure was not its \
             document's doing: {message}"
        );
        assert!(
            !message.contains("internal error: internal error"),
            "{message}"
        );
    }

    /// Every `AppError` that is not a caller-facing class lands on the same
    /// opaque text, not just `Internal`.
    ///
    /// The catch-all arm was the quieter leak: it rendered whatever `Display`
    /// the error happened to have, so a variant added later would start
    /// publishing itself without anyone choosing to.
    #[test]
    fn the_catch_all_arm_is_opaque_too() {
        let message = message_of(app_error_to_reject(
            &doc(),
            AppError::SecretStore("vault backend at 10.0.0.7 refused the token".into()),
        ));
        assert!(!message.contains("10.0.0.7"), "{message}");
        assert!(!message.contains("vault backend"), "{message}");
        assert!(message.contains(OPAQUE_INTERNAL_ERROR), "{message}");
    }

    /// The unrouted body-parse error must claim the same document type as a
    /// routed one. It cannot ask the framework — `trust_task_error_type_uri()`
    /// is `pub(crate)` there — so it names the version, and this compares that
    /// against what `reject_with` actually stamps. A framework bump fails here
    /// instead of splitting this service into two dialects, which is how the
    /// unrouted path came to say `0.1` while every routed reject said `0.3`.
    #[test]
    fn unrouted_and_routed_errors_agree_on_the_type_uri() {
        let routed = doc().reject_with(
            "urn:uuid:routed",
            RejectReason::InternalError {
                reason: "probe".into(),
            },
        );
        assert_eq!(
            framework_error_type_uri(),
            routed.type_uri,
            "the unrouted body-parse error names a different document type than \
             the framework stamps on a routed rejection"
        );
    }

    /// …and the bytes on the wire carry it, not just the value we compute.
    #[test]
    fn the_body_parse_error_goes_out_as_a_framework_error_document() {
        let outcome = body_parse_error_response("not json");
        let doc: Value = serde_json::from_slice(&outcome.body).expect("error doc parses");
        assert_eq!(
            doc["type"].as_str().expect("type present"),
            framework_error_type_uri().to_string()
        );
    }

    /// The other arms pair a differently-worded reject reason with the variant,
    /// so their `Display` is not redundant and stays — a `NotFound` still reads
    /// "task failed: not found: …", naming both the framework's verdict and ours.
    /// Pinned so a future tidy-up does not strip the cause along with the stutter.
    #[test]
    fn a_not_found_keeps_the_cause_the_operator_needs() {
        let message = message_of(app_error_to_reject(
            &doc(),
            AppError::NotFound("SCID QmNope not found".into()),
        ));
        assert!(message.contains("SCID QmNope not found"), "{message}");
    }

    /// `Gone` must not fall through to the `internal_error` catch-all. A
    /// consumed single-use resource is a terminal outcome the *caller* has to
    /// act on; `internal_error` reads as "server bug, try again", which is the
    /// one instruction that can never work here.
    #[test]
    fn a_gone_is_a_task_failure_not_an_internal_error() {
        let message = message_of(app_error_to_reject(
            &doc(),
            AppError::Gone("carve-out has already been used".into()),
        ));
        assert!(
            message.contains("carve-out has already been used"),
            "{message}"
        );
        assert!(
            !message.starts_with("internal error"),
            "a consumed resource must not report as a server fault: {message}"
        );
    }
}