vta-sdk 0.48.0

SDK 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
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
//! REST transport for the online provisioning attempt fns.
//!
//! Sibling to [`super::runner_didcomm`] which handles the DIDComm path.
//! Both modules return the shared [`super::event::AttemptOutcome`] so the
//! orchestrator's outcome → event translation is uniform regardless of
//! which wire delivered the credential.

use tokio::sync::mpsc::UnboundedSender;

use crate::client::VtaClient;
use crate::did_key::decode_private_key_multibase;
use crate::provision_integration::http::{AdminScope, ProvisionIntegrationRequest};

use super::ask::ProvisionAsk;
use super::diagnostics::{DiagCheck, DiagStatus};
use super::event::{AttemptOutcome, VtaEvent};
use super::intent::{AdminCredentialReply, VtaReply};
use super::result::{admin_rotation_response_to_reply, decode_nonce_b64url, response_to_result_v2};

/// Run the REST leg of the AdminOnly auth check.
///
/// AdminOnly's proof-of-ACL today is "the auth handshake completes" —
/// for REST that's a successful round-trip through the DI-signed
/// [`super::auth_rest::challenge_response_di`]. The returned access token is
/// discarded; the integration's downstream code re-authenticates at
/// runtime via the same flow.
///
/// Mirrors the diagnostic-row emissions of the DIDComm AdminOnly path:
/// `AuthenticateREST` runs, `ListWebvhServers` and `ProvisionIntegration`
/// are `Skipped` with the same operator rationale. AdminOnly has no
/// post-auth phase.
pub(crate) async fn run_rest_attempt_admin_only(
    rest_url: &str,
    vta_did: &str,
    setup_did: String,
    setup_privkey_mb: String,
    tx: &UnboundedSender<VtaEvent>,
) -> AttemptOutcome {
    let _ = tx.send(VtaEvent::CheckStart(DiagCheck::AuthenticateREST));

    match super::auth_rest::challenge_response_di(rest_url, &setup_did, &setup_privkey_mb, vta_did)
        .await
    {
        Ok(_auth) => {
            let _ = tx.send(VtaEvent::CheckDone(
                DiagCheck::AuthenticateREST,
                DiagStatus::Ok(format!("REST auth as {setup_did}")),
            ));
            // Unlike the TSP and DIDComm legs, REST authentication *is* a VTA
            // round-trip that reads the ACL — `check_acl_full` runs at
            // `/auth/challenge`. A green row above therefore already means the
            // grant landed, and AdminOnly dispatches no task whose version
            // could skew, so there is nothing left for the probe to ask.
            let _ = tx.send(VtaEvent::CheckDone(
                DiagCheck::VerifyAuthorization,
                DiagStatus::Skipped("REST authentication is itself the VTA's ACL check".into()),
            ));
            let _ = tx.send(VtaEvent::CheckDone(
                DiagCheck::ListWebvhServers,
                DiagStatus::Skipped("AdminOnly — no VTA-minted DID so no webvh host needed".into()),
            ));
            let _ = tx.send(VtaEvent::CheckDone(
                DiagCheck::ProvisionIntegration,
                DiagStatus::Skipped(
                    "AdminOnly — setup did:key is the long-term admin credential; \
                     no template render, no rollover"
                        .into(),
                ),
            ));
            AttemptOutcome::Connected(VtaReply::AdminOnly(AdminCredentialReply {
                admin_did: setup_did,
                admin_private_key_mb: setup_privkey_mb,
            }))
        }
        Err(e) => {
            let msg = e.to_string();
            let _ = tx.send(VtaEvent::CheckDone(
                DiagCheck::AuthenticateREST,
                DiagStatus::Failed(msg.clone()),
            ));
            let _ = tx.send(VtaEvent::CheckDone(
                DiagCheck::VerifyAuthorization,
                DiagStatus::Skipped("REST auth did not complete".into()),
            ));
            let _ = tx.send(VtaEvent::CheckDone(
                DiagCheck::ListWebvhServers,
                DiagStatus::Skipped("REST auth did not complete".into()),
            ));
            let _ = tx.send(VtaEvent::CheckDone(
                DiagCheck::ProvisionIntegration,
                DiagStatus::Skipped("REST auth did not complete".into()),
            ));
            AttemptOutcome::PreAuthFailure(format!(
                "Could not complete REST authentication against the VTA. \
                 Confirm the `pnm acl create` command ran successfully for \
                 this setup DID and that the VTA's REST endpoint is reachable. \
                 ({msg})"
            ))
        }
    }
}

/// Run the REST FullSetup flow: authenticate, then POST a VP-framed
/// provision-integration request and open the returned sealed bundle.
///
/// Pre-auth boundary: failures inside [`super::auth_rest::challenge_response_di`] or
/// [`VtaClient`] construction → [`AttemptOutcome::PreAuthFailure`]. Once
/// auth completes, any error from the provision RPC, VP signing, nonce
/// decode, or sealed-bundle opening is [`AttemptOutcome::PostAuthFailure`]
/// — the VTA accepted us, so a different transport will reproduce the
/// same outcome.
pub(crate) async fn run_rest_attempt_full_setup(
    rest_url: &str,
    vta_did: &str,
    setup_did: String,
    setup_privkey_mb: String,
    ask: ProvisionAsk,
    tx: &UnboundedSender<VtaEvent>,
) -> AttemptOutcome {
    let _ = tx.send(VtaEvent::CheckStart(DiagCheck::AuthenticateREST));

    let token_result = match super::auth_rest::challenge_response_di(
        rest_url,
        &setup_did,
        &setup_privkey_mb,
        vta_did,
    )
    .await
    {
        Ok(r) => {
            let _ = tx.send(VtaEvent::CheckDone(
                DiagCheck::AuthenticateREST,
                DiagStatus::Ok(format!("REST auth as {setup_did}")),
            ));
            r
        }
        Err(e) => {
            let msg = e.to_string();
            let _ = tx.send(VtaEvent::CheckDone(
                DiagCheck::AuthenticateREST,
                DiagStatus::Failed(msg.clone()),
            ));
            let _ = tx.send(VtaEvent::CheckDone(
                DiagCheck::VerifyAuthorization,
                DiagStatus::Skipped("REST auth did not complete".into()),
            ));
            let _ = tx.send(VtaEvent::CheckDone(
                DiagCheck::ListWebvhServers,
                DiagStatus::Skipped("REST auth did not complete".into()),
            ));
            let _ = tx.send(VtaEvent::CheckDone(
                DiagCheck::ProvisionIntegration,
                DiagStatus::Skipped("REST auth did not complete".into()),
            ));
            return AttemptOutcome::PreAuthFailure(format!(
                "Could not complete REST authentication against the VTA. \
                     Confirm the `pnm acl create` command ran successfully for \
                     this setup DID and that the VTA's REST endpoint is reachable. \
                     ({msg})"
            ));
        }
    };

    // The setup DID *is* this client's identity: it just authenticated with it,
    // and the provisioning tasks that follow are proof-REQUIRED like any other.
    let client = VtaClient::authenticated(
        rest_url,
        crate::client::ClientIdentity {
            client_did: setup_did.clone(),
            private_key_multibase: setup_privkey_mb.clone(),
            vta_did: vta_did.to_string(),
            verification_method: None,
        },
        token_result.access_token,
    )
    .await;

    // REST authentication already proved the ACL grant, so what is left to ask
    // is whether this VTA serves the provisioning version this client
    // dispatches. #1147 cut `provision/integration` 0.2 -> 0.3 with no
    // dual-accept window — the two response schemas are mutually exclusive, so
    // there could not be one — which makes a client/VTA age gap a hard failure
    // rather than a degraded one. Better found here than after the VP is signed.
    if let Err(msg) = super::authz::verify_authorization(
        &client,
        &setup_did,
        vta_did,
        Some(
            crate::protocols::provision_integration_management::ProvisionSpecVersion::CURRENT
                .request_uri(),
        ),
        tx,
    )
    .await
    {
        let _ = tx.send(VtaEvent::CheckDone(
            DiagCheck::ListWebvhServers,
            DiagStatus::Skipped("authorization was not verified".into()),
        ));
        let _ = tx.send(VtaEvent::CheckDone(
            DiagCheck::ProvisionIntegration,
            DiagStatus::Skipped("authorization was not verified".into()),
        ));
        return AttemptOutcome::PostAuthFailure(msg);
    }

    let _ = tx.send(VtaEvent::CheckDone(
        DiagCheck::ListWebvhServers,
        DiagStatus::Skipped(
            "REST FullSetup — picker not run; using operator-supplied template vars".into(),
        ),
    ));

    let _ = tx.send(VtaEvent::CheckStart(DiagCheck::ProvisionIntegration));

    // Past the auth boundary: every failure below is post-auth.
    let seed = match decode_private_key_multibase(&setup_privkey_mb) {
        Ok(s) => s,
        Err(e) => {
            let msg = e.to_string();
            let _ = tx.send(VtaEvent::CheckDone(
                DiagCheck::ProvisionIntegration,
                DiagStatus::Failed(msg.clone()),
            ));
            return AttemptOutcome::PostAuthFailure(format!("setup key decode failed: {msg}"));
        }
    };
    let vp = match ask.to_builder().sign_with(&seed, &setup_did).await {
        Ok(v) => v,
        Err(e) => {
            let msg = e.to_string();
            let _ = tx.send(VtaEvent::CheckDone(
                DiagCheck::ProvisionIntegration,
                DiagStatus::Failed(msg.clone()),
            ));
            return AttemptOutcome::PostAuthFailure(format!("VP signing failed: {msg}"));
        }
    };
    let nonce = match decode_nonce_b64url(&vp.nonce) {
        Ok(n) => n,
        Err(e) => {
            let _ = tx.send(VtaEvent::CheckDone(
                DiagCheck::ProvisionIntegration,
                DiagStatus::Failed(e.clone()),
            ));
            return AttemptOutcome::PostAuthFailure(format!("nonce decode failed: {e}"));
        }
    };

    // This process signed `vp` moments ago, so its serde rendering *is*
    // the signed bytes. A VP from anywhere else must travel as the raw
    // JSON it arrived as.
    let request = match vp.to_signed_wire_value() {
        Ok(v) => v,
        Err(e) => {
            let _ = tx.send(VtaEvent::CheckDone(
                DiagCheck::ProvisionIntegration,
                DiagStatus::Failed(e.to_string()),
            ));
            return AttemptOutcome::PostAuthFailure(format!("serialize VP: {e}"));
        }
    };

    let req = ProvisionIntegrationRequest {
        request,
        context: Some(ask.context.clone()),
        assertion: None,
        vc_validity_seconds: None,
        create_context: false,
        admin_scope: AdminScope::default(),
    };
    let response = match client.provision_integration(req).await {
        Ok(r) => r,
        Err(e) => {
            let msg = e.to_string();
            let _ = tx.send(VtaEvent::CheckDone(
                DiagCheck::ProvisionIntegration,
                DiagStatus::Failed(msg.clone()),
            ));
            return AttemptOutcome::PostAuthFailure(format!(
                "VTA rejected the REST provision request. ({msg})"
            ));
        }
    };

    let result = match response_to_result_v2(&seed, nonce, response) {
        Ok(r) => r,
        Err(e) => {
            let msg = e.to_string();
            let _ = tx.send(VtaEvent::CheckDone(
                DiagCheck::ProvisionIntegration,
                DiagStatus::Failed(msg.clone()),
            ));
            return AttemptOutcome::PostAuthFailure(format!(
                "could not open returned bundle: {msg}"
            ));
        }
    };

    let _ = tx.send(VtaEvent::CheckDone(
        DiagCheck::ProvisionIntegration,
        DiagStatus::Ok(format!(
            "admin DID: {} (rolled: {}), integration DID: {}",
            result.admin_did(),
            result.summary.admin_rolled_over,
            result.integration_did().unwrap_or("(none)"),
        )),
    ));

    AttemptOutcome::Connected(VtaReply::Full(Box::new(result)))
}

/// Run the REST AdminRotated flow: authenticate, then POST a VP-framed
/// `BootstrapAsk::AdminRotation` request and open the returned sealed
/// `SealedPayloadV1::AdminRotation` bundle.
///
/// Mirrors [`run_rest_attempt_full_setup`] for the admin-only-rotation
/// intent. Same pre-auth / post-auth boundary semantics. Emits the same
/// diagnostic rows so consumer UIs don't need to fork their event
/// handling between the two flows; `ListWebvhServers` is `Skipped` here
/// because no integration DID is minted.
pub(crate) async fn run_rest_attempt_admin_rotated(
    rest_url: &str,
    vta_did: &str,
    setup_did: String,
    setup_privkey_mb: String,
    ask: ProvisionAsk,
    tx: &UnboundedSender<VtaEvent>,
) -> AttemptOutcome {
    let _ = tx.send(VtaEvent::CheckStart(DiagCheck::AuthenticateREST));

    let token_result = match super::auth_rest::challenge_response_di(
        rest_url,
        &setup_did,
        &setup_privkey_mb,
        vta_did,
    )
    .await
    {
        Ok(r) => {
            let _ = tx.send(VtaEvent::CheckDone(
                DiagCheck::AuthenticateREST,
                DiagStatus::Ok(format!("REST auth as {setup_did}")),
            ));
            r
        }
        Err(e) => {
            let msg = e.to_string();
            let _ = tx.send(VtaEvent::CheckDone(
                DiagCheck::AuthenticateREST,
                DiagStatus::Failed(msg.clone()),
            ));
            let _ = tx.send(VtaEvent::CheckDone(
                DiagCheck::VerifyAuthorization,
                DiagStatus::Skipped("REST auth did not complete".into()),
            ));
            let _ = tx.send(VtaEvent::CheckDone(
                DiagCheck::ListWebvhServers,
                DiagStatus::Skipped("REST auth did not complete".into()),
            ));
            let _ = tx.send(VtaEvent::CheckDone(
                DiagCheck::ProvisionIntegration,
                DiagStatus::Skipped("REST auth did not complete".into()),
            ));
            return AttemptOutcome::PreAuthFailure(format!(
                "Could not complete REST authentication against the VTA. \
                     Confirm the `pnm acl create` command ran successfully for \
                     this setup DID and that the VTA's REST endpoint is reachable. \
                     ({msg})"
            ));
        }
    };

    // The setup DID *is* this client's identity: it just authenticated with it,
    // and the provisioning tasks that follow are proof-REQUIRED like any other.
    let client = VtaClient::authenticated(
        rest_url,
        crate::client::ClientIdentity {
            client_did: setup_did.clone(),
            private_key_multibase: setup_privkey_mb.clone(),
            vta_did: vta_did.to_string(),
            verification_method: None,
        },
        token_result.access_token,
    )
    .await;

    // REST authentication already proved the ACL grant, so what is left to ask
    // is whether this VTA serves the provisioning version this client
    // dispatches. #1147 cut `provision/integration` 0.2 -> 0.3 with no
    // dual-accept window — the two response schemas are mutually exclusive, so
    // there could not be one — which makes a client/VTA age gap a hard failure
    // rather than a degraded one. Better found here than after the VP is signed.
    if let Err(msg) = super::authz::verify_authorization(
        &client,
        &setup_did,
        vta_did,
        Some(
            crate::protocols::provision_integration_management::ProvisionSpecVersion::CURRENT
                .request_uri(),
        ),
        tx,
    )
    .await
    {
        let _ = tx.send(VtaEvent::CheckDone(
            DiagCheck::ListWebvhServers,
            DiagStatus::Skipped("authorization was not verified".into()),
        ));
        let _ = tx.send(VtaEvent::CheckDone(
            DiagCheck::ProvisionIntegration,
            DiagStatus::Skipped("authorization was not verified".into()),
        ));
        return AttemptOutcome::PostAuthFailure(msg);
    }

    let _ = tx.send(VtaEvent::CheckDone(
        DiagCheck::ListWebvhServers,
        DiagStatus::Skipped(
            "AdminRotated — no integration DID minted so no webvh host needed".into(),
        ),
    ));

    let _ = tx.send(VtaEvent::CheckStart(DiagCheck::ProvisionIntegration));

    // Past the auth boundary: every failure below is post-auth.
    let seed = match decode_private_key_multibase(&setup_privkey_mb) {
        Ok(s) => s,
        Err(e) => {
            let msg = e.to_string();
            let _ = tx.send(VtaEvent::CheckDone(
                DiagCheck::ProvisionIntegration,
                DiagStatus::Failed(msg.clone()),
            ));
            return AttemptOutcome::PostAuthFailure(format!("setup key decode failed: {msg}"));
        }
    };
    let vp = match ask.to_builder().sign_with(&seed, &setup_did).await {
        Ok(v) => v,
        Err(e) => {
            let msg = e.to_string();
            let _ = tx.send(VtaEvent::CheckDone(
                DiagCheck::ProvisionIntegration,
                DiagStatus::Failed(msg.clone()),
            ));
            return AttemptOutcome::PostAuthFailure(format!("VP signing failed: {msg}"));
        }
    };
    let nonce = match decode_nonce_b64url(&vp.nonce) {
        Ok(n) => n,
        Err(e) => {
            let _ = tx.send(VtaEvent::CheckDone(
                DiagCheck::ProvisionIntegration,
                DiagStatus::Failed(e.clone()),
            ));
            return AttemptOutcome::PostAuthFailure(format!("nonce decode failed: {e}"));
        }
    };

    // This process signed `vp` moments ago, so its serde rendering *is*
    // the signed bytes. A VP from anywhere else must travel as the raw
    // JSON it arrived as.
    let request = match vp.to_signed_wire_value() {
        Ok(v) => v,
        Err(e) => {
            let _ = tx.send(VtaEvent::CheckDone(
                DiagCheck::ProvisionIntegration,
                DiagStatus::Failed(e.to_string()),
            ));
            return AttemptOutcome::PostAuthFailure(format!("serialize VP: {e}"));
        }
    };

    let req = ProvisionIntegrationRequest {
        request,
        context: Some(ask.context.clone()),
        assertion: None,
        vc_validity_seconds: None,
        create_context: false,
        admin_scope: AdminScope::default(),
    };
    let response = match client.provision_integration(req).await {
        Ok(r) => r,
        Err(e) => {
            let msg = e.to_string();
            let _ = tx.send(VtaEvent::CheckDone(
                DiagCheck::ProvisionIntegration,
                DiagStatus::Failed(msg.clone()),
            ));
            return AttemptOutcome::PostAuthFailure(format!(
                "VTA rejected the REST AdminRotation request. ({msg})"
            ));
        }
    };

    let reply = match admin_rotation_response_to_reply(&seed, nonce, response) {
        Ok(r) => r,
        Err(e) => {
            let msg = e.to_string();
            let _ = tx.send(VtaEvent::CheckDone(
                DiagCheck::ProvisionIntegration,
                DiagStatus::Failed(msg.clone()),
            ));
            return AttemptOutcome::PostAuthFailure(format!(
                "could not open returned AdminRotation bundle: {msg}"
            ));
        }
    };

    let _ = tx.send(VtaEvent::CheckDone(
        DiagCheck::ProvisionIntegration,
        DiagStatus::Ok(format!("admin DID rotated: {}", reply.admin_did)),
    ));

    AttemptOutcome::Connected(VtaReply::AdminOnly(reply))
}

#[cfg(test)]
mod tests {
    /// A challenge that satisfies the spec payload's `minLength: 16` (the
    /// canonical handler issues hex-encoded 32 random bytes). The old
    /// `"test-challenge"` fixture was 14 chars — accepted only while the client
    /// hand-wrote its payload JSON instead of building the typed spec type.
    const TEST_CHALLENGE: &str = "test-challenge-0123456789abcdef";

    use super::*;
    use crate::provision_client::setup_key::EphemeralSetupKey;
    use serde_json::json;
    use wiremock::matchers::{method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    /// `did:key` is self-resolving (the verification key is encoded in
    /// the identifier itself), so the unit test stays network-free.
    fn test_vta_did_key() -> String {
        EphemeralSetupKey::generate().unwrap().did
    }

    fn drain(rx: &mut tokio::sync::mpsc::UnboundedReceiver<VtaEvent>) -> Vec<VtaEvent> {
        let mut out = Vec::new();
        while let Ok(ev) = rx.try_recv() {
            out.push(ev);
        }
        out
    }

    #[tokio::test]
    async fn admin_only_returns_connected_on_successful_auth() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/auth/challenge"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "challenge": TEST_CHALLENGE,
                "sessionId": "test-session",
                "expiresAt": "2026-12-31T23:59:59Z"
            })))
            .mount(&server)
            .await;
        // Canonical authenticate response shape: { session, tokens }.
        Mock::given(method("POST"))
            .and(path("/auth/"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "session": {
                    "id": "test-session",
                    "subject": "did:example:caller",
                    "issuedAt": "2026-05-23T10:00:00Z",
                    "expiresAt": "2026-05-23T10:15:00Z",
                    "amr": ["did"],
                    "acr": "aal1"
                },
                "tokens": {
                    "accessToken": "test-access-token",
                    "tokenType": "Bearer",
                    "expiresIn": 900
                }
            })))
            .mount(&server)
            .await;

        let key = EphemeralSetupKey::generate().unwrap();
        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();

        let outcome = run_rest_attempt_admin_only(
            &server.uri(),
            &test_vta_did_key(),
            key.did.clone(),
            key.private_key_multibase().to_string(),
            &tx,
        )
        .await;

        match outcome {
            AttemptOutcome::Connected(VtaReply::AdminOnly(reply)) => {
                assert_eq!(reply.admin_did, key.did);
                assert_eq!(reply.admin_private_key_mb, key.private_key_multibase());
            }
            other => panic!("expected Connected/AdminOnly, got {other:?}"),
        }

        drop(tx);
        let events = drain(&mut rx);
        assert!(matches!(
            events.first(),
            Some(VtaEvent::CheckStart(DiagCheck::AuthenticateREST))
        ));
        let mut saw_auth_ok = false;
        let mut saw_provision_skip = false;
        for ev in &events {
            if let VtaEvent::CheckDone(DiagCheck::AuthenticateREST, DiagStatus::Ok(_)) = ev {
                saw_auth_ok = true;
            }
            if let VtaEvent::CheckDone(DiagCheck::ProvisionIntegration, DiagStatus::Skipped(_)) = ev
            {
                saw_provision_skip = true;
            }
        }
        assert!(saw_auth_ok, "AuthenticateREST did not transition to Ok");
        assert!(
            saw_provision_skip,
            "ProvisionIntegration did not get a Skipped row"
        );
    }

    #[tokio::test]
    async fn admin_only_returns_pre_auth_failure_on_401() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/auth/challenge"))
            .respond_with(ResponseTemplate::new(401).set_body_string("ACL not found"))
            .mount(&server)
            .await;

        let key = EphemeralSetupKey::generate().unwrap();
        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();

        let outcome = run_rest_attempt_admin_only(
            &server.uri(),
            &test_vta_did_key(),
            key.did.clone(),
            key.private_key_multibase().to_string(),
            &tx,
        )
        .await;

        match outcome {
            AttemptOutcome::PreAuthFailure(reason) => {
                assert!(
                    reason.contains("REST authentication"),
                    "operator-facing message missing REST mention: {reason}"
                );
                assert!(
                    reason.contains("401") || reason.contains("ACL not found"),
                    "operator-facing message did not include upstream detail: {reason}"
                );
            }
            other => panic!("expected PreAuthFailure, got {other:?}"),
        }

        drop(tx);
        let events = drain(&mut rx);
        let mut saw_auth_failed = false;
        for ev in &events {
            if let VtaEvent::CheckDone(DiagCheck::AuthenticateREST, DiagStatus::Failed(_)) = ev {
                saw_auth_failed = true;
            }
        }
        assert!(
            saw_auth_failed,
            "AuthenticateREST did not transition to Failed"
        );
    }

    #[tokio::test]
    async fn full_setup_returns_pre_auth_failure_on_auth_401() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/auth/challenge"))
            .respond_with(ResponseTemplate::new(401).set_body_string("ACL not found"))
            .mount(&server)
            .await;

        let key = EphemeralSetupKey::generate().unwrap();
        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
        let ask = ProvisionAsk::didcomm_mediator("mediator", "https://mediator.example.com");

        let outcome = run_rest_attempt_full_setup(
            &server.uri(),
            &test_vta_did_key(),
            key.did.clone(),
            key.private_key_multibase().to_string(),
            ask,
            &tx,
        )
        .await;

        match outcome {
            AttemptOutcome::PreAuthFailure(reason) => {
                assert!(
                    reason.contains("REST authentication"),
                    "operator-facing message missing REST mention: {reason}"
                );
            }
            other => panic!("expected PreAuthFailure, got {other:?}"),
        }

        drop(tx);
        let events = drain(&mut rx);
        let mut saw_provision_skipped = false;
        for ev in &events {
            if let VtaEvent::CheckDone(DiagCheck::ProvisionIntegration, DiagStatus::Skipped(_)) = ev
            {
                saw_provision_skipped = true;
            }
        }
        assert!(
            saw_provision_skipped,
            "ProvisionIntegration row should be Skipped after pre-auth failure"
        );
    }

    /// Mount the two-step auth ceremony every post-auth test needs.
    async fn mount_auth(server: &MockServer) {
        Mock::given(method("POST"))
            .and(path("/auth/challenge"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "challenge": TEST_CHALLENGE,
                "sessionId": "test-session",
                "expiresAt": "2026-12-31T23:59:59Z"
            })))
            .mount(server)
            .await;
        Mock::given(method("POST"))
            .and(path("/auth/"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "session": {
                    "id": "test-session",
                    "subject": "did:example:caller",
                    "issuedAt": "2026-05-23T10:00:00Z",
                    "expiresAt": "2026-05-23T10:15:00Z",
                    "amr": ["did"],
                    "acr": "aal1"
                },
                "tokens": {
                    "accessToken": "test-access-token",
                    "tokenType": "Bearer",
                    "expiresIn": 900
                }
            })))
            .mount(server)
            .await;
    }

    /// A VTA on the previous provisioning version is stopped before any key is
    /// minted, and told which version it is on.
    ///
    /// The other half of the probe's tolerance, and the half worth pinning:
    /// an unsigned reply is accepted, a **badly signed** one is not.
    ///
    /// `trusting_unsigned_replies` is narrow on purpose — a *present* proof is
    /// still verified and still bound to this VTA — so a rewritten reply cannot
    /// steer the diagnostic. Without this test the fix for the regression below
    /// reads exactly like "verification was turned off for the probe", which is
    /// what it must not be: the skew message here would prove a forged task
    /// list had been believed.
    #[tokio::test]
    async fn a_reply_with_a_broken_proof_does_not_steer_the_diagnostic() {
        let server = MockServer::start().await;
        mount_auth(&server).await;
        Mock::given(method("POST"))
            .and(path("/trust-tasks"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "id": "urn:uuid:11111111-1111-4111-8111-111111111111",
                "type": "https://trusttasks.org/spec/trust-task-discovery/0.1#response",
                "payload": {
                    "frameworkVersion": "0.2",
                    "supportedTypes": [
                        "https://trusttasks.org/spec/provision/integration/0.2"
                    ]
                },
                // Present, and nonsense. The narrow tolerance must reject this.
                "proof": {
                    "type": "DataIntegrityProof",
                    "cryptosuite": "eddsa-jcs-2022",
                    "created": "2026-01-01T00:00:00Z",
                    "verificationMethod": "did:key:zNotTheAgent#zNotTheAgent",
                    "proofPurpose": "assertionMethod",
                    "proofValue": "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz"
                }
            })))
            .mount(&server)
            .await;

        let key = EphemeralSetupKey::generate().unwrap();
        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
        let ask = ProvisionAsk::didcomm_mediator("mediator", "https://mediator.example.com");

        let outcome = run_rest_attempt_full_setup(
            &server.uri(),
            &test_vta_did_key(),
            key.did.clone(),
            key.private_key_multibase().to_string(),
            ask,
            &tx,
        )
        .await;

        // The forged list said 0.2 and only 0.2. If it had been believed, the
        // run would stop with the version-skew message naming it.
        if let AttemptOutcome::PostAuthFailure(reason) = &outcome {
            assert!(
                !reason.contains("version skew"),
                "a reply with a broken proof steered the diagnostic: {reason}"
            );
        }
        drop(tx);
        let _ = drain(&mut rx);
    }

    /// REGRESSION (2026-08-31). #1147 cut `provision/integration` 0.2 -> 0.3
    /// with no dual-accept window; a current client against a VTA still on 0.2
    /// signed its VP, dispatched, and got back
    /// `unsupported type: …/provision/integration/0.3` — a sentence that names
    /// the version the *client* wanted and never the one the VTA has. The
    /// operator read it as "provisioning is broken on this VTA" and went
    /// looking in the wrong half of the system.
    ///
    /// The `/bootstrap/provision-integration` route is deliberately left
    /// unmounted: reaching it at all would fail this test with a 404, which is
    /// how it asserts the run stops *before* the mint rather than during it.
    #[tokio::test]
    async fn a_vta_on_the_previous_provision_version_is_named_before_minting() {
        let server = MockServer::start().await;
        mount_auth(&server).await;
        Mock::given(method("POST"))
            .and(path("/trust-tasks"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "id": "urn:uuid:11111111-1111-4111-8111-111111111111",
                "type": "https://trusttasks.org/spec/trust-task-discovery/0.1#response",
                "payload": {
                    "frameworkVersion": "0.2",
                    "supportedTypes": [
                        "https://trusttasks.org/spec/provision/integration/0.2"
                    ]
                }
            })))
            .mount(&server)
            .await;

        let key = EphemeralSetupKey::generate().unwrap();
        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
        let ask = ProvisionAsk::didcomm_mediator("mediator", "https://mediator.example.com");

        let outcome = run_rest_attempt_full_setup(
            &server.uri(),
            &test_vta_did_key(),
            key.did.clone(),
            key.private_key_multibase().to_string(),
            ask,
            &tx,
        )
        .await;

        match outcome {
            AttemptOutcome::PostAuthFailure(reason) => {
                assert!(
                    reason.contains("provision/integration/0.2"),
                    "must name the version the VTA serves: {reason}"
                );
                assert!(
                    reason.contains("version skew"),
                    "must say which kind of failure this is: {reason}"
                );
            }
            other => panic!("expected PostAuthFailure, got {other:?}"),
        }

        drop(tx);
        let events = drain(&mut rx);
        assert!(
            events.iter().any(|ev| matches!(
                ev,
                VtaEvent::CheckDone(DiagCheck::VerifyAuthorization, DiagStatus::Failed(_))
            )),
            "the authorization row should carry the finding"
        );
        assert!(
            events.iter().any(|ev| matches!(
                ev,
                VtaEvent::CheckDone(DiagCheck::ProvisionIntegration, DiagStatus::Skipped(_))
            )),
            "provisioning must be skipped, not attempted"
        );
    }

    /// A VTA that does not serve discovery is still provisioned.
    ///
    /// The probe is a diagnostic, and a diagnostic that refuses to let a
    /// working VTA be provisioned is worse than no diagnostic. Here the
    /// discovery call 404s and the run carries on to the provisioning call —
    /// which is mounted, and fails on its own terms.
    #[tokio::test]
    async fn a_vta_without_discovery_still_reaches_the_provision_call() {
        let server = MockServer::start().await;
        mount_auth(&server).await;
        Mock::given(method("POST"))
            .and(path("/bootstrap/provision-integration"))
            .respond_with(ResponseTemplate::new(400).set_body_string("template render rejected"))
            .mount(&server)
            .await;

        let key = EphemeralSetupKey::generate().unwrap();
        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
        let ask = ProvisionAsk::didcomm_mediator("mediator", "https://mediator.example.com");

        let outcome = run_rest_attempt_full_setup(
            &server.uri(),
            &test_vta_did_key(),
            key.did.clone(),
            key.private_key_multibase().to_string(),
            ask,
            &tx,
        )
        .await;

        match outcome {
            AttemptOutcome::PostAuthFailure(reason) => assert!(
                reason.contains("REST provision request"),
                "the provision call must be the thing that failed: {reason}"
            ),
            other => panic!("expected PostAuthFailure, got {other:?}"),
        }

        drop(tx);
        let events = drain(&mut rx);
        assert!(
            events.iter().any(|ev| matches!(
                ev,
                VtaEvent::CheckDone(DiagCheck::VerifyAuthorization, DiagStatus::Skipped(_))
            )),
            "an unanswerable probe is Skipped, never Failed"
        );
    }

    #[tokio::test]
    async fn full_setup_returns_post_auth_failure_on_provision_400() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/auth/challenge"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "challenge": TEST_CHALLENGE,
                "sessionId": "test-session",
                "expiresAt": "2026-12-31T23:59:59Z"
            })))
            .mount(&server)
            .await;
        // Canonical authenticate response shape: { session, tokens }.
        Mock::given(method("POST"))
            .and(path("/auth/"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "session": {
                    "id": "test-session",
                    "subject": "did:example:caller",
                    "issuedAt": "2026-05-23T10:00:00Z",
                    "expiresAt": "2026-05-23T10:15:00Z",
                    "amr": ["did"],
                    "acr": "aal1"
                },
                "tokens": {
                    "accessToken": "test-access-token",
                    "tokenType": "Bearer",
                    "expiresIn": 900
                }
            })))
            .mount(&server)
            .await;
        Mock::given(method("POST"))
            .and(path("/bootstrap/provision-integration"))
            .respond_with(ResponseTemplate::new(400).set_body_string("template render rejected"))
            .mount(&server)
            .await;

        let key = EphemeralSetupKey::generate().unwrap();
        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
        let ask = ProvisionAsk::didcomm_mediator("mediator", "https://mediator.example.com");

        let outcome = run_rest_attempt_full_setup(
            &server.uri(),
            &test_vta_did_key(),
            key.did.clone(),
            key.private_key_multibase().to_string(),
            ask,
            &tx,
        )
        .await;

        match outcome {
            AttemptOutcome::PostAuthFailure(reason) => {
                assert!(
                    reason.contains("REST provision request"),
                    "operator-facing message missing provision mention: {reason}"
                );
            }
            other => panic!("expected PostAuthFailure, got {other:?}"),
        }

        drop(tx);
        let events = drain(&mut rx);
        let mut saw_auth_ok = false;
        let mut saw_provision_failed = false;
        for ev in &events {
            if let VtaEvent::CheckDone(DiagCheck::AuthenticateREST, DiagStatus::Ok(_)) = ev {
                saw_auth_ok = true;
            }
            if let VtaEvent::CheckDone(DiagCheck::ProvisionIntegration, DiagStatus::Failed(_)) = ev
            {
                saw_provision_failed = true;
            }
        }
        assert!(
            saw_auth_ok,
            "AuthenticateREST should be Ok before the provision call fails"
        );
        assert!(
            saw_provision_failed,
            "ProvisionIntegration row should be Failed after the 400"
        );
    }
}