vta-service 0.10.0

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
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
790
791
792
793
794
795
796
797
798
799
800
801
802
//! `POST /api/trust-tasks` — the VTA-side trust-task dispatcher.
//!
//! Mirrors `affinidi-webvh-service`'s `did-hosting-control` dispatcher
//! (`routes/trust_tasks.rs`) — body shape, error envelope, and routing
//! semantics are byte-equivalent.
//!
//! ## Module layout
//!
//! - [`helpers`]: shared wire-shape helpers (`parse_payload`,
//!   `reject_with`, `success_response`, `app_error_to_reject`, etc.)
//!   used by every slice's handler module. `pub(super)` only.
//! - One module per Phase 3 slice (`auth`, `acl`, `contexts`, `keys`,
//!   `seeds`, `audit`, `discovery`, …). Each module's handler
//!   functions are `pub(super) async fn handle_<op>(state, auth, doc)
//!   -> Response`. The dispatcher's match arms call them.
//! - The cross-crate URI parity harness lives in the test module
//!   below; it asserts every URI declared in `vta-sdk::trust_tasks`
//!   is either dispatched or on the `REST_ROUTED` allowlist.
//!
//! ## Adding a new URI
//!
//! 1. Add the `TASK_*` const to `vta-sdk::trust_tasks` and extend its
//!    `ALL_URIS` array.
//! 2. Add a `handle_*` function in the appropriate slice module
//!    (create a new one if no slice fits).
//! 3. Add one line to the [`dispatch_table!`] invocation: `TASK_* =>
//!    slice::handle_*`. That single declaration generates **both** the
//!    `dispatch_typed` match arm **and** the parity-harness entry — they
//!    can't drift, so there is no separate test array to update.
//!
//! ## Body-parse failures emit framework-conformant errors
//!
//! Like the webvh-service dispatcher, we accept the body as
//! `axum::body::Bytes` and parse to `TrustTask<Value>` by hand so a
//! malformed body produces a `trust-task-error/0.1` document (per
//! framework SPEC §8.5) instead of axum's plain-text 400 default.

use axum::extract::State;
use axum::response::{IntoResponse, Response};
use serde_json::Value;
use trust_tasks_rs::TrustTask;

use crate::auth::AuthClaims;
use crate::error::AppError;
use crate::server::AppState;

mod acl;
mod audit;
mod auth;
mod backup;
mod config;
mod consent;
mod contexts;
mod cred_vault;
mod credential_exchange;
mod device;
mod did_templates;
mod discovery;
mod helpers;
mod keys;
mod management;
#[cfg(all(feature = "webvh", feature = "didcomm"))]
mod passkey_vms;
#[cfg(feature = "webvh")]
mod provision_integration;
mod seeds;
// `pub(crate)` so the REST routes (`routes::acl`, `routes::contexts`) can
// reach the `RequireStepUp` extractor + op markers. The step-up *engine* lives
// in `operations::step_up` (P2.4); this module holds only the transport
// wrappers (the trust-task `require_step_up`/`handle_approve_response` and the
// REST `RequireStepUp` extractor) over it.
pub(crate) mod step_up;
mod step_up_policy;
pub(crate) use step_up::{
    AclChangeRoleOp, AclGrantOp, AclRevokeOp, AclSwapKeyOp, ContextDeleteOp, RequireStepUp,
};
mod vault;
#[cfg(feature = "webvh")]
mod webvh;
pub(crate) mod wire_v0_2;

/// The transport-neutral dispatch result — see [`helpers::TrustTaskOutcome`].
/// Re-exported so both transports (`routes`-mounted REST handler + DIDComm
/// `messaging::handlers::handle_trust_task`) can name `crate::trust_tasks::
/// TrustTaskOutcome`.
pub(crate) use helpers::TrustTaskOutcome;
use helpers::{body_parse_error_response, method_not_found, reject_with};
#[cfg(feature = "didcomm")]
use trust_tasks_rs::RejectReason;

/// URIs that the VTA exposes through dedicated unauth REST routes
/// rather than the authenticated `/api/trust-tasks` dispatcher.
///
/// The canonical list lives in the SDK
/// ([`vta_sdk::trust_tasks::REST_ROUTED_URIS`]) so the dispatcher's parity
/// harness and any generic client catalog (e.g. the `vta-mcp` `vta_call`
/// gateway, which advertises [`vta_sdk::trust_tasks::dispatch_routed_uris`])
/// can't drift. Handlers live in `routes::auth` (passkey login, legacy
/// challenge/authenticate/refresh) and `routes::attestation` (TEE status /
/// report).
#[allow(dead_code)] // consumed by the dispatcher's test-only parity harness
const REST_ROUTED: &[&str] = vta_sdk::trust_tasks::REST_ROUTED_URIS;

/// URIs that vta-sdk declares but the dispatcher may not wire in
/// every build because they depend on `vta-service` feature flags
/// (e.g. `webvh`, `didcomm`, `tee`).
///
/// When their feature is **on**, the [`dispatch_table!`] entry is compiled, so
/// `dispatched_uris()` lists them. When the feature is **off**, the entry's
/// `#[cfg(...)]` excludes it from both the match and the parity list — so only
/// this allowlist keeps the parity harness from failing on them.
///
/// Adding a URI here is a deliberate act: it says "this URI's
/// dispatch lives behind a feature flag and may be unreachable in
/// some builds, but the URI is canonically declared in vta-sdk."
///
/// All entries are unconditional (don't change per cfg). They're
/// just statements that the dispatcher knows about them.
#[allow(dead_code)] // consumed by the dispatcher's test-only parity harness
const KNOWN_FEATURE_GATED_URIS: &[&str] = &[
    // Passkey-VMs slice — requires `webvh` + `didcomm` features. The
    // `dispatch_table!` entries list the same URIs and are tracked by the
    // parity harness when both features are on; this allowlist covers builds
    // where either feature is off.
    vta_sdk::trust_tasks::TASK_PASSKEY_VMS_ENROLL_CHALLENGE_0_1,
    vta_sdk::trust_tasks::TASK_PASSKEY_VMS_ENROLL_SUBMIT_0_1,
    vta_sdk::trust_tasks::TASK_PASSKEY_VMS_LIST_0_1,
    vta_sdk::trust_tasks::TASK_PASSKEY_VMS_REVOKE_0_1,
    // Provision-integration — requires `webvh`.
    vta_sdk::trust_tasks::TASK_PROVISION_INTEGRATION_REQUEST_1_0,
    // WebVH-DID-lifecycle slice — requires `webvh`. The `dispatch_table!`
    // entries list the same URIs and are tracked by the parity harness when
    // `webvh` is on; this allowlist covers builds where `webvh` is off.
    vta_sdk::trust_tasks::TASK_WEBVH_SERVERS_LIST_1_0,
    vta_sdk::trust_tasks::TASK_WEBVH_SERVERS_ADD_1_0,
    vta_sdk::trust_tasks::TASK_WEBVH_SERVERS_UPDATE_1_0,
    vta_sdk::trust_tasks::TASK_WEBVH_SERVERS_REMOVE_1_0,
    vta_sdk::trust_tasks::TASK_WEBVH_DIDS_LIST_1_0,
    vta_sdk::trust_tasks::TASK_WEBVH_DIDS_CREATE_1_0,
    vta_sdk::trust_tasks::TASK_WEBVH_DIDS_GET_1_0,
    vta_sdk::trust_tasks::TASK_WEBVH_DIDS_GET_LOG_1_0,
    vta_sdk::trust_tasks::TASK_WEBVH_DIDS_DELETE_1_0,
    vta_sdk::trust_tasks::TASK_WEBVH_DIDS_UPDATE_1_0,
    vta_sdk::trust_tasks::TASK_WEBVH_DIDS_ROTATE_KEYS_1_0,
    vta_sdk::trust_tasks::TASK_WEBVH_DIDS_REGISTER_WITH_SERVER_1_0,
    // did-management Trust-Task spec URIs — declared in vta-sdk by
    // PR #139 ("PR 1 of N") as the shared vocabulary for the
    // cross-repo did-management migration (vta-sdk + vta-service +
    // affinidi-webvh-service all reference these). They are
    // **outbound producer URIs** — VTA's `webvh_didcomm.rs` sends
    // requests with these URIs to did-hosting, then matches
    // `<uri>#response` on the way back. They are not consumed by any
    // vta-service inbound dispatcher arm, so the parity harness
    // treats them like the feature-gated URIs above (declared
    // canonically, intentionally not in `DISPATCHED_URIS`). Removing
    // an entry here without a corresponding dispatcher addition will
    // surface as a parity-harness failure pointing back at this list.
    vta_sdk::trust_tasks::TASK_DID_MANAGEMENT_DID_REGISTER_0_1,
    vta_sdk::trust_tasks::TASK_DID_MANAGEMENT_DID_PUBLISH_0_1,
    vta_sdk::trust_tasks::TASK_DID_MANAGEMENT_DID_DELETE_0_1,
    vta_sdk::trust_tasks::TASK_DID_MANAGEMENT_DID_ENABLE_0_1,
    vta_sdk::trust_tasks::TASK_DID_MANAGEMENT_DID_DISABLE_0_1,
    vta_sdk::trust_tasks::TASK_DID_MANAGEMENT_DID_LIST_0_1,
    vta_sdk::trust_tasks::TASK_DID_MANAGEMENT_DID_INFO_0_1,
    vta_sdk::trust_tasks::TASK_DID_MANAGEMENT_DID_CHECK_NAME_0_1,
    vta_sdk::trust_tasks::TASK_DID_MANAGEMENT_DID_CHANGE_OWNER_0_1,
    vta_sdk::trust_tasks::TASK_DID_MANAGEMENT_DID_ROLLBACK_0_1,
    vta_sdk::trust_tasks::TASK_DID_MANAGEMENT_DID_PROBLEM_REPORT_0_1,
    vta_sdk::trust_tasks::TASK_DID_MANAGEMENT_DOMAIN_CREATE_0_1,
    vta_sdk::trust_tasks::TASK_DID_MANAGEMENT_DOMAIN_UPDATE_0_1,
    vta_sdk::trust_tasks::TASK_DID_MANAGEMENT_DOMAIN_DISABLE_0_1,
    vta_sdk::trust_tasks::TASK_DID_MANAGEMENT_DOMAIN_PURGE_0_1,
    vta_sdk::trust_tasks::TASK_DID_MANAGEMENT_DOMAIN_SET_DEFAULT_0_1,
    vta_sdk::trust_tasks::TASK_DID_MANAGEMENT_DOMAIN_ASSIGN_0_1,
    vta_sdk::trust_tasks::TASK_DID_MANAGEMENT_DOMAIN_UNASSIGN_0_1,
    vta_sdk::trust_tasks::TASK_DID_MANAGEMENT_SERVER_REGISTER_0_1,
    vta_sdk::trust_tasks::TASK_DID_MANAGEMENT_SERVER_HEALTH_0_1,
    vta_sdk::trust_tasks::TASK_DID_MANAGEMENT_SERVER_STATS_SYNC_0_1,
    vta_sdk::trust_tasks::TASK_DID_MANAGEMENT_REGISTRY_ADMIN_REGISTER_0_1,
    vta_sdk::trust_tasks::TASK_DID_MANAGEMENT_REGISTRY_DEREGISTER_0_1,
];

/// Declarative Trust-Task dispatch table.
///
/// Each entry is `URI(s) => slice::handler`. From one list the macro generates
/// **both** [`dispatch_typed`]'s `match` arms **and** (test-only) the
/// `dispatched_uris()` parity list — so a handler and its parity entry are the
/// same declaration and cannot drift. Adding a slice is one line.
///
/// Supported per entry:
/// - `#[cfg(...)]` attributes (feature-gated arms contribute to the parity
///   list only when their cfg is active — mirrors the prior per-slice consts;
///   the URI must also sit in [`KNOWN_FEATURE_GATED_URIS`] for builds with the
///   feature off);
/// - `A | B => handler` for dual-accepted URIs sharing one handler.
///
/// Every handler has the uniform `(&AppState, &AuthClaims, TrustTask<Value>)
/// -> Response` signature; the dispatcher spine ([`dispatch_trust_task_core`])
/// keeps `validate_basic` + the 0.2 down/up-convert.
macro_rules! dispatch_table {
    (
        $(
            $(#[$meta:meta])*
            $($uri:path)|+ => $handler:path
        ),+ $(,)?
    ) => {
        /// Type-dispatch over the inbound document's `type` URI; generated by
        /// [`dispatch_table!`]. Unknown URIs fall through to `method_not_found`
        /// (`unsupported_type` per the framework's status table).
        ///
        /// `#[allow(deprecated)]`: arms match deprecated `*_0_1` URI constants
        /// on purpose — the VTA keeps serving 0.1 during the migration; 0.2
        /// counterparts arrive pre-down-converted (see `wire_v0_2`).
        #[allow(deprecated)]
        async fn dispatch_typed(
            state: &AppState,
            auth: &AuthClaims,
            doc: TrustTask<Value>,
        ) -> TrustTaskOutcome {
            let type_uri = doc.type_uri.to_string();
            match type_uri.as_str() {
                $(
                    $(#[$meta])*
                    $($uri)|+ => $handler(state, auth, doc).await,
                )+
                // A client mistakenly sending a REST-routed URI through the
                // envelope path gets `unsupported_type` here — correct from the
                // dispatcher's POV; the operation lives elsewhere.
                _ => method_not_found(doc, &type_uri),
            }
        }

        /// URIs wired into [`dispatch_typed`], collected from the same
        /// declarations that generate the match arms. Feature-gated arms
        /// contribute only when their cfg is active.
        #[cfg(test)]
        #[allow(deprecated)]
        fn dispatched_uris() -> Vec<&'static str> {
            let mut v: Vec<&'static str> = Vec::new();
            $(
                $(#[$meta])*
                v.extend([$($uri),+]);
            )+
            v
        }
    };
}

/// `POST /api/trust-tasks` handler.
///
/// Bearer-auth'd via [`AuthClaims`]; the caller's DID is the
/// transport-authenticated peer for SPEC.md §4.8.1 precedence inside
/// each typed handler.
///
/// Body is accepted as raw bytes so a parse failure surfaces as a
/// `trust-task-error/0.1` document with `code: malformed_request`
/// rather than axum's text/plain default. The route mount caps body
/// size separately (the workspace-wide 1 MB cap applies).
pub async fn dispatch_trust_task(
    auth: AuthClaims,
    State(state): State<AppState>,
    body: axum::body::Bytes,
) -> Result<Response, AppError> {
    Ok(dispatch_trust_task_core(&state, &auth, &body)
        .await
        .into_response())
}

/// Transport-agnostic trust-task dispatch core.
///
/// Parses the envelope bytes and dispatches by `type` URI, returning a
/// typed [`TrustTaskOutcome`] — the framework result/error document bytes
/// plus the status code from the framework's status table. Shared by:
/// - the REST route [`dispatch_trust_task`], which renders it via
///   `IntoResponse`, and
/// - the DIDComm trust-task handler
///   (`crate::messaging::handlers::handle_trust_task`), which reads
///   `outcome.body` straight as the reply envelope — no round-trip through
///   an `axum::Response` to re-extract the JSON.
///
/// `body` is the full `TrustTask<Value>` envelope JSON — the HTTP POST
/// body on REST, the DIDComm message body on DIDComm.
pub(crate) async fn dispatch_trust_task_core(
    state: &AppState,
    auth: &AuthClaims,
    body: &[u8],
) -> TrustTaskOutcome {
    // 1. Parse the envelope.
    let doc: TrustTask<Value> = match serde_json::from_slice(body) {
        Ok(d) => d,
        Err(e) => return body_parse_error_response(&e.to_string()),
    };

    // 2. Framework §7.2 items 4 + 5 — expiry + recipient
    //    enforcement. Closes L5 from the May 2026 security
    //    review: the hand-rolled dispatcher previously skipped
    //    these, so a Trust-Task envelope addressed at a
    //    different recipient would be silently accepted and an
    //    expired envelope would be honoured.
    //
    //    Audience binding (proof + recipient required for non-
    //    bearer specs, framework §7.2 item 8) is typed —
    //    `enforce_audience_binding` needs `P: Payload`, so each
    //    slice's typed handler runs it after `parse_payload`.
    {
        let vta_did = state.config.read().await.vta_did.clone();
        if let Some(my_vid) = vta_did.as_deref()
            && let Err(reason) = doc.validate_basic(chrono::Utc::now(), my_vid)
        {
            return reject_with(&doc, reason);
        }
        // No vta_did configured → service is in setup; skip
        // the recipient check (no identity to bind against).
        // Production VTAs always have vta_did set by `vta setup`.
    }

    // 3. Session-pubkey binding pre-check.
    //
    // Once `AuthClaims` carries `session_pubkey_b58btc` (Phase 3 work,
    // mirrors `webvh-service`'s pattern) the dispatcher will enforce
    // that the proof's `verificationMethod` matches the JWT-bound
    // pubkey before any handler runs. Phase 2 scaffold elides this —
    // no passkey-bound sessions exist yet on the VTA side.
    let _ = auth;

    // 4. Dispatch by type URI.
    //
    // 0.2 dual-accept: bearer-authed specs whose only 0.1→0.2 delta is
    // enum-value casing are down-converted to their canonical 0.1 form,
    // dispatched through the existing 0.1 handler, and the response
    // up-converted back to 0.2 (see `wire_v0_2`). Signed-payload specs are NOT
    // routed here — they have typed 0.2 arms in `dispatch_typed`.
    // The negotiated wire version is scoped around `dispatch_typed` via a
    // `task_local` so the two JWE-sealing handlers (`vault/release`,
    // `vault/proxy-login`) can serialise the *sealed* cleartext in the right
    // casing — the edge transform can't reach inside ciphertext. Every other
    // handler ignores it.
    use wire_v0_2::{WIRE_VERSION, WireVersion};
    let type_uri = doc.type_uri.to_string();

    // Blanket vault audit: capture the audit context BEFORE `doc` is moved
    // into dispatch. Every password-vault and credential-vault task — read or
    // write, success or denied — produces exactly one persisted audit row here
    // (the one place that sees the type URI, the authenticated actor, and the
    // final outcome). Non-vault tasks audit through their own handlers/ops.
    let vault_audit = vault_audit_action(&type_uri).map(|action| {
        let resource = vault_audit_resource(&doc.payload);
        let context_id = doc
            .payload
            .get("contextId")
            .and_then(Value::as_str)
            .map(str::to_string);
        // Operator-supplied rationale (the `reason` field that delete/archive/
        // restore/purge carry) — persisted so "audit the reason" is satisfied.
        let detail = doc
            .payload
            .get("reason")
            .and_then(Value::as_str)
            .map(str::to_string);
        (action, resource, context_id, detail)
    });

    let outcome = if let Some(spec) = wire_v0_2::lookup_0_2(&type_uri) {
        let mut doc = doc;
        wire_v0_2::downconvert_request(&mut doc.payload, spec);
        if let Ok(uri_0_1) = spec.uri_0_1.parse() {
            doc.type_uri = uri_0_1;
        }
        let outcome = WIRE_VERSION
            .scope(WireVersion::V0_2, dispatch_typed(state, auth, doc))
            .await;
        wire_v0_2::upconvert_response(outcome, spec)
    } else {
        WIRE_VERSION
            .scope(WireVersion::V0_1, dispatch_typed(state, auth, doc))
            .await
    };

    if let Some((action, resource, context_id, detail)) = vault_audit {
        let label = vault_audit_outcome_label(&outcome);
        if let Err(e) = crate::audit::record_with_detail(
            &state.audit_ks,
            &action,
            &auth.did,
            resource.as_deref(),
            &label,
            Some(helpers::TRANSPORT_TRUST_TASK),
            context_id.as_deref(),
            detail.as_deref(),
        )
        .await
        {
            // Audit is best-effort: a failed write must never fail the op.
            tracing::warn!(error = %e, action = %action, "vault audit record failed");
        }
    }

    outcome
}

/// Audit action string for a vault-family Trust Task, or `None` for any task
/// outside the vault family (those audit through their own handlers/ops).
///
/// `…/spec/vault/<verb>/<ver>` → `vault.<verb>` (e.g. `vault.delete`);
/// `…/spec/vault/credentials/<verb>/<ver>` → `vault.cred.<verb>`. Version is
/// ignored, so a 0.2 password-vault URI and its 0.1 form audit identically.
fn vault_audit_action(type_uri: &str) -> Option<String> {
    let rest = type_uri.split("/spec/vault/").nth(1)?;
    let segs: Vec<&str> = rest.split('/').filter(|s| !s.is_empty()).collect();
    match segs.as_slice() {
        ["credentials", verb, ..] => Some(format!("vault.cred.{verb}")),
        [verb, ..] => Some(format!("vault.{verb}")),
        _ => None,
    }
}

/// Best-effort resource id for the audit row, pulled generically from the
/// request payload (`id` / `entryId` / `credentialId`). `None` for list/query
/// tasks that carry no single-entry id.
fn vault_audit_resource(payload: &Value) -> Option<String> {
    for key in ["id", "entryId", "credentialId"] {
        if let Some(v) = payload.get(key).and_then(Value::as_str) {
            return Some(v.to_string());
        }
    }
    None
}

/// Map a dispatch outcome to an audit outcome label: `"success"` on a 2xx,
/// otherwise `"denied:<code>"` with the framework reject code lifted from the
/// error document (falling back to `"denied"` if it can't be read). The audit
/// sink keys INFO vs ERROR on the `"success"` prefix.
fn vault_audit_outcome_label(outcome: &TrustTaskOutcome) -> String {
    if outcome.status.is_success() {
        return "success".to_string();
    }
    if let Ok(v) = serde_json::from_slice::<Value>(&outcome.body)
        && let Some(code) = v
            .get("payload")
            .and_then(|p| p.get("code"))
            .and_then(Value::as_str)
    {
        return format!("denied:{code}");
    }
    "denied".to_string()
}

/// Build a Trust-Task rejection `Response` for a request whose envelope
/// bytes are in `body`, WITHOUT dispatching it.
///
/// The DIDComm trust-task handler uses this when it can't authorize the
/// transport peer (no ACL entry), so the reply is still a proper
/// Trust-Task error document — not a DIDComm problem-report, which a
/// conformant Trust-Task client can't read. (On REST the JWT extractor
/// rejects unauthenticated callers before dispatch, so this gap is
/// DIDComm-only — hence the feature gate.)
#[cfg(feature = "didcomm")]
pub(crate) fn reject_trust_task(body: &[u8], reason: RejectReason) -> TrustTaskOutcome {
    match serde_json::from_slice::<TrustTask<Value>>(body) {
        Ok(doc) => reject_with(&doc, reason),
        Err(e) => body_parse_error_response(&e.to_string()),
    }
}

// Note: `passkey-login-{start,finish}/1.0`, `challenge/1.0`,
// `authenticate/1.0`, and `refresh/1.0` are NOT in this table. They are
// UNAUTHENTICATED operations served as dedicated REST routes (`/auth/*`) — the
// user has no session JWT, so they can't pass `AuthClaims` through the
// dispatcher's extractor. The parity harness's `REST_ROUTED` allowlist tracks
// them.
dispatch_table! {
    // ─── Auth slice (authenticated operations) ───────────────────
    vta_sdk::trust_tasks::TASK_AUTH_REVOKE_SESSION_0_1 => auth::handle_revoke_session,
    vta_sdk::trust_tasks::TASK_AUTH_WHOAMI_0_1 => auth::handle_whoami,
    vta_sdk::trust_tasks::TASK_AUTH_SESSIONS_LIST_0_1 => auth::handle_sessions_list,
    // Dual-accept: both versions route to the same typed handler, which
    // normalises the `evidence.kind` discriminator on a copy (the signed
    // document is never mutated). Not edge-transformed in `wire_v0_2` because
    // the payload carries the approver's signature.
    vta_sdk::trust_tasks::TASK_AUTH_STEP_UP_APPROVE_RESPONSE_0_1
        | vta_sdk::trust_tasks::TASK_AUTH_STEP_UP_APPROVE_RESPONSE_0_2
        => step_up::handle_approve_response,
    vta_sdk::trust_tasks::TASK_AUTH_STEP_UP_POLICY_0_2 => step_up_policy::handle_set_step_up_policy,
    // ─── Consent slice ────────────────────────────────────────────
    vta_sdk::trust_tasks::TASK_CONSENT_REQUEST_1_0 => consent::handle_request,
    vta_sdk::trust_tasks::TASK_CONSENT_DECISION_1_0 => consent::handle_decision,
    vta_sdk::trust_tasks::TASK_CONSENT_REVOKE_1_0 => consent::handle_revoke,
    vta_sdk::trust_tasks::TASK_CONSENT_LIST_1_0 => consent::handle_list,
    vta_sdk::trust_tasks::TASK_CONSENT_APPROVER_SET_1_0 => consent::handle_approver_set,
    vta_sdk::trust_tasks::TASK_CONSENT_APPROVER_LIST_1_0 => consent::handle_approver_list,
    // ─── ACL slice ────────────────────────────────────────────────
    vta_sdk::trust_tasks::TASK_ACL_LIST_1_0 => acl::handle_list,
    vta_sdk::trust_tasks::TASK_ACL_CREATE_1_0 => acl::handle_create,
    vta_sdk::trust_tasks::TASK_ACL_GET_1_0 => acl::handle_get,
    vta_sdk::trust_tasks::TASK_ACL_UPDATE_1_0 => acl::handle_update,
    vta_sdk::trust_tasks::TASK_ACL_DELETE_1_0 => acl::handle_delete,
    // ─── Device slice ─────────────────────────────────────────────
    vta_sdk::trust_tasks::TASK_DEVICE_REGISTER_0_1 => device::handle_register,
    vta_sdk::trust_tasks::TASK_DEVICE_HEARTBEAT_0_1 => device::handle_heartbeat,
    vta_sdk::trust_tasks::TASK_DEVICE_LIST_0_1 => device::handle_list,
    vta_sdk::trust_tasks::TASK_DEVICE_DISABLE_0_1 => device::handle_disable,
    vta_sdk::trust_tasks::TASK_DEVICE_WIPE_0_1 => device::handle_wipe,
    vta_sdk::trust_tasks::TASK_DEVICE_SET_WAKE_0_1 => device::handle_set_wake,
    // ─── Contexts slice ──────────────────────────────────────────
    vta_sdk::trust_tasks::TASK_CONTEXTS_LIST_1_0 => contexts::handle_list,
    vta_sdk::trust_tasks::TASK_CONTEXTS_CREATE_1_0 => contexts::handle_create,
    vta_sdk::trust_tasks::TASK_CONTEXTS_GET_1_0 => contexts::handle_get,
    vta_sdk::trust_tasks::TASK_CONTEXTS_UPDATE_1_0 => contexts::handle_update,
    vta_sdk::trust_tasks::TASK_CONTEXTS_UPDATE_DID_1_0 => contexts::handle_update_did,
    vta_sdk::trust_tasks::TASK_CONTEXTS_PREVIEW_DELETE_1_0 => contexts::handle_preview_delete,
    vta_sdk::trust_tasks::TASK_CONTEXTS_DELETE_1_0 => contexts::handle_delete,
    // ─── Keys slice ──────────────────────────────────────────────
    vta_sdk::trust_tasks::TASK_KEYS_LIST_1_0 => keys::handle_list,
    vta_sdk::trust_tasks::TASK_KEYS_CREATE_1_0 => keys::handle_create,
    vta_sdk::trust_tasks::TASK_KEYS_GET_1_0 => keys::handle_get,
    vta_sdk::trust_tasks::TASK_KEYS_RENAME_1_0 => keys::handle_rename,
    vta_sdk::trust_tasks::TASK_KEYS_REVOKE_1_0 => keys::handle_revoke,
    vta_sdk::trust_tasks::TASK_KEYS_SIGN_1_0 => keys::handle_sign,
    // ─── Seeds slice ─────────────────────────────────────────────
    vta_sdk::trust_tasks::TASK_SEEDS_LIST_1_0 => seeds::handle_list,
    vta_sdk::trust_tasks::TASK_SEEDS_ROTATE_1_0 => seeds::handle_rotate,
    vta_sdk::trust_tasks::TASK_SEEDS_EXPORT_MNEMONIC_1_0 => seeds::handle_export_mnemonic,
    // ─── Audit slice ─────────────────────────────────────────────
    vta_sdk::trust_tasks::TASK_AUDIT_LIST_LOGS_1_0 => audit::handle_list_logs,
    vta_sdk::trust_tasks::TASK_AUDIT_GET_RETENTION_1_0 => audit::handle_get_retention,
    vta_sdk::trust_tasks::TASK_AUDIT_UPDATE_RETENTION_1_0 => audit::handle_update_retention,
    // ─── Discovery ───────────────────────────────────────────────
    vta_sdk::trust_tasks::TASK_DISCOVERY_CAPABILITIES_1_0 => discovery::handle_capabilities,
    // ─── Credential-exchange: deferred-presentation approval ─────
    //
    // The holder operator's out-of-band surface over deferred presentations.
    // The `credential-exchange/*` family keeps its URIs in
    // `vta_sdk::protocols::credential_exchange`, not the central `trust_tasks`
    // registry — so these sit outside the `ALL_URIS` parity harness (like the
    // `query`/`present` message types), but are still tracked by
    // `dispatched_uris()` (harmless extra entries).
    vta_sdk::protocols::credential_exchange::PENDING_LIST
        => credential_exchange::handle_pending_list,
    vta_sdk::protocols::credential_exchange::PENDING_APPROVE
        => credential_exchange::handle_pending_approve,
    vta_sdk::protocols::credential_exchange::PENDING_DENY
        => credential_exchange::handle_pending_deny,
    // ─── Vault slice (public 0.1 spec) ──────────────────────────
    vta_sdk::trust_tasks::TASK_VAULT_LIST_0_1 => vault::handle_list,
    vta_sdk::trust_tasks::TASK_VAULT_GET_0_1 => vault::handle_get,
    vta_sdk::trust_tasks::TASK_VAULT_UPSERT_0_1 => vault::handle_upsert,
    vta_sdk::trust_tasks::TASK_VAULT_DELETE_0_1 => vault::handle_delete,
    vta_sdk::trust_tasks::TASK_VAULT_RELEASE_0_1 => vault::handle_release,
    vta_sdk::trust_tasks::TASK_VAULT_PROXY_LOGIN_0_1 => vault::handle_proxy_login,
    vta_sdk::trust_tasks::TASK_VAULT_SIGN_TRUST_TASK_0_1 => vault::handle_sign_trust_task,
    // Vault archival lifecycle (openvtc extension). `delete` above is now soft.
    vta_sdk::trust_tasks::TASK_VAULT_ARCHIVE_0_1 => vault::handle_archive,
    vta_sdk::trust_tasks::TASK_VAULT_UNARCHIVE_0_1 => vault::handle_unarchive,
    vta_sdk::trust_tasks::TASK_VAULT_RESTORE_0_1 => vault::handle_restore,
    vta_sdk::trust_tasks::TASK_VAULT_PURGE_0_1 => vault::handle_purge,

    vta_sdk::trust_tasks::TASK_VAULT_CREDENTIALS_RECEIVE_0_1 => cred_vault::handle_receive,
    vta_sdk::trust_tasks::TASK_VAULT_CREDENTIALS_QUERY_0_1 => cred_vault::handle_query,
    vta_sdk::trust_tasks::TASK_VAULT_CREDENTIALS_GET_0_1 => cred_vault::handle_get,
    // Credential archival lifecycle (openvtc extension; CredentialWrite-gated).
    vta_sdk::trust_tasks::TASK_VAULT_CREDENTIALS_ARCHIVE_0_1 => cred_vault::handle_archive,
    vta_sdk::trust_tasks::TASK_VAULT_CREDENTIALS_UNARCHIVE_0_1 => cred_vault::handle_unarchive,
    vta_sdk::trust_tasks::TASK_VAULT_CREDENTIALS_DELETE_0_1 => cred_vault::handle_delete,
    vta_sdk::trust_tasks::TASK_VAULT_CREDENTIALS_RESTORE_0_1 => cred_vault::handle_restore,
    vta_sdk::trust_tasks::TASK_VAULT_CREDENTIALS_PURGE_0_1 => cred_vault::handle_purge,
    // ─── Config slice ────────────────────────────────────────────
    vta_sdk::trust_tasks::TASK_CONFIG_GET_1_0 => config::handle_get,
    vta_sdk::trust_tasks::TASK_CONFIG_UPDATE_1_0 => config::handle_update,
    // ─── Management slice ────────────────────────────────────────
    vta_sdk::trust_tasks::TASK_MANAGEMENT_RELOAD_SERVICES_1_0 => management::handle_reload_services,
    // ─── Backup slice (descriptor pattern) ───────────────────────
    vta_sdk::trust_tasks::TASK_BACKUP_INITIATE_EXPORT_1_0 => backup::handle_initiate_export,
    vta_sdk::trust_tasks::TASK_BACKUP_COMPLETE_EXPORT_1_0 => backup::handle_complete_export,
    vta_sdk::trust_tasks::TASK_BACKUP_INITIATE_IMPORT_1_0 => backup::handle_initiate_import,
    vta_sdk::trust_tasks::TASK_BACKUP_FINALIZE_IMPORT_1_0 => backup::handle_finalize_import,
    vta_sdk::trust_tasks::TASK_BACKUP_ABORT_1_0 => backup::handle_abort,
    // ─── DID-templates slice (global) ────────────────────────────
    vta_sdk::trust_tasks::TASK_DID_TEMPLATES_LIST_1_0 => did_templates::handle_list,
    vta_sdk::trust_tasks::TASK_DID_TEMPLATES_CREATE_1_0 => did_templates::handle_create,
    vta_sdk::trust_tasks::TASK_DID_TEMPLATES_GET_1_0 => did_templates::handle_get,
    vta_sdk::trust_tasks::TASK_DID_TEMPLATES_UPDATE_1_0 => did_templates::handle_update,
    vta_sdk::trust_tasks::TASK_DID_TEMPLATES_DELETE_1_0 => did_templates::handle_delete,
    vta_sdk::trust_tasks::TASK_DID_TEMPLATES_RENDER_1_0 => did_templates::handle_render,
    // ─── DID-templates slice (context-scoped) ────────────────────
    vta_sdk::trust_tasks::TASK_CONTEXTS_DID_TEMPLATES_LIST_1_0 => did_templates::handle_context_list,
    vta_sdk::trust_tasks::TASK_CONTEXTS_DID_TEMPLATES_CREATE_1_0
        => did_templates::handle_context_create,
    vta_sdk::trust_tasks::TASK_CONTEXTS_DID_TEMPLATES_GET_1_0 => did_templates::handle_context_get,
    vta_sdk::trust_tasks::TASK_CONTEXTS_DID_TEMPLATES_UPDATE_1_0
        => did_templates::handle_context_update,
    vta_sdk::trust_tasks::TASK_CONTEXTS_DID_TEMPLATES_DELETE_1_0
        => did_templates::handle_context_delete,
    vta_sdk::trust_tasks::TASK_CONTEXTS_DID_TEMPLATES_RENDER_1_0
        => did_templates::handle_context_render,
    // ─── Passkey-VMs slice (feature-gated: webvh + didcomm) ─────
    //
    // Canonical 0.1 only — the pre-spec 1.0 aliases were removed (the browser
    // plugin migrated to 0.1; a 1.0 doc now gets UnsupportedType).
    #[cfg(all(feature = "webvh", feature = "didcomm"))]
    vta_sdk::trust_tasks::TASK_PASSKEY_VMS_ENROLL_CHALLENGE_0_1
        => passkey_vms::handle_enroll_challenge,
    #[cfg(all(feature = "webvh", feature = "didcomm"))]
    vta_sdk::trust_tasks::TASK_PASSKEY_VMS_ENROLL_SUBMIT_0_1 => passkey_vms::handle_enroll_submit,
    #[cfg(all(feature = "webvh", feature = "didcomm"))]
    vta_sdk::trust_tasks::TASK_PASSKEY_VMS_LIST_0_1 => passkey_vms::handle_list,
    #[cfg(all(feature = "webvh", feature = "didcomm"))]
    vta_sdk::trust_tasks::TASK_PASSKEY_VMS_REVOKE_0_1 => passkey_vms::handle_revoke,
    // ─── Provision-integration (feature-gated: webvh) ────────────
    #[cfg(feature = "webvh")]
    vta_sdk::trust_tasks::TASK_PROVISION_INTEGRATION_REQUEST_1_0
        => provision_integration::handle_request,
    // ─── WebVH-DID-lifecycle slice (feature-gated: webvh) ────────
    #[cfg(feature = "webvh")]
    vta_sdk::trust_tasks::TASK_WEBVH_SERVERS_LIST_1_0 => webvh::handle_servers_list,
    #[cfg(feature = "webvh")]
    vta_sdk::trust_tasks::TASK_WEBVH_SERVERS_ADD_1_0 => webvh::handle_servers_add,
    #[cfg(feature = "webvh")]
    vta_sdk::trust_tasks::TASK_WEBVH_SERVERS_UPDATE_1_0 => webvh::handle_servers_update,
    #[cfg(feature = "webvh")]
    vta_sdk::trust_tasks::TASK_WEBVH_SERVERS_REMOVE_1_0 => webvh::handle_servers_remove,
    #[cfg(feature = "webvh")]
    vta_sdk::trust_tasks::TASK_WEBVH_DIDS_LIST_1_0 => webvh::handle_dids_list,
    #[cfg(feature = "webvh")]
    vta_sdk::trust_tasks::TASK_WEBVH_DIDS_CREATE_1_0 => webvh::handle_dids_create,
    #[cfg(feature = "webvh")]
    vta_sdk::trust_tasks::TASK_WEBVH_DIDS_GET_1_0 => webvh::handle_dids_get,
    #[cfg(feature = "webvh")]
    vta_sdk::trust_tasks::TASK_WEBVH_DIDS_GET_LOG_1_0 => webvh::handle_dids_get_log,
    #[cfg(feature = "webvh")]
    vta_sdk::trust_tasks::TASK_WEBVH_DIDS_DELETE_1_0 => webvh::handle_dids_delete,
    #[cfg(feature = "webvh")]
    vta_sdk::trust_tasks::TASK_WEBVH_DIDS_UPDATE_1_0 => webvh::handle_dids_update,
    #[cfg(feature = "webvh")]
    vta_sdk::trust_tasks::TASK_WEBVH_DIDS_ROTATE_KEYS_1_0 => webvh::handle_dids_rotate_keys,
    #[cfg(feature = "webvh")]
    vta_sdk::trust_tasks::TASK_WEBVH_DIDS_REGISTER_WITH_SERVER_1_0
        => webvh::handle_dids_register_with_server,
}

#[cfg(test)]
mod tests {
    //! Smoke tests for the dispatcher's wire-shape contracts + the
    //! cross-crate URI parity harness. Each arm's actual handler
    //! logic is tested in its owning operations module (or by the
    //! Phase 5 integration suite once full AppState scaffolding is
    //! in place).

    use trust_tasks_rs::TrustTask;

    use super::*;

    #[test]
    fn body_parse_error_wire_shape() {
        let resp = body_parse_error_response("expected `,`");
        // Function returns; full HTTP-shape assertions live in the
        // Phase 5 integration tests once the route is reachable
        // through a real router setup.
        let _ = resp;
    }

    /// Pins the framework's current `TypeUri::from_str` constraint:
    /// the wire-format `type` field MUST use the canonical
    /// `/spec/<slug>/<major.minor>` shape. Flat URIs are rejected.
    ///
    /// If the framework parser relaxes (accepts both), the test fails
    /// on the flat-rejection assert and we know Phase 3 can simplify.
    #[test]
    fn framework_requires_canonical_uri_in_wire_type_field() {
        // Canonical form parses — with HIERARCHICAL slug
        // (`vta/auth/revoke-session`) per SPEC.md slug grammar.
        let canonical = serde_json::json!({
            "id": "urn:uuid:00000000-0000-0000-0000-000000000001",
            "type": "https://trusttasks.org/spec/auth/revoke-session/0.1",
            "issuer": "did:example:alice",
            "recipient": "did:example:vta",
            "issuedAt": "2026-05-20T00:00:00Z",
            "payload": { "session_id": "sess-1" }
        });
        let bytes = serde_json::to_vec(&canonical).unwrap();
        let parsed: Result<TrustTask<Value>, _> = serde_json::from_slice(&bytes);
        assert!(
            parsed.is_ok(),
            "canonical URI must parse: {:?}",
            parsed.err()
        );

        // Flat form is rejected.
        let flat = serde_json::json!({
            "id": "urn:uuid:00000000-0000-0000-0000-000000000001",
            "type": "https://trusttasks.org/vta/auth/revoke-session/1.0",
            "issuer": "did:example:alice",
            "recipient": "did:example:vta",
            "issuedAt": "2026-05-20T00:00:00Z",
            "payload": { "session_id": "sess-1" }
        });
        let bytes = serde_json::to_vec(&flat).unwrap();
        let parsed: Result<TrustTask<Value>, _> = serde_json::from_slice(&bytes);
        assert!(
            parsed.is_err(),
            "flat URI must NOT parse — if this changes, the framework \
             relaxed its parser and Phase 3 design can simplify"
        );
    }

    #[test]
    #[allow(deprecated)] // names the dual-accepted passkey-login 0.1 URIs on purpose
    fn phase_2_uri_registry_present() {
        // Compile-time check: every URI we route in `dispatch_typed`
        // is declared in `vta-sdk::trust_tasks`. If a URI gets renamed
        // or removed in vta-sdk, this stops compiling.
        let _ = vta_sdk::trust_tasks::TASK_AUTH_CHALLENGE_0_1;
        let _ = vta_sdk::trust_tasks::TASK_AUTH_AUTHENTICATE_0_1;
        let _ = vta_sdk::trust_tasks::TASK_AUTH_REFRESH_0_1;
        let _ = vta_sdk::trust_tasks::TASK_AUTH_REVOKE_SESSION_0_1;
        let _ = vta_sdk::trust_tasks::TASK_AUTH_WHOAMI_0_1;
        let _ = vta_sdk::trust_tasks::TASK_AUTH_SESSIONS_LIST_0_1;
        let _ = vta_sdk::trust_tasks::TASK_AUTH_PASSKEY_LOGIN_START_0_1;
        let _ = vta_sdk::trust_tasks::TASK_AUTH_PASSKEY_LOGIN_FINISH_0_1;
    }

    /// Cross-crate URI parity harness (mirrors webvh-service's T9
    /// invariant). Every URI declared in `vta-sdk::trust_tasks` must
    /// either:
    ///
    /// 1. Be tracked by `dispatched_uris()` (i.e. have a
    ///    [`dispatch_table!`] entry wiring its handler into `dispatch_typed`), OR
    /// 2. Be on the `REST_ROUTED` allowlist (served by dedicated
    ///    unauth REST handlers — passkey login, legacy challenge/
    ///    authenticate/refresh, TEE attestation), OR
    /// 3. Be on the `KNOWN_FEATURE_GATED_URIS` allowlist (feature-
    ///    flagged in vta-service and not compiled in this build).
    ///
    /// See `docs/05-design-notes/trust-task-feature-gating.md` for
    /// the full convention.
    ///
    /// Adding a new URI to `vta-sdk::trust_tasks::ALL_URIS` without
    /// doing one of these three fails this test loudly with the
    /// offending URI in the message.
    #[test]
    fn dispatcher_handles_every_vta_sdk_uri() {
        let dispatched = dispatched_uris();

        for declared in vta_sdk::trust_tasks::ALL_URIS {
            let in_dispatched = dispatched.contains(declared);
            let in_rest_routed = REST_ROUTED.contains(declared);
            let in_feature_gated = KNOWN_FEATURE_GATED_URIS.contains(declared);
            // 0.2 dual-accept URIs are served via the `wire_v0_2` edge
            // transform (down-convert → 0.1 handler → up-convert), not a
            // dedicated `dispatch_typed` arm, so they're tracked here.
            let in_wire_v0_2 = wire_v0_2::WIRE_V0_2_URIS.contains(declared);

            assert!(
                in_dispatched || in_rest_routed || in_feature_gated || in_wire_v0_2,
                "vta-sdk declares URI `{declared}` but it is not tracked in this dispatcher — \
                 either (a) add a `dispatch_table!` entry (`URI => slice::handler`), \
                 (b) add it to `REST_ROUTED` if it lives on a dedicated REST route, \
                 (c) add it to `KNOWN_FEATURE_GATED_URIS` with a comment explaining the gating, or \
                 (d) register it in `wire_v0_2::WIRE_V0_2_URIS` if it's an edge-transformed 0.2 URI"
            );
        }
    }

    /// Passkey-VMs: the canonical `…/0.1` URIs are dispatched. The pre-spec
    /// `…/1.0` aliases were removed (the browser plugin migrated to 0.1), so a
    /// 1.0 document now falls through to `UnsupportedType`.
    #[test]
    fn passkey_vms_0_1_dispatched() {
        let dispatched = dispatched_uris();
        let tracked = |u: &&str| dispatched.contains(u) || KNOWN_FEATURE_GATED_URIS.contains(u);
        for v0_1 in [
            vta_sdk::trust_tasks::TASK_PASSKEY_VMS_ENROLL_CHALLENGE_0_1,
            vta_sdk::trust_tasks::TASK_PASSKEY_VMS_ENROLL_SUBMIT_0_1,
            vta_sdk::trust_tasks::TASK_PASSKEY_VMS_LIST_0_1,
            vta_sdk::trust_tasks::TASK_PASSKEY_VMS_REVOKE_0_1,
        ] {
            assert!(tracked(&v0_1), "canonical 0.1 URI not dispatched: {v0_1}");
            assert!(v0_1.ends_with("/0.1"), "version-label mismatch for {v0_1}");
        }
    }

    /// Defensive guard against double-tracking. A URI should appear in
    /// exactly one of (`dispatched_uris()`, `REST_ROUTED`,
    /// `KNOWN_FEATURE_GATED_URIS`) — except that `KNOWN_FEATURE_GATED_URIS`
    /// redundantly mirrors a feature-gated `dispatch_table!` entry's URIs when
    /// the feature is on. That redundancy is allowed (the harness tolerates
    /// it); other overlaps would indicate confusion about which transport a URI
    /// uses.
    ///
    /// Specifically: a URI MUST NOT be in BOTH `dispatched_uris()`
    /// AND `REST_ROUTED`. That'd mean two handlers compete for it.
    #[test]
    fn no_uri_is_both_dispatched_and_rest_routed() {
        let dispatched = dispatched_uris();
        for uri in REST_ROUTED {
            assert!(
                !dispatched.contains(uri),
                "URI `{uri}` is in REST_ROUTED but also in a `dispatch_table!` entry — \
                 a URI must live on exactly one transport"
            );
        }
    }
}