vta-service 0.38.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
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
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
//! Services slice trust-task handlers — `vta/services/*`.
//!
//! The transports the agent advertises in its own did:webvh document. Every
//! mutation here edits that document and republishes the signed log, so none of
//! them is a runtime flag flip: **the log entry is the change**.
//!
//! ## One task per verb, not per transport
//!
//! `service` names the transport and `config` carries its settings, so these
//! eight handlers cover what twenty `/services/*` REST routes did. The fan-out
//! onto the per-transport operations happens here rather than on the wire,
//! which is what keeps a fifth transport to a config variant instead of four
//! new specs.
//!
//! The operations are untouched — `operations::protocol::*` already implements
//! each transport, and this module is the parameterised door onto them.
//!
//! ## The state shape is mapped, not forwarded
//!
//! `vta_sdk::protocol::services::ServiceState` is an internally-tagged enum
//! whose members serialize snake_case (`mediator_did`); the published schema is
//! a flat object with camelCase members. They are close enough to look
//! interchangeable and are not, so every response here is built explicitly
//! against the generated type. Forwarding the SDK value would put
//! `mediator_did` on the wire under a schema that says `mediatorDid`, and the
//! dispatch spine's `validate_payload` would reject it on arrival.

use super::helpers::{
    TRANSPORT_TRUST_TASK, TrustTaskOutcome, app_error_to_reject, parse_payload, success_response,
};
use serde_json::Value;
use trust_tasks_rs::TrustTask;
use trust_tasks_rs::specs::vta::services as spec;

use crate::auth::AuthClaims;
use crate::error::AppError;
use crate::operations::protocol::list::ListServicesError;
use crate::operations::protocol::{OpContext, ServiceOpDeps};
use crate::server::AppState;

use vta_sdk::protocol::services::ServiceState as SdkState;

/// The DID resolver, or a refusal.
///
/// Every mutation needs it: publishing a log entry means resolving the agent's
/// own DID first, and an agent that cannot do that must not claim it changed
/// what the world can see.
fn resolver(state: &AppState) -> Result<affinidi_did_resolver_cache_sdk::DIDCacheClient, AppError> {
    state
        .did_resolver
        .as_ref()
        .cloned()
        .ok_or_else(|| AppError::Internal("DID resolver not available".into()))
}

/// Map one SDK state record onto the published shape.
///
/// `drains_until` has no SDK counterpart on the state record — a drain is
/// reported by `vta/services/drain/list`, which reads a different store — so it
/// is left absent here rather than guessed.
fn state(s: &SdkState) -> spec::list::v1_0::ServiceState {
    use spec::list::v1_0::{ServiceKind as K, ServiceState as Out};
    let (kind, enabled, mediator_did, url) = match s {
        SdkState::Tsp {
            enabled,
            mediator_did,
        } => (K::Tsp, *enabled, mediator_did.clone(), None),
        SdkState::Rest { enabled, url } => (K::Rest, *enabled, None, url.clone()),
        SdkState::Didcomm {
            enabled,
            mediator_did,
            ..
        } => (K::Didcomm, *enabled, mediator_did.clone(), None),
        SdkState::Webauthn { enabled, url } => (K::Webauthn, *enabled, None, url.clone()),
    };
    // `drainsUntil` unset: a state snapshot says nothing about drains, which
    // `services/drain/list` answers.
    Out::builder()
        .kind(kind)
        .enabled(enabled)
        .mediator_did(mediator_did)
        .url(url)
        .try_into()
        .expect("every required member of the service state is set above")
}

/// Finish a generated response/component builder.
///
/// The generated types are `#[non_exhaustive]` as of trust-tasks-rs 0.17, so
/// this crate cannot name their members in a struct literal — that is what lets
/// the registry add an OPTIONAL member without breaking every consumer. The
/// builder starts each REQUIRED member as `Err("no value supplied for …")`, so
/// every call below sets its required members explicitly and lets the optional
/// ones default.
fn built<T, B>(builder: B) -> Result<T, AppError>
where
    B: TryInto<T>,
    B::Error: std::fmt::Display,
{
    builder
        .try_into()
        .map_err(|e| AppError::Internal(format!("couldn't build a services response: {e}")))
}

fn kind_of(s: &SdkState) -> spec::list::v1_0::ServiceKind {
    state(s).kind
}

/// Classify a listing failure the way the REST route does.
///
/// Mirrored rather than collapsed to `Internal`: an agent whose DID is not yet
/// configured is a conflict the operator can fix, and telling them so is the
/// difference between "run `vta setup`" and "something broke". A refusal is
/// forbidden, not internal, for the same reason.
fn list_error(e: ListServicesError) -> AppError {
    match e {
        ListServicesError::Auth(msg) => AppError::Forbidden(msg),
        ListServicesError::VtaDidNotConfigured => {
            AppError::Conflict("VTA DID is not configured — run `vta setup` first".into())
        }
        other => AppError::Internal(other.to_string()),
    }
}

// ── list / get ──────────────────────────────────────────────────────

pub(super) async fn handle_list(
    state_: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let _req: spec::list::v1_0::Payload = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };
    // The operation enforces super-admin itself; letting it do so keeps one
    // authorization decision rather than two that can drift apart.
    match crate::operations::protocol::list::list_services(&state_.config, &state_.webvh_ks, auth)
        .await
    {
        Ok(body) => match built::<spec::list::v1_0::Response, _>(
            spec::list::v1_0::Response::builder()
                .services(body.services.iter().map(state).collect::<Vec<_>>()),
        ) {
            Ok(r) => success_response(&doc, r),
            Err(e) => app_error_to_reject(&doc, e),
        },
        Err(e) => app_error_to_reject(&doc, list_error(e)),
    }
}

pub(super) async fn handle_get(
    state_: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    let req: spec::get::v1_0::Payload = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };
    match crate::operations::protocol::list::list_services(&state_.config, &state_.webvh_ks, auth)
        .await
    {
        Ok(body) => {
            // `get` narrows `list` rather than having its own operation: the
            // agent holds one state record per transport, so querying twice
            // could disagree with itself.
            let want = match req.service {
                spec::get::v1_0::ServiceKind::Didcomm => spec::list::v1_0::ServiceKind::Didcomm,
                spec::get::v1_0::ServiceKind::Rest => spec::list::v1_0::ServiceKind::Rest,
                spec::get::v1_0::ServiceKind::Tsp => spec::list::v1_0::ServiceKind::Tsp,
                spec::get::v1_0::ServiceKind::Webauthn => spec::list::v1_0::ServiceKind::Webauthn,
                // The generated enum is `#[non_exhaustive]`: a caller on a
                // newer registry can name a transport this build does not
                // serve. Refuse rather than fall through to one of the four —
                // `get` exists to distinguish "never configured" from
                // "configured and disabled", and answering about the wrong
                // transport would corrupt exactly that distinction.
                _ => {
                    return app_error_to_reject(
                        &doc,
                        AppError::Validation(
                            "services/get: unrecognised service kind — this VTA does not serve \
                             a transport added to the registry after it was built"
                                .into(),
                        ),
                    );
                }
            };
            match body.services.iter().find(|s| kind_of(s) == want) {
                Some(found) => match built::<spec::get::v1_0::Response, _>(
                    spec::get::v1_0::Response::builder().state(
                        serde_json::from_value::<spec::get::v1_0::ServiceState>(
                            serde_json::to_value(state(found)).unwrap_or(Value::Null),
                        )
                        .expect("the two generated ServiceState shapes are identical"),
                    ),
                ) {
                    Ok(r) => success_response(&doc, r),
                    Err(e) => app_error_to_reject(&doc, e),
                },
                // Absent means never configured — distinct from configured and
                // disabled, which comes back with `enabled: false`. Answering
                // an empty success here would erase that distinction, which is
                // the only reason to call `get` over `list`.
                None => app_error_to_reject(
                    &doc,
                    crate::error::AppError::NotFound(format!(
                        "no {:?} transport is configured on this agent",
                        req.service
                    )),
                ),
            }
        }
        Err(e) => app_error_to_reject(&doc, list_error(e)),
    }
}

// ── the mutating verbs ──────────────────────────────────────────────
//
// Each fans out on `service`. The three uniform transports take the same
// `(deps, auth, params, ctx, channel)` shape; `didcomm` differs because it
// carries a mediator handshake and a drain, which is the whole reason the
// spec's `config` is a discriminated union rather than one flat object.

use crate::operations::protocol::disable_didcomm::{
    DisableDidcommParams, DisableTransport, disable_didcomm,
};
use crate::operations::protocol::disable_rest::{DisableRestParams, disable_rest};
use crate::operations::protocol::disable_tsp::{DisableTspParams, disable_tsp};
use crate::operations::protocol::disable_webauthn::{DisableWebauthnParams, disable_webauthn};
use crate::operations::protocol::drain_cancel::{DrainCancelParams, drain_cancel};
use crate::operations::protocol::enable_rest::{EnableRestParams, enable_rest};
use crate::operations::protocol::enable_tsp::{EnableTspParams, enable_tsp};
use crate::operations::protocol::enable_webauthn::{EnableWebauthnParams, enable_webauthn};
use crate::operations::protocol::list_drain::list_drain;
use crate::operations::protocol::rollback_rest::{RollbackRestParams, rollback_rest};
use crate::operations::protocol::rollback_tsp::{RollbackTspParams, rollback_tsp};
use crate::operations::protocol::rollback_webauthn::{RollbackWebauthnParams, rollback_webauthn};
use crate::operations::protocol::update_rest::{UpdateRestParams, update_rest};
use crate::operations::protocol::update_tsp::{UpdateTspParams, update_tsp};
use crate::operations::protocol::update_webauthn::{UpdateWebauthnParams, update_webauthn};

/// Which transport this task arrived over, for the drain guard.
///
/// The dispatch spine records confidentiality, not binding: DIDComm and TSP are
/// both `EndToEnd`, and it cannot tell them apart. So `EndToEnd` maps to
/// `Didcomm` here, which **over-applies** the 1-hour drain floor to a
/// TSP-carried disable that does not strictly need it.
///
/// That asymmetry is deliberate. Under-applying the floor tears down the
/// mediator a request arrived through and discards the reply to the very task
/// asking for it; over-applying only delays a teardown the operator can repeat.
/// A bounded delay is the cheaper mistake, so the ambiguous case takes it.
fn arrival_transport() -> DisableTransport {
    match super::transport::current() {
        super::transport::TransportConfidentiality::EndToEnd => DisableTransport::Didcomm,
        super::transport::TransportConfidentiality::HopByHop => DisableTransport::Rest,
    }
}

/// `config.url`, or a validation refusal naming the member that is missing.
fn need_url(url: Option<String>) -> Result<String, AppError> {
    url.ok_or_else(|| AppError::Conflict("this service needs `config.url`; none was sent".into()))
}

fn need_mediator(mediator_did: Option<String>) -> Result<String, AppError> {
    mediator_did.ok_or_else(|| {
        AppError::Conflict("this service needs `config.mediatorDid`; none was sent".into())
    })
}

/// The shared success shape, stamped with the instant the change took effect.
///
/// The operations return the log-entry id but not the time; the REST routes
/// stamp it at the boundary and so does this, so both surfaces agree.
fn mutation(
    log_entry_version_id: String,
    vta_did: String,
    serverless: bool,
    drain_until: Option<chrono::DateTime<chrono::Utc>>,
    draining_mediator: Option<String>,
) -> Result<spec::enable::v1_0::ServiceMutationResult, AppError> {
    built(
        spec::enable::v1_0::ServiceMutationResult::builder()
            .log_entry_version_id(
                spec::enable::v1_0::ServiceMutationResultLogEntryVersionId::try_from(
                    log_entry_version_id,
                )
                .map_err(|_| {
                    AppError::Internal("operation returned an empty log entry id".into())
                })?,
            )
            .effective_at(chrono::Utc::now())
            .drain_until(drain_until)
            .draining_mediator(draining_mediator)
            .vta_did((!vta_did.is_empty()).then_some(vta_did))
            .serverless(serverless),
    )
}

/// Re-type an identically-shaped generated value for a sibling family.
///
/// `enable`, `update` and `disable` each get their own `ServiceMutationResult`
/// from codegen: same members, distinct types. Rather than hand-copy the
/// members three times — and drift when one gains a field — go through the wire
/// form, which is the representation all of them agree on by construction.
fn retype<T: serde::de::DeserializeOwned>(v: impl serde::Serialize) -> Result<T, AppError> {
    serde_json::to_value(v)
        .and_then(serde_json::from_value)
        .map_err(|e| AppError::Internal(format!("service result re-type: {e}")))
}

/// Await a service operation, mapping its error to a conflict rejection.
///
/// This used to `Box::pin` the operation future. These handlers fan out to four
/// operations, each with a sizeable future, and before the dispatch seam was
/// fixed the spine awaited the whole handler inline in a match that summed every
/// task's state machine — so inlining these operations too grew that frame past
/// the thread stack and aborted an unrelated mock_vta test with a stack overflow
/// (which reads as, but is not, infinite recursion). That boxing now lives at
/// the dispatch seam itself (`dispatch_typed` `Box::pin`s every arm), which
/// heap-allocates each handler's whole future once; the per-operation box here
/// was redundant on top of it and dropped.
macro_rules! op {
    ($doc:expr, $call:expr) => {
        match $call.await {
            Ok(r) => r,
            Err(e) => return app_error_to_reject($doc, AppError::Conflict(e.to_string())),
        }
    };
}

pub(super) async fn handle_enable(
    state_: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    if let Err(e) = auth.require_super_admin() {
        return app_error_to_reject(&doc, e);
    }
    let req: spec::enable::v1_0::Payload = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };
    let resolver = match resolver(state_) {
        Ok(r) => r,
        Err(e) => return app_error_to_reject(&doc, e),
    };
    let deps = ServiceOpDeps::from_app_state(state_, &resolver);
    use spec::enable::v1_0::ServiceKind as K;

    let result = match req.service {
        K::Rest => {
            let url = match need_url(req.config.url.clone().map(String::from)) {
                Ok(u) => u,
                Err(e) => return app_error_to_reject(&doc, e),
            };
            let r = op!(
                &doc,
                enable_rest(
                    &deps,
                    auth,
                    EnableRestParams { url },
                    OpContext::Direct,
                    TRANSPORT_TRUST_TASK
                )
            );
            mutation(r.new_version_id, r.vta_did, r.serverless, None, None)
        }
        K::Webauthn => {
            let url = match need_url(req.config.url.clone().map(String::from)) {
                Ok(u) => u,
                Err(e) => return app_error_to_reject(&doc, e),
            };
            let r = op!(
                &doc,
                enable_webauthn(
                    &deps,
                    auth,
                    EnableWebauthnParams { url },
                    OpContext::Direct,
                    TRANSPORT_TRUST_TASK
                )
            );
            mutation(r.new_version_id, r.vta_did, r.serverless, None, None)
        }
        K::Tsp => {
            let mediator_did =
                match need_mediator(req.config.mediator_did.clone().map(String::from)) {
                    Ok(m) => m,
                    Err(e) => return app_error_to_reject(&doc, e),
                };
            let r = op!(
                &doc,
                enable_tsp(
                    &deps,
                    auth,
                    EnableTspParams { mediator_did },
                    OpContext::Direct,
                    TRANSPORT_TRUST_TASK
                )
            );
            mutation(r.new_version_id, r.vta_did, r.serverless, None, None)
        }
        K::Didcomm => {
            // `AlwaysOkProver` for the same reason the REST enable route uses
            // it: the handshake's steps 2-5 need a running `DIDCommService`,
            // and at first-enable there is not one yet. The steady-state case
            // — where DIDComm is already up — goes through `update`, which
            // builds a live prover.
            let mediator_did =
                match need_mediator(req.config.mediator_did.clone().map(String::from)) {
                    Ok(m) => m,
                    Err(e) => return app_error_to_reject(&doc, e),
                };
            let params = crate::operations::protocol::enable_didcomm::EnableDidcommParams {
                mediator_did,
                force: req.config.force.unwrap_or(false),
                handshake_timeout: std::time::Duration::from_secs(
                    req.config.handshake_timeout_secs.map_or(10, u64::from),
                ),
            };
            let prover = crate::messaging::handshake::AlwaysOkProver;
            let r = op!(
                &doc,
                crate::operations::protocol::enable_didcomm::enable_didcomm(
                    &deps,
                    &prover,
                    auth,
                    params,
                    OpContext::Direct,
                    TRANSPORT_TRUST_TASK
                )
            );
            mutation(r.new_version_id, r.vta_did, r.serverless, None, None)
        }
        // `#[non_exhaustive]`: a caller on a newer registry can name a
        // transport this build does not serve. Refusing is the only safe
        // answer — every arm above mutates the DID document, and picking
        // one for an unrecognised kind would write the wrong service.
        _ => {
            return app_error_to_reject(
                &doc,
                AppError::Validation(
                    "unrecognised service kind — this VTA does not serve a \
                     transport added to the registry after it was built"
                        .into(),
                ),
            );
        }
    };
    match result {
        Ok(result) => match built::<spec::enable::v1_0::Response, _>(
            spec::enable::v1_0::Response::builder().result(result),
        ) {
            Ok(r) => success_response(&doc, r),
            Err(e) => app_error_to_reject(&doc, e),
        },
        Err(e) => app_error_to_reject(&doc, e),
    }
}

pub(super) async fn handle_update(
    state_: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    if let Err(e) = auth.require_super_admin() {
        return app_error_to_reject(&doc, e);
    }
    let req: spec::update::v1_0::Payload = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };
    let resolver = match resolver(state_) {
        Ok(r) => r,
        Err(e) => return app_error_to_reject(&doc, e),
    };
    let deps = ServiceOpDeps::from_app_state(state_, &resolver);
    use spec::update::v1_0::ServiceKind as K;

    let result = match req.service {
        K::Rest => {
            let url = match need_url(req.config.url.clone().map(String::from)) {
                Ok(u) => u,
                Err(e) => return app_error_to_reject(&doc, e),
            };
            let r = op!(
                &doc,
                update_rest(
                    &deps,
                    auth,
                    UpdateRestParams { url },
                    OpContext::Direct,
                    TRANSPORT_TRUST_TASK
                )
            );
            mutation(r.new_version_id, r.vta_did, r.serverless, None, None)
        }
        K::Webauthn => {
            let url = match need_url(req.config.url.clone().map(String::from)) {
                Ok(u) => u,
                Err(e) => return app_error_to_reject(&doc, e),
            };
            let r = op!(
                &doc,
                update_webauthn(
                    &deps,
                    auth,
                    UpdateWebauthnParams { url },
                    OpContext::Direct,
                    TRANSPORT_TRUST_TASK
                )
            );
            mutation(r.new_version_id, r.vta_did, r.serverless, None, None)
        }
        K::Tsp => {
            let mediator_did =
                match need_mediator(req.config.mediator_did.clone().map(String::from)) {
                    Ok(m) => m,
                    Err(e) => return app_error_to_reject(&doc, e),
                };
            let r = op!(
                &doc,
                update_tsp(
                    &deps,
                    auth,
                    UpdateTspParams { mediator_did },
                    OpContext::Direct,
                    TRANSPORT_TRUST_TASK
                )
            );
            mutation(r.new_version_id, r.vta_did, r.serverless, None, None)
        }
        K::Didcomm => {
            // Replacing the mediator drains the old one, so this carries the
            // same arrival-transport guard as `disable`: swapping the mediator
            // a request arrived through must not cut its reply.
            let mediator_did =
                match need_mediator(req.config.mediator_did.clone().map(String::from)) {
                    Ok(m) => m,
                    Err(e) => return app_error_to_reject(&doc, e),
                };
            let prover = crate::messaging::handshake::AlwaysOkProver;
            let params = crate::operations::protocol::update_didcomm::UpdateDidcommParams {
                new_mediator_did: mediator_did,
                drain_ttl: crate::operations::protocol::disable_didcomm::MIN_DRAIN_TTL_OVER_DIDCOMM,
                force: req.config.force.unwrap_or(false),
                handshake_timeout: std::time::Duration::from_secs(
                    req.config.handshake_timeout_secs.map_or(10, u64::from),
                ),
                audit_kind: crate::operations::protocol::update_didcomm::MigrateAuditKind::Forward,
                transport: arrival_transport(),
            };
            let r = op!(
                &doc,
                crate::operations::protocol::update_didcomm::update_didcomm(
                    &deps,
                    &prover,
                    auth,
                    params,
                    OpContext::Direct,
                    TRANSPORT_TRUST_TASK
                )
            );
            mutation(
                r.new_version_id,
                r.vta_did,
                r.serverless,
                Some(r.drains_until),
                Some(r.prior_mediator_did),
            )
        }
        // `#[non_exhaustive]`: a caller on a newer registry can name a
        // transport this build does not serve. Refusing is the only safe
        // answer — every arm above mutates the DID document, and picking
        // one for an unrecognised kind would write the wrong service.
        _ => {
            return app_error_to_reject(
                &doc,
                AppError::Validation(
                    "unrecognised service kind — this VTA does not serve a \
                     transport added to the registry after it was built"
                        .into(),
                ),
            );
        }
    };
    match result {
        // Annotated: the target type used to be pinned by the response struct
        // literal, and the builder's `TryInto` setter no longer pins it.
        Ok(result) => match retype::<spec::update::v1_0::ServiceMutationResult>(result) {
            Ok(result) => {
                match built::<spec::update::v1_0::Response, _>(
                    spec::update::v1_0::Response::builder().result(result),
                ) {
                    Ok(r) => success_response(&doc, r),
                    Err(e) => app_error_to_reject(&doc, e),
                }
            }
            Err(e) => app_error_to_reject(&doc, e),
        },
        Err(e) => app_error_to_reject(&doc, e),
    }
}

pub(super) async fn handle_disable(
    state_: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    if let Err(e) = auth.require_super_admin() {
        return app_error_to_reject(&doc, e);
    }
    let req: spec::disable::v1_0::Payload = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };
    let resolver = match resolver(state_) {
        Ok(r) => r,
        Err(e) => return app_error_to_reject(&doc, e),
    };
    let deps = ServiceOpDeps::from_app_state(state_, &resolver);
    use spec::disable::v1_0::ServiceKind as K;

    let result = match req.service {
        K::Rest => {
            let r = op!(
                &doc,
                disable_rest(
                    &deps,
                    auth,
                    DisableRestParams,
                    OpContext::Direct,
                    TRANSPORT_TRUST_TASK
                )
            );
            mutation(r.new_version_id, r.vta_did, r.serverless, None, None)
        }
        K::Webauthn => {
            let r = op!(
                &doc,
                disable_webauthn(
                    &deps,
                    auth,
                    DisableWebauthnParams {},
                    OpContext::Direct,
                    TRANSPORT_TRUST_TASK
                )
            );
            mutation(r.new_version_id, r.vta_did, r.serverless, None, None)
        }
        K::Tsp => {
            let r = op!(
                &doc,
                disable_tsp(
                    &deps,
                    auth,
                    DisableTspParams,
                    OpContext::Direct,
                    TRANSPORT_TRUST_TASK
                )
            );
            mutation(r.new_version_id, r.vta_did, r.serverless, None, None)
        }
        K::Didcomm => {
            // `drainTtlSecs` is a REQUEST, not an instruction — the operation
            // raises it to the 1h floor when `transport` says the task arrived
            // end-to-end. The spec says so, and the result's `drainUntil` is
            // what a caller must read to learn what actually happened.
            let params = DisableDidcommParams {
                drain_ttl: std::time::Duration::from_secs(req.drain_ttl_secs.unwrap_or(0)),
                transport: arrival_transport(),
            };
            let r = op!(
                &doc,
                disable_didcomm(&deps, auth, params, OpContext::Direct, TRANSPORT_TRUST_TASK)
            );
            let draining = r.drains_until.map(|_| r.prior_mediator_did.clone());
            mutation(
                r.new_version_id,
                r.vta_did,
                r.serverless,
                r.drains_until,
                draining,
            )
        }
        // `#[non_exhaustive]`: a caller on a newer registry can name a
        // transport this build does not serve. Refusing is the only safe
        // answer — every arm above mutates the DID document, and picking
        // one for an unrecognised kind would write the wrong service.
        _ => {
            return app_error_to_reject(
                &doc,
                AppError::Validation(
                    "unrecognised service kind — this VTA does not serve a \
                     transport added to the registry after it was built"
                        .into(),
                ),
            );
        }
    };
    match result {
        Ok(result) => match retype::<spec::disable::v1_0::ServiceMutationResult>(result) {
            Ok(result) => {
                match built::<spec::disable::v1_0::Response, _>(
                    spec::disable::v1_0::Response::builder().result(result),
                ) {
                    Ok(r) => success_response(&doc, r),
                    Err(e) => app_error_to_reject(&doc, e),
                }
            }
            Err(e) => app_error_to_reject(&doc, e),
        },
        Err(e) => app_error_to_reject(&doc, e),
    }
}

/// Map a forward-op rollback kind onto the published one.
///
/// Each transport's rollback module declares its own `RollbackKind` with the
/// same four variants, so this takes the enum path rather than one type. They
/// are parallel by convention, not by a shared definition, and a macro that
/// names the variants keeps a divergence a compile error rather than a silent
/// mismatch.
macro_rules! rollback_kind {
    ($m:ident, $k:expr) => {{
        use crate::operations::protocol::$m::RollbackKind as K;
        use spec::rollback::v1_0::RollbackResultKind as Out;
        match $k {
            K::Disabled => Out::Disabled,
            K::Enabled => Out::Enabled,
            K::Updated => Out::Updated,
            K::NoOp => Out::NoOp,
        }
    }};
}

/// Build the rollback result.
///
/// `logEntryVersionId` is optional here and required on `ServiceMutationResult`,
/// which is the whole reason rollback has its own shape: when the previous
/// state already equals the current one nothing is written, and `kind: noOp`
/// says so. That is a **success** — the requested state holds — so reporting it
/// as a failure would be wrong, and inventing a log entry id would be worse.
fn rollback_result(
    kind: spec::rollback::v1_0::RollbackResultKind,
    new_version_id: Option<String>,
    vta_did: String,
    serverless: bool,
    draining_mediator: Option<String>,
) -> spec::rollback::v1_0::RollbackResult {
    let wrote_an_entry = new_version_id.is_some();
    spec::rollback::v1_0::RollbackResult::builder()
        .kind(kind)
        .log_entry_version_id(new_version_id)
        .effective_at(wrote_an_entry.then(chrono::Utc::now))
        .draining_mediator(draining_mediator)
        .vta_did((!vta_did.is_empty()).then_some(vta_did))
        .serverless(serverless)
        .try_into()
        .expect("every required member of the rollback result is set above")
}

pub(super) async fn handle_rollback(
    state_: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    if let Err(e) = auth.require_super_admin() {
        return app_error_to_reject(&doc, e);
    }
    let req: spec::rollback::v1_0::Payload = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };
    let resolver = match resolver(state_) {
        Ok(r) => r,
        Err(e) => return app_error_to_reject(&doc, e),
    };
    let deps = ServiceOpDeps::from_app_state(state_, &resolver);
    use spec::rollback::v1_0::ServiceKind as K;

    let result = match req.service {
        K::Rest => {
            let r = op!(
                &doc,
                rollback_rest(&deps, auth, RollbackRestParams, TRANSPORT_TRUST_TASK)
            );
            rollback_result(
                rollback_kind!(rollback_rest, r.kind),
                r.new_version_id,
                r.vta_did,
                r.serverless,
                None,
            )
        }
        K::Webauthn => {
            let r = op!(
                &doc,
                rollback_webauthn(&deps, auth, RollbackWebauthnParams, TRANSPORT_TRUST_TASK)
            );
            rollback_result(
                rollback_kind!(rollback_webauthn, r.kind),
                r.new_version_id,
                r.vta_did,
                r.serverless,
                None,
            )
        }
        K::Tsp => {
            let r = op!(
                &doc,
                rollback_tsp(&deps, auth, RollbackTspParams, TRANSPORT_TRUST_TASK)
            );
            rollback_result(
                rollback_kind!(rollback_tsp, r.kind),
                r.new_version_id,
                r.vta_did,
                r.serverless,
                None,
            )
        }
        K::Didcomm => {
            // Rolling DIDComm back can leave the superseded mediator draining,
            // so it takes the same arrival guard as disable.
            let params = crate::operations::protocol::rollback_didcomm::RollbackDidcommParams {
                drain_ttl: crate::operations::protocol::disable_didcomm::MIN_DRAIN_TTL_OVER_DIDCOMM,
                transport: arrival_transport(),
            };
            // Rolling back re-runs the forward op, so it needs a prover for
            // the same reason enable does — and `AlwaysOkProver` for the same
            // reason: the restored mediator's handshake cannot depend on a
            // DIDComm service that the rollback may itself be turning off.
            let prover = crate::messaging::handshake::AlwaysOkProver;
            let r = op!(
                &doc,
                crate::operations::protocol::rollback_didcomm::rollback_didcomm(
                    &deps,
                    &prover,
                    auth,
                    params,
                    TRANSPORT_TRUST_TASK
                )
            );
            let draining = r.draining_mediator.clone();
            rollback_result(
                rollback_kind!(rollback_didcomm, r.kind),
                r.new_version_id,
                r.vta_did,
                r.serverless,
                draining,
            )
        }
        // `#[non_exhaustive]`: a caller on a newer registry can name a
        // transport this build does not serve. Refusing is the only safe
        // answer — every arm above mutates the DID document, and picking
        // one for an unrecognised kind would write the wrong service.
        _ => {
            return app_error_to_reject(
                &doc,
                AppError::Validation(
                    "unrecognised service kind — this VTA does not serve a \
                     transport added to the registry after it was built"
                        .into(),
                ),
            );
        }
    };
    match built::<spec::rollback::v1_0::Response, _>(
        spec::rollback::v1_0::Response::builder().result(result),
    ) {
        Ok(r) => success_response(&doc, r),
        Err(e) => app_error_to_reject(&doc, e),
    }
}

// ── drain ───────────────────────────────────────────────────────────

pub(super) async fn handle_drain_list(
    state_: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    if let Err(e) = auth.require_super_admin() {
        return app_error_to_reject(&doc, e);
    }
    let _req: spec::drain::list::v1_0::Payload = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };
    match list_drain(&state_.config, &state_.drains_ks, auth).await {
        Ok(body) => {
            let entries = body
                .entries
                .into_iter()
                .map(|e| {
                    built(
                        spec::drain::list::v1_0::DrainEntry::builder()
                            .mediator_did(
                                spec::drain::list::v1_0::DrainEntryMediatorDid::try_from(
                                    e.mediator_did,
                                )
                                .map_err(|_| {
                                    AppError::Internal(
                                        "drain entry has an empty mediator did".into(),
                                    )
                                })?,
                            )
                            .endpoint(e.endpoint)
                            .drains_until(
                                e.drains_until
                                    .parse::<chrono::DateTime<chrono::Utc>>()
                                    .map_err(|_| {
                                        AppError::Internal(
                                            "drain entry has an unparseable deadline".into(),
                                        )
                                    })?,
                            ),
                    )
                })
                .collect::<Result<Vec<_>, AppError>>();
            match entries {
                Ok(entries) => match built::<spec::drain::list::v1_0::Response, _>(
                    spec::drain::list::v1_0::Response::builder().entries(entries),
                ) {
                    Ok(r) => success_response(&doc, r),
                    Err(e) => app_error_to_reject(&doc, e),
                },
                Err(e) => app_error_to_reject(&doc, e),
            }
        }
        Err(e) => app_error_to_reject(&doc, AppError::Conflict(e.to_string())),
    }
}

pub(super) async fn handle_drain_cancel(
    state_: &AppState,
    auth: &AuthClaims,
    doc: TrustTask<Value>,
) -> TrustTaskOutcome {
    if let Err(e) = auth.require_super_admin() {
        return app_error_to_reject(&doc, e);
    }
    let req: spec::drain::cancel::v1_0::Payload = match parse_payload(&doc) {
        Ok(r) => r,
        Err(resp) => return resp,
    };
    // Destructive: whatever is still in flight through that mediator is lost,
    // which is exactly what the drain window existed to prevent. The operation
    // refuses when the mediator is the active one, so an operator cannot strand
    // the route the agent depends on by hand.
    let params = DrainCancelParams {
        mediator_did: req.mediator_did.to_string(),
    };
    match drain_cancel(
        &state_.config,
        &state_.drains_ks,
        &state_.mediator_registry,
        &state_.telemetry,
        auth,
        params,
        TRANSPORT_TRUST_TASK,
    )
    .await
    {
        // `mediatorDid` is a plain String in this family — no newtype to
        // fall through, so there is nothing to validate here beyond what
        // the operation already guaranteed.
        Ok(r) => match built::<spec::drain::cancel::v1_0::Response, _>(
            spec::drain::cancel::v1_0::Response::builder().mediator_did(r.mediator_did),
        ) {
            Ok(resp) => success_response(&doc, resp),
            Err(e) => app_error_to_reject(&doc, e),
        },
        Err(e) => app_error_to_reject(&doc, AppError::Conflict(e.to_string())),
    }
}