vta-service 0.42.0

Service for Verifiable Trust Agents operating in Verifiable Trust Communities
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
//! DIDComm message dispatch for the delivery-layer inbound loop.
//!
//! **D2 P2a cut-over**: this used to build an
//! `affinidi-messaging-didcomm-service` `Router` (type-routed handler table +
//! `MessagePolicy` middleware) wrapped in a `BridgeHandler`. That framework is
//! gone. [`dispatch`] is now a plain `msg.typ` match that calls the same ~50
//! handler functions directly — they are unchanged, taking
//! `(HandlerContext, Message, Extension<T>)` from [`crate::messaging::shim`].
//! The [`crate::server`] inbound loop drives it off
//! [`affinidi_messaging_delivery::MessagingService::subscribe`].
//!
//! The `MessagePolicy` auth gate (`require_encrypted` + verified-sender-or-none)
//! now lives in the inbound loop, which sets `Message::from` to the
//! cryptographically-authenticated sender before calling [`dispatch`] (the
//! `#620` anti-spoof guarantee), so every handler's `auth_from_message` /
//! `ctx.sender_did` sees only a proven sender.

use std::sync::Arc;

use affinidi_messaging_didcomm::Message;
use tokio::sync::RwLock;

use affinidi_did_resolver_cache_sdk::DIDCacheClient;

use crate::config::AppConfig;
use crate::didcomm_bridge::DIDCommBridge;
use crate::keys::seed_store::SeedStore;
use crate::messaging::shim::{DIDCommResponse, DIDCommServiceError, HandlerContext, ProblemReport};
#[cfg(feature = "didcomm")]
use crate::messaging::shim::{Extension, ServiceProblemReport};
use crate::server::AppState;
use crate::store::KeyspaceHandle;

#[cfg(feature = "didcomm")]
use super::handlers;

#[cfg(all(feature = "tee", feature = "didcomm"))]
use vta_sdk::protocols::attestation_management;
#[cfg(all(feature = "webvh", feature = "didcomm"))]
use vta_sdk::protocols::did_management;
#[cfg(all(feature = "webvh", feature = "didcomm"))]
use vta_sdk::protocols::protocol_management;
// `provision-integration` is unconditionally enabled via the
// `vta-sdk` feature list in vta-service's Cargo.toml — no cfg gate.
#[cfg(all(feature = "webvh", feature = "didcomm"))]
use vta_sdk::protocols::provision_integration_management;
#[cfg(feature = "didcomm")]
use vta_sdk::protocols::{
    self, acl_management, audit_management, context_management, credential_exchange,
    key_management, seed_management, vta_management,
};

/// Trust-ping protocol identifiers (was the framework's `TRUST_PING_TYPE` /
/// `TRUST_PONG_TYPE`). Re-declared locally now the framework is gone.
#[cfg(feature = "didcomm")]
const TRUST_PING_TYPE: &str = "https://didcomm.org/trust-ping/2.0/ping";
#[cfg(feature = "didcomm")]
const TRUST_PONG_TYPE: &str = "https://didcomm.org/trust-ping/2.0/ping-response";
/// The high-frequency message-pickup status heartbeat (was the framework's
/// `MESSAGE_PICKUP_STATUS_TYPE`, routed to `ignore_handler`). Dispatched as a
/// silent no-op.
pub(crate) const MESSAGE_PICKUP_STATUS_TYPE: &str = "https://didcomm.org/messagepickup/3.0/status";

/// Shared state injected into all DIDComm handlers via `Extension<Arc<VtaState>>`.
#[derive(Clone)]
pub struct VtaState {
    pub keys_ks: KeyspaceHandle,
    pub acl_ks: KeyspaceHandle,
    /// Sessions keyspace — mirrored from `AppState` so intrinsic-sender
    /// (DIDComm/TSP) auth can resolve + elevate the caller's canonical
    /// DID-keyed session, exactly as the REST path does.
    pub sessions_ks: KeyspaceHandle,
    pub contexts_ks: KeyspaceHandle,
    pub did_templates_ks: KeyspaceHandle,
    pub audit_ks: KeyspaceHandle,
    /// Shared with `AppState` — one audit sink across both transports, so a
    /// deployment-installed backend covers DIDComm as well as REST. Cloned as
    /// an `Arc`, not rebuilt, for the same reason the config `RwLock` is (P1.1):
    /// two transports resolving audit differently is a gap you find in an
    /// incident.
    pub audit_sink: vta_audit::SharedAuditSink,
    pub imported_ks: KeyspaceHandle,
    /// Non-extractable internal signing keys, mirrored from `AppState` so the
    /// DIDComm signing oracle reaches the same keys the REST one does.
    pub internal_ks: KeyspaceHandle,
    /// Persistent runtime state for service enable/disable
    /// (`operations::protocol::runtime_state`). Mirrored from `AppState`.
    pub service_state_ks: KeyspaceHandle,
    #[cfg(feature = "webvh")]
    pub webvh_ks: KeyspaceHandle,
    /// Credentials the VTA issued — needed so a DID deletion over this
    /// transport can revoke them rather than orphan them.
    pub issued_credentials_ks: KeyspaceHandle,
    /// Anti-replay log for sealed-bootstrap `bundle_id`s — required by
    /// the DIDComm provision-integration handler so it can drive the
    /// same shared library function the REST handler does.
    pub sealed_nonces_ks: KeyspaceHandle,
    /// Persisted drain set for the protocol-management feature
    /// (`docs/05-design-notes/didcomm-protocol-management.md`).
    /// Accessible from DIDComm handlers so disable/migrate over
    /// DIDComm transport land in the same drain bookkeeping as
    /// the REST path.
    #[cfg(feature = "webvh")]
    pub drains_ks: KeyspaceHandle,
    /// Per-kind previous-config snapshot store for fail-forward
    /// rollback (spec §3.5a). Mirrored from `AppState` so REST and
    /// DIDComm transport handlers feed the same snapshot.
    #[cfg(feature = "webvh")]
    pub snapshot_ks: KeyspaceHandle,
    /// In-process registry of active + draining mediator listeners.
    #[cfg(feature = "webvh")]
    pub mediator_registry: Arc<crate::messaging::registry::MediatorListenerRegistry>,
    /// Per-mediator TTL sweeper.
    #[cfg(feature = "webvh")]
    pub drain_sweeper: Arc<crate::messaging::drain_sweeper::DrainSweeper>,
    /// Per-webvh-server async mutex registry. Mirrored from
    /// `AppState` so DIDComm-transport handlers serialise the same
    /// daemon-REST auth-cache reads as REST handlers.
    #[cfg(feature = "webvh")]
    pub webvh_auth_locks: crate::operations::did_webvh::WebvhAuthLocks,
    /// Pluggable telemetry sink — driven by both REST and DIDComm
    /// transport handlers so `mediator report` is consistent
    /// regardless of which transport posted the inbound event.
    pub telemetry: vti_common::telemetry::SharedTelemetrySink,
    pub seed_store: Arc<dyn SeedStore>,
    pub config: Arc<RwLock<AppConfig>>,
    pub did_resolver: Option<DIDCacheClient>,
    /// DIDComm bridge for outbound WebVH server communication.
    pub didcomm_bridge: Arc<DIDCommBridge>,
    /// Secrets resolver — present iff DIDComm is configured. Used
    /// (alongside `signing_vm_id` / `ka_vm_id`) by service-management
    /// rollback over DIDComm transport to assemble a live
    /// `ListenerProver` for re-promotion handshakes.
    #[cfg(feature = "didcomm")]
    pub secrets_resolver: Option<Arc<affinidi_tdk::secrets_resolver::ThreadedSecretsResolver>>,
    /// VM id of the VTA's signing key. Threaded through to the live
    /// prover for service-management ops dispatched over DIDComm.
    #[cfg(feature = "didcomm")]
    pub signing_vm_id: Option<String>,
    /// VM id of the VTA's key-agreement key.
    #[cfg(feature = "didcomm")]
    pub ka_vm_id: Option<String>,
    #[cfg(feature = "tee")]
    pub tee_state: Option<crate::tee::TeeState>,
    /// Send `true` to trigger a soft restart.
    pub restart_tx: tokio::sync::watch::Sender<bool>,
    /// Mirrored from `AppState` for backup and restore, which read every
    /// keyspace and stage into the unencrypted `bootstrap` one.
    pub store: vti_common::store::Store,
    pub storage_encryption_key: Option<[u8; 32]>,
    pub in_enclave: bool,
}

impl VtaState {
    /// What a backup or a restore needs from this VTA.
    pub fn backup_access(&self) -> crate::restore::BackupAccess<'_> {
        crate::restore::BackupAccess {
            store: &self.store,
            storage_key: self.storage_encryption_key,
            in_enclave: self.in_enclave,
            seed_store: self.seed_store.as_ref(),
            config: &self.config,
        }
    }
}

// Gated on `webvh`: provision-integration mints WebVH DIDs, so the op (and the
// DIDComm handler/route that drive it, below) only exist in webvh builds —
// matching the REST side (`routes::bootstrap`'s `#[cfg(feature = "webvh")] mod
// provision`). Without this gate the impl had to fill the cfg-gated
// `VtaState::webvh_ks` with a `panic!()` arm in non-webvh builds — a runtime
// landmine inside a `From`. Gating the impl removes it: a non-webvh build
// simply doesn't expose DIDComm provision-integration.
#[cfg(feature = "webvh")]
impl From<&VtaState> for crate::operations::provision_integration::ProvisionIntegrationDeps {
    fn from(state: &VtaState) -> Self {
        Self {
            keys_ks: state.keys_ks.clone(),
            acl_ks: state.acl_ks.clone(),
            audit: std::sync::Arc::clone(&state.audit_sink),
            contexts_ks: state.contexts_ks.clone(),
            did_templates_ks: state.did_templates_ks.clone(),
            imported_ks: state.imported_ks.clone(),
            webvh_ks: state.webvh_ks.clone(),
            sealed_nonces_ks: state.sealed_nonces_ks.clone(),
            seed_store: state.seed_store.clone(),
            config: state.config.clone(),
            did_resolver: state.did_resolver.clone(),
            didcomm_bridge: state.didcomm_bridge.clone(),
            webvh_auth_locks: state.webvh_auth_locks.clone(),
        }
    }
}

/// Derive the DIDComm-transport view of shared state from the canonical
/// [`AppState`].
///
/// `VtaState` is a strict subset of `AppState` — every field is a cheap clone
/// of the corresponding `AppState` field (an `Arc`, a `KeyspaceHandle`, or the
/// `Arc`-backed [`WebvhAuthLocks`]). Building it this way is what guarantees the
/// REST front-end and the DIDComm router share the *same* config `RwLock`,
/// `WebvhAuthLocks`, mediator registry, drain sweeper, and telemetry sink
/// (P1.1): a `PATCH /config` on the REST side is visible to DIDComm handlers,
/// and the per-server webvh auth-cache lock serialises across both transports.
/// Constructing `VtaState` with a freshly-minted webvh auth-lock registry or a
/// freshly-wrapped config lock was a live divergence bug — don't reintroduce
/// it; always derive from the canonical `AppState`.
impl From<&AppState> for VtaState {
    fn from(state: &AppState) -> Self {
        Self {
            keys_ks: state.keys_ks.clone(),
            acl_ks: state.acl_ks.clone(),
            sessions_ks: state.sessions_ks.clone(),
            contexts_ks: state.contexts_ks.clone(),
            did_templates_ks: state.did_templates_ks.clone(),
            audit_ks: state.audit_ks.clone(),
            audit_sink: std::sync::Arc::clone(&state.audit_sink),
            imported_ks: state.imported_ks.clone(),
            internal_ks: state.internal_ks.clone(),
            service_state_ks: state.service_state_ks.clone(),
            #[cfg(feature = "webvh")]
            webvh_ks: state.webvh_ks.clone(),
            issued_credentials_ks: state.issued_credentials_ks.clone(),
            sealed_nonces_ks: state.sealed_nonces_ks.clone(),
            #[cfg(feature = "webvh")]
            drains_ks: state.drains_ks.clone(),
            #[cfg(feature = "webvh")]
            snapshot_ks: state.snapshot_ks.clone(),
            #[cfg(feature = "webvh")]
            mediator_registry: Arc::clone(&state.mediator_registry),
            #[cfg(feature = "webvh")]
            drain_sweeper: Arc::clone(&state.drain_sweeper),
            #[cfg(feature = "webvh")]
            webvh_auth_locks: state.webvh_auth_locks.clone(),
            telemetry: Arc::clone(&state.telemetry),
            seed_store: state.seed_store.clone(),
            config: Arc::clone(&state.config),
            did_resolver: state.did_resolver.clone(),
            didcomm_bridge: Arc::clone(&state.didcomm_bridge),
            #[cfg(feature = "didcomm")]
            secrets_resolver: state.secrets_resolver.clone(),
            #[cfg(feature = "didcomm")]
            signing_vm_id: state.signing_vm_id.clone(),
            #[cfg(feature = "didcomm")]
            ka_vm_id: state.ka_vm_id.clone(),
            #[cfg(feature = "tee")]
            tee_state: state.tee.as_ref().map(|tc| tc.state.clone()),
            restart_tx: state.restart_tx.clone(),
            store: state.store.clone(),
            storage_encryption_key: state.storage_encryption_key,
            in_enclave: state.tee.is_some(),
        }
    }
}

// ---------------------------------------------------------------------------
// Type-routed dispatch (was the framework `Router` + `BridgeHandler`)
// ---------------------------------------------------------------------------

/// The handler return shape (unchanged from the framework): a reply, no reply,
/// or a handler error the dispatch renders as an `internal-error`
/// problem-report.
#[cfg(feature = "didcomm")]
type HandlerResult = Result<Option<DIDCommResponse>, DIDCommServiceError>;

/// Fold a handler's `Result` into the reply the loop sends. A handler `Err`
/// becomes a threaded `internal-error` problem-report (was the framework's
/// `DefaultErrorHandler::on_error`).
#[cfg(feature = "didcomm")]
fn finish(result: HandlerResult) -> Option<DIDCommResponse> {
    match result {
        Ok(opt) => opt,
        Err(e) => Some(DIDCommResponse::problem_report(
            ProblemReport::internal_error(e.to_string()),
        )),
    }
}

/// Local trust-ping responder (was the framework `trust_ping_handler`). Replies
/// a `trust-ping/2.0/ping-response` on the ping's thread unless the ping didn't
/// request a response or has no authenticated sender to reply to.
#[cfg(feature = "didcomm")]
fn trust_ping_reply(msg: &Message, sender_did: Option<&str>) -> Option<DIDCommResponse> {
    #[derive(serde::Deserialize)]
    struct PingBody {
        #[serde(default = "default_true")]
        response_requested: bool,
    }
    fn default_true() -> bool {
        true
    }
    let body: PingBody = serde_json::from_value(msg.body.clone()).unwrap_or(PingBody {
        response_requested: true,
    });
    if !body.response_requested {
        return None;
    }
    // Only pong an authenticated ping (no reply to a spoofed/anonymous sender).
    sender_did?;
    Some(DIDCommResponse::new(TRUST_PONG_TYPE, serde_json::Value::Null).thid(msg.id.clone()))
}

/// Route one inbound (authenticated-sender-stamped) DIDComm message to its
/// handler, mirroring the framework route list (same URIs, same feature gates).
///
/// `ctx.sender_did` and `msg.from` are the cryptographically-authenticated
/// sender (or `None`); handlers authorize on those, never on the raw wire
/// `from`. The `_` arm is the fallback (`handle_unknown`).
#[cfg(feature = "didcomm")]
pub async fn dispatch(
    msg: Message,
    ctx: HandlerContext,
    vta_state: Arc<VtaState>,
    app_state: AppState,
) -> Option<DIDCommResponse> {
    let t = msg.typ.clone();
    let t = t.as_str();

    // Message-pickup status heartbeat: silent no-op (was `ignore_handler`).
    if t == MESSAGE_PICKUP_STATUS_TYPE {
        return None;
    }
    // Trust-ping (was the built-in `trust_ping_handler`).
    if t == TRUST_PING_TYPE {
        return trust_ping_reply(&msg, ctx.sender_did.as_deref());
    }

    // ── Trust-Tasks envelope (AppState) ──────────────────────────────
    if t == trust_tasks_didcomm::ENVELOPE_TYPE {
        return finish(handlers::handle_trust_task(ctx, msg, Extension(app_state)).await);
    }

    // ── Key management ───────────────────────────────────────────────
    if t == key_management::CREATE_KEY {
        return finish(handlers::handle_create_key(ctx, msg, Extension(vta_state)).await);
    }
    if t == key_management::GET_KEY {
        return finish(handlers::handle_get_key(ctx, msg, Extension(vta_state)).await);
    }
    if t == key_management::LIST_KEYS {
        return finish(handlers::handle_list_keys(ctx, msg, Extension(vta_state)).await);
    }
    if t == key_management::RENAME_KEY {
        return finish(handlers::handle_rename_key(ctx, msg, Extension(vta_state)).await);
    }
    if t == key_management::REVOKE_KEY {
        return finish(handlers::handle_revoke_key(ctx, msg, Extension(vta_state)).await);
    }
    if t == key_management::GET_KEY_SECRET {
        return finish(handlers::handle_get_key_secret(ctx, msg, Extension(vta_state)).await);
    }
    if t == key_management::SIGN_REQUEST {
        return finish(handlers::handle_sign_request(ctx, msg, Extension(vta_state)).await);
    }

    // ── Seed management ──────────────────────────────────────────────
    if t == seed_management::LIST_SEEDS {
        return finish(handlers::handle_list_seeds(ctx, msg, Extension(vta_state)).await);
    }
    if t == seed_management::ROTATE_SEED {
        return finish(handlers::handle_rotate_seed(ctx, msg, Extension(vta_state)).await);
    }

    // ── Context management ───────────────────────────────────────────
    if t == context_management::CREATE_CONTEXT {
        return finish(handlers::handle_create_context(ctx, msg, Extension(vta_state)).await);
    }
    if t == context_management::GET_CONTEXT {
        return finish(handlers::handle_get_context(ctx, msg, Extension(vta_state)).await);
    }
    if t == context_management::LIST_CONTEXTS {
        return finish(handlers::handle_list_contexts(ctx, msg, Extension(vta_state)).await);
    }
    if t == context_management::UPDATE_CONTEXT {
        return finish(handlers::handle_update_context(ctx, msg, Extension(vta_state)).await);
    }
    if t == context_management::UPDATE_CONTEXT_DID {
        return finish(handlers::handle_update_context_did(ctx, msg, Extension(vta_state)).await);
    }
    if t == context_management::PREVIEW_DELETE_CONTEXT {
        return finish(
            handlers::handle_preview_delete_context(ctx, msg, Extension(vta_state)).await,
        );
    }
    if t == context_management::DELETE_CONTEXT {
        return finish(handlers::handle_delete_context(ctx, msg, Extension(vta_state)).await);
    }

    // ── ACL management ───────────────────────────────────────────────
    if t == acl_management::CREATE_ACL {
        return finish(handlers::handle_create_acl(ctx, msg, Extension(vta_state)).await);
    }
    if t == acl_management::GET_ACL {
        return finish(handlers::handle_get_acl(ctx, msg, Extension(vta_state)).await);
    }
    if t == acl_management::LIST_ACL {
        return finish(handlers::handle_list_acl(ctx, msg, Extension(vta_state)).await);
    }
    if t == acl_management::CHANGE_ROLE {
        return finish(handlers::handle_change_acl_role(ctx, msg, Extension(vta_state)).await);
    }
    if t == acl_management::UPDATE_ACL {
        return finish(handlers::handle_update_acl(ctx, msg, Extension(vta_state)).await);
    }
    if t == acl_management::DELETE_ACL {
        return finish(handlers::handle_delete_acl(ctx, msg, Extension(vta_state)).await);
    }
    // Legacy FPN-private `swap-acl` + canonical Trust Task `acl/swap-key/0.1`
    // both route to the same handler (dispatches on the incoming type).
    if t == acl_management::SWAP_ACL || t == acl_management::ACL_SWAP_KEY {
        return finish(
            handlers::handle_swap_acl(ctx, msg, Extension(vta_state), Extension(app_state)).await,
        );
    }

    // ── Audit management ─────────────────────────────────────────────
    if t == audit_management::LIST_LOGS {
        return finish(handlers::handle_list_logs(ctx, msg, Extension(vta_state)).await);
    }
    if t == audit_management::GET_RETENTION {
        return finish(handlers::handle_get_retention(ctx, msg, Extension(vta_state)).await);
    }
    if t == audit_management::UPDATE_RETENTION {
        return finish(handlers::handle_update_retention(ctx, msg, Extension(vta_state)).await);
    }

    // ── VTA management ───────────────────────────────────────────────
    if t == vta_management::GET_CONFIG {
        return finish(handlers::handle_get_config(ctx, msg, Extension(vta_state)).await);
    }
    if t == vta_management::UPDATE_CONFIG {
        return finish(handlers::handle_update_config(ctx, msg, Extension(vta_state)).await);
    }
    if t == protocols::PROBLEM_REPORT_TYPE {
        return finish(handlers::handle_problem_report(ctx, msg).await);
    }
    if t == vta_management::RESTART {
        return finish(handlers::handle_restart(ctx, msg, Extension(vta_state)).await);
    }
    if t == protocols::backup_management::EXPORT_BACKUP {
        return finish(handlers::handle_backup_export(ctx, msg, Extension(vta_state)).await);
    }
    if t == protocols::backup_management::IMPORT_BACKUP {
        return finish(handlers::handle_backup_import(ctx, msg, Extension(vta_state)).await);
    }

    // ── Credential exchange (AppState) ───────────────────────────────
    if t == credential_exchange::ISSUE {
        return finish(handlers::handle_credential_issue(ctx, msg, Extension(app_state)).await);
    }
    if t == credential_exchange::QUERY {
        return finish(handlers::handle_credential_query(ctx, msg, Extension(app_state)).await);
    }
    if t == credential_exchange::OFFER {
        return finish(handlers::handle_credential_offer(ctx, msg, Extension(app_state)).await);
    }

    // ── DID WebVH management (webvh) ─────────────────────────────────
    #[cfg(feature = "webvh")]
    {
        if t == did_management::CREATE_DID_WEBVH {
            return finish(handlers::handle_create_did_webvh(ctx, msg, Extension(vta_state)).await);
        }
        if t == did_management::GET_DID_WEBVH {
            return finish(handlers::handle_get_did_webvh(ctx, msg, Extension(vta_state)).await);
        }
        if t == did_management::GET_DID_WEBVH_LOG {
            return finish(
                handlers::handle_get_did_webvh_log(ctx, msg, Extension(vta_state)).await,
            );
        }
        if t == did_management::LIST_DIDS_WEBVH {
            return finish(handlers::handle_list_dids_webvh(ctx, msg, Extension(vta_state)).await);
        }
        if t == did_management::DELETE_DID_WEBVH {
            return finish(handlers::handle_delete_did_webvh(ctx, msg, Extension(vta_state)).await);
        }
        if t == did_management::ADD_WEBVH_SERVER {
            return finish(handlers::handle_add_webvh_server(ctx, msg, Extension(vta_state)).await);
        }
        if t == did_management::LIST_WEBVH_SERVERS {
            return finish(
                handlers::handle_list_webvh_servers(ctx, msg, Extension(vta_state)).await,
            );
        }
        if t == did_management::LIST_WEBVH_SERVER_DOMAINS {
            return finish(
                handlers::handle_list_webvh_server_domains(ctx, msg, Extension(vta_state)).await,
            );
        }
        if t == did_management::UPDATE_WEBVH_SERVER {
            return finish(
                handlers::handle_update_webvh_server(ctx, msg, Extension(vta_state)).await,
            );
        }
        if t == did_management::REMOVE_WEBVH_SERVER {
            return finish(
                handlers::handle_remove_webvh_server(ctx, msg, Extension(vta_state)).await,
            );
        }
        if t == did_management::UPDATE_DID_WEBVH {
            return finish(handlers::handle_update_did_webvh(ctx, msg, Extension(vta_state)).await);
        }
        if t == did_management::ROTATE_DID_WEBVH_KEYS {
            return finish(
                handlers::handle_rotate_did_webvh_keys(ctx, msg, Extension(vta_state)).await,
            );
        }
        if t == did_management::REGISTER_DID_WITH_SERVER {
            return finish(
                handlers::handle_register_did_with_server(ctx, msg, Extension(vta_state)).await,
            );
        }
    }

    // ── Protocol management over DIDComm (webvh) ─────────────────────
    #[cfg(feature = "webvh")]
    {
        use super::handlers_protocol as hp;
        if t == protocol_management::DISABLE_DIDCOMM {
            return finish(hp::handle_disable_didcomm(ctx, msg, Extension(vta_state)).await);
        }
        if t == protocol_management::ENABLE_REST {
            return finish(hp::handle_enable_rest(ctx, msg, Extension(vta_state)).await);
        }
        if t == protocol_management::UPDATE_REST {
            return finish(hp::handle_update_rest(ctx, msg, Extension(vta_state)).await);
        }
        if t == protocol_management::DISABLE_REST {
            return finish(hp::handle_disable_rest(ctx, msg, Extension(vta_state)).await);
        }
        if t == protocol_management::ROLLBACK_REST {
            return finish(hp::handle_rollback_rest(ctx, msg, Extension(vta_state)).await);
        }
        if t == protocol_management::ENABLE_TSP {
            return finish(hp::handle_enable_tsp(ctx, msg, Extension(vta_state)).await);
        }
        if t == protocol_management::UPDATE_TSP {
            return finish(hp::handle_update_tsp(ctx, msg, Extension(vta_state)).await);
        }
        if t == protocol_management::DISABLE_TSP {
            return finish(hp::handle_disable_tsp(ctx, msg, Extension(vta_state)).await);
        }
        if t == protocol_management::ROLLBACK_TSP {
            return finish(hp::handle_rollback_tsp(ctx, msg, Extension(vta_state)).await);
        }
        if t == protocol_management::UPDATE_DIDCOMM {
            return finish(hp::handle_update_didcomm(ctx, msg, Extension(vta_state)).await);
        }
        if t == protocol_management::ROLLBACK_DIDCOMM {
            return finish(hp::handle_rollback_didcomm(ctx, msg, Extension(vta_state)).await);
        }
        if t == protocol_management::LIST_SERVICES {
            return finish(hp::handle_list_services(ctx, msg, Extension(vta_state)).await);
        }
        if t == protocol_management::LIST_DRAIN {
            return finish(hp::handle_list_drain(ctx, msg, Extension(vta_state)).await);
        }
        if t == protocol_management::DRAIN_CANCEL {
            return finish(hp::handle_drain_cancel(ctx, msg, Extension(vta_state)).await);
        }
        if t == protocol_management::MEDIATOR_REPORT {
            return finish(hp::handle_mediator_report(ctx, msg, Extension(vta_state)).await);
        }
    }

    // ── Provision-integration (webvh) ────────────────────────────────
    #[cfg(feature = "webvh")]
    {
        // One version only, matching the Trust-Task dispatcher: the response
        // carries `digestMultibase`, which 0.1's and 0.2's closed response
        // schemas reject. Read from `CURRENT` rather than pinned to the 0.3
        // constant so that the URI this accepts, the URI the handler answers
        // under, and the URI vta-sdk's clients dispatch are one knob — the
        // 0.3 cut-over moved two of those three and left provisioning broken
        // on both counts.
        if t == provision_integration_management::ProvisionSpecVersion::CURRENT.request_uri() {
            return finish(
                handlers::handle_provision_integration(ctx, msg, Extension(vta_state)).await,
            );
        }
    }

    // ── Step-up approval (always) ────────────────────────────────────
    if t == handlers::STEP_UP_APPROVE_REQUEST_TYPE
        || t == handlers::STEP_UP_APPROVE_REQUEST_CANONICAL
        || t == handlers::STEP_UP_APPROVE_REQUEST_CANONICAL_0_2
    {
        return finish(handlers::handle_step_up_approve(ctx, msg, Extension(vta_state)).await);
    }

    // ── TEE attestation (tee) ────────────────────────────────────────
    #[cfg(feature = "tee")]
    {
        if t == attestation_management::GET_TEE_STATUS {
            return finish(handlers::handle_tee_status(ctx, msg, Extension(vta_state)).await);
        }
        if t == attestation_management::REQUEST_ATTESTATION {
            return finish(
                handlers::handle_request_attestation(ctx, msg, Extension(vta_state)).await,
            );
        }
    }

    // The `discovery/1.0/*` DIDComm protocol was routed here — unauthenticated
    // — until #1043 retired it with the task behind it. Capability discovery is
    // `trust-task-discovery/0.1` on the Trust-Task spine, which is authenticated
    // like everything else there.

    // ── Fallback ─────────────────────────────────────────────────────
    finish(handlers::handle_unknown(ctx, msg).await)
}

/// Keyring VTI-42: the DIDComm binding envelope is the only carriage for a
/// Trust Task (`bindings/didcomm/0.2` §2–§5).
///
/// Driven by the dispatcher's own list, so a verb added to the spine is
/// covered without anybody remembering to add it here — the failure this
/// router used to have on the VTC side.
#[cfg(all(test, feature = "didcomm"))]
mod envelope_only_carriage {
    use super::*;
    use serde_json::json;
    use trust_tasks_didcomm::ENVELOPE_TYPE;

    /// A sender the VTA has never heard of: the spine must still *answer* —
    /// with a refusal — which is only reachable past the router.
    const STRANGER: &str = "did:key:z6MkhaXgBZDvotDkL5257faiztiGiC2QtKLGpbnnEGta2doK";

    /// Served URIs that also have a task-typed arm in [`dispatch`]. Both have
    /// task-typed senders: `vta_sdk::provision_integration::didcomm` still
    /// sends `provision/integration` typed as the task, and the `swap-key` arm
    /// shares its handler with the pre-envelope FPN `swap-acl` message. So
    /// retiring either is a client migration first, not a router edit. Only
    /// shrinks.
    #[cfg(feature = "webvh")]
    const LEGACY_TASK_TYPED_ARMS: &[&str] = &[
        vta_sdk::protocols::acl_management::ACL_SWAP_KEY,
        provision_integration_management::CANONICAL_PROVISION_INTEGRATION_0_3,
    ];
    #[cfg(not(feature = "webvh"))]
    const LEGACY_TASK_TYPED_ARMS: &[&str] = &[vta_sdk::protocols::acl_management::ACL_SWAP_KEY];

    fn problem_comment(resp: &DIDCommResponse) -> Option<&str> {
        (resp.type_ == vta_sdk::protocols::PROBLEM_REPORT_TYPE)
            .then(|| resp.body.get("comment").and_then(|c| c.as_str()))
            .flatten()
    }

    #[tokio::test]
    async fn every_dispatched_uri_is_served_in_the_envelope_and_refused_typed_as_itself() {
        let (app_state, _dir) = crate::test_support::build_signing_test_app_state().await;
        let vta_state = Arc::new(VtaState::from(&app_state));
        let uris = crate::trust_tasks::dispatched_uris();
        assert!(!uris.is_empty(), "the dispatcher serves nothing?");
        let mut typed_arm: Vec<&str> = Vec::new();

        for uri in uris {
            let doc = json!({
                "id": format!("urn:uuid:{}", uuid::Uuid::new_v4()),
                "type": uri,
                "issuer": STRANGER,
                "payload": {},
            });

            // Enveloped: reaches the spine, answered in the envelope.
            let req_id = format!("urn:uuid:{}", uuid::Uuid::new_v4());
            let msg = Message::build(req_id.clone(), ENVELOPE_TYPE.to_string(), doc.clone())
                .from(STRANGER.to_string())
                .finalize();
            let ctx = HandlerContext {
                sender_did: Some(STRANGER.to_string()),
            };
            let resp = dispatch(msg, ctx, vta_state.clone(), app_state.clone())
                .await
                .unwrap_or_else(|| panic!("`{uri}` in the envelope got no reply at all"));
            assert!(
                !problem_comment(&resp).is_some_and(|c| c.contains("unsupported message type")),
                "`{uri}` is dispatched, but the router refused its envelope: {:?}",
                resp.body
            );
            assert_eq!(
                resp.type_, ENVELOPE_TYPE,
                "`{uri}`: a reply to an enveloped request rides the envelope (binding §5)"
            );

            // Typed as the task: refused at the DIDComm layer, naming the
            // envelope, threaded to the request.
            let req_id = format!("urn:uuid:{}", uuid::Uuid::new_v4());
            let msg = Message::build(req_id.clone(), uri.to_string(), doc)
                .from(STRANGER.to_string())
                .finalize();
            let ctx = HandlerContext {
                sender_did: Some(STRANGER.to_string()),
            };
            let resp = dispatch(msg, ctx, vta_state.clone(), app_state.clone())
                .await
                .unwrap_or_else(|| panic!("`{uri}` typed as itself got no reply at all"));
            let refused = problem_comment(&resp).is_some_and(|c| c.contains(ENVELOPE_TYPE));
            if !refused {
                typed_arm.push(uri);
                continue;
            }
            assert_eq!(
                resp.thid.as_deref(),
                Some(req_id.as_str()),
                "`{uri}`: unthreaded"
            );
        }

        // A served URI the router *also* answers typed as itself is a legacy
        // task-typed arm (the binding says it must be refused). The VTA keeps
        // these for now — they predate the envelope and have callers — so they
        // are pinned here instead: the list may only shrink, and an entry that
        // no longer has an arm fails, so it cannot go stale.
        typed_arm.sort_unstable();
        let mut expected = LEGACY_TASK_TYPED_ARMS.to_vec();
        expected.sort_unstable();
        assert_eq!(
            typed_arm, expected,
            "the served URIs the router still answers typed as the task changed. A new one \
             is a regression — carry it in the envelope instead; a removed one should be \
             deleted from `LEGACY_TASK_TYPED_ARMS`"
        );
    }

    /// Not every unknown type is a Trust Task, and those keep the plain answer.
    #[test]
    fn a_non_trust_task_type_is_not_told_about_the_envelope() {
        assert!(
            handlers::trust_task_needs_envelope("https://example.com/protocols/x/1.0/y").is_none()
        );
    }
}