vta-service 0.62.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
//! The witnessed-party tasks end to end, through the slice's own handlers, against a real witness
//! (`vti_witness::dispatch::answer`, the same dispatch core `vti-witness run` puts behind its
//! sockets). The test is the client: it carries each document the VTA builds to the witness,
//! from the relationship DID, and hands each answer back — exactly the carriage of
//! `vta/_shared/0.6/CONVENTIONS.md`.
//!
//! The relationship DID is a `did:peer:2` whose signing key the VTA holds (the shape openvtc
//! mints), the member DID a `did:key` the VTA holds, and the witness and the community are
//! `did:key`s held by the test. Every proof verifies with no network.

use super::*;
use crate::acl::Role;
use crate::operations::persona::{PersonaStores, Relationship, persona_key_for};
use crate::operations::room_issuance::{SigningContext, VtaKeySigner};
use crate::test_support::build_signing_test_app_state;
use chrono::{TimeDelta, Utc};
use dtg_credentials::{DTGCredential, IssuerScope};
use trust_tasks_rs::TypeUri;
use vta_sdk::provision_client::EphemeralSetupKey;
use vta_sdk::trust_task_proof::TrustTaskVmResolver;
use vta_sdk::trust_task_sign::{HolderKey, sign_in_place_with, sign_object_for_assertion};
use vta_sdk::trust_tasks as uris;
use vti_witness::config::SessionLimits;
use vti_witness::dispatch::{IdentityContext, Outcome, answer};
use vti_witness::store::{self as wstore, WitnessStore};
use vti_witness::witness::{WitnessPolicy, Witnessing};

const CTX: &str = "personal";
const OTHER: &str = "other";

// ── Plumbing ────────────────────────────────────────────────────────────

fn claims(role: Role, ctx: &str) -> AuthClaims {
    AuthClaims {
        did: "did:key:z6MkClientWalletExample".to_string(),
        role,
        allowed_contexts: vec![ctx.to_string()],
        session_id: "test-session".into(),
        access_expires_at: 0,
        issued_at: 0,
        amr: Vec::new(),
        acr: String::new(),
    }
}

fn doc(uri: &str, payload: Value) -> TrustTask<Value> {
    let uri: TypeUri = uri.parse().expect("witness uri");
    TrustTask::new(format!("urn:uuid:{}", uuid::Uuid::new_v4()), uri, payload)
}

fn body(out: &TrustTaskOutcome) -> Value {
    serde_json::from_slice(&out.body).expect("response is JSON")
}

fn ok(out: &TrustTaskOutcome) -> Value {
    let b = body(out);
    assert!(out.status.is_success(), "expected success, got {b:#}");
    b["payload"].clone()
}

fn code(out: &TrustTaskOutcome) -> String {
    body(out)
        .pointer("/payload/code")
        .and_then(Value::as_str)
        .unwrap_or_default()
        .to_string()
}

fn urn() -> String {
    format!("urn:uuid:{}", uuid::Uuid::new_v4())
}

/// A `did:key` the test holds the private key of.
struct Key {
    did: String,
    multibase: String,
}

impl Key {
    fn new() -> Self {
        let k = EphemeralSetupKey::generate().expect("key");
        Self {
            did: k.did.clone(),
            multibase: k.private_key_multibase().to_string(),
        }
    }

    fn holder(&self) -> HolderKey {
        HolderKey::from_did_key(&self.did, &self.multibase).expect("holder")
    }
}

/// The witness: one `vti-witness` identity, dispatched in process.
struct Witness {
    key: Key,
    identity: IdentityContext,
    _dir: tempfile::TempDir,
}

impl Witness {
    fn new(communities: Vec<String>) -> Self {
        let key = Key::new();
        let dir = tempfile::tempdir().expect("tempdir");
        let store = vti_common::store::test_fixture::open_with_keyspaces(dir.path(), wstore::ALL)
            .expect("witness store");
        let witnessing = Witnessing::new(
            WitnessPolicy::new(
                communities,
                None,
                vec![key.did.clone()],
                SessionLimits::default(),
            ),
            WitnessStore::from_store(&store).expect("witness keyspaces"),
        );
        let identity =
            IdentityContext::new("w", key.did.clone(), key.holder(), witnessing).expect("identity");
        Self {
            key,
            identity,
            _dir: dir,
        }
    }

    fn did(&self) -> &str {
        &self.key.did
    }

    /// Carry `document` to the witness from `sender`, as the client does, and return its answer.
    async fn carry(&self, sender: &str, document: &Value) -> Value {
        match answer(
            &self.identity,
            sender,
            &serde_json::to_vec(document).unwrap(),
            &TrustTaskVmResolver::did_key_only(),
            Utc::now(),
        )
        .await
        {
            Outcome::Reply(reply) => reply,
            Outcome::Drop(reason) => panic!("the witness dropped the document: {reason:?}"),
        }
    }
}

/// A principal whose relationship and member keys this VTA holds in [`CTX`], with a
/// relationship credential for one counterparty and a community membership credential in its
/// vault.
struct World {
    state: AppState,
    _dir: tempfile::TempDir,
    auth: AuthClaims,
    witness: Witness,
    community: Key,
    relationship: String,
    counterparty: String,
    member: String,
}

impl World {
    /// `member_link`: whether the VMC names a separate member DID (the member link) or the
    /// relationship DID itself.
    async fn new(member_link: bool) -> Self {
        let (state, dir) = build_signing_test_app_state().await;
        for ctx in [CTX, OTHER] {
            crate::contexts::create_context(&state.contexts_ks, ctx, ctx)
                .await
                .expect("create context");
        }
        let community = Key::new();
        let witness = Witness::new(vec![community.did.clone()]);

        // The relationship DID: a did:peer:2 over a key minted in CTX.
        let raw = crate::operations::persona::test_fixture::mint_key(
            &state.keys_ks,
            &state.internal_ks,
            &state.contexts_ks,
            &state.acl_ks,
            &state.seed_store,
            &state.audit_sink,
            CTX,
            "relationship-key",
        )
        .await;
        let relationship = format!(
            "did:peer:2.V{}",
            vta_sdk::did_key::ed25519_multibase_pubkey(&raw)
        );
        // The member DID: a did:key minted in CTX.
        let member = crate::operations::persona::test_fixture::did_key_persona(
            &state.keys_ks,
            &state.internal_ks,
            &state.contexts_ks,
            &state.acl_ks,
            &state.seed_store,
            &state.audit_sink,
            CTX,
            "member-key",
        )
        .await
        .did;
        let counterparty = Key::new().did;
        let auth = claims(Role::Admin, CTX);

        let w = Self {
            state,
            _dir: dir,
            auth,
            witness,
            community,
            relationship,
            counterparty,
            member,
        };
        let vrc = w.vrc(&w.counterparty.clone()).await;
        w.store("vrc-1", vrc).await;
        let member_of = if member_link {
            w.member.clone()
        } else {
            w.relationship.clone()
        };
        let vmc = w.vmc(&member_of).await;
        w.store("vmc-1", vmc).await;
        w
    }

    fn signing(&self) -> SigningContext<'_> {
        SigningContext {
            keys_ks: &self.state.keys_ks,
            imported_ks: &self.state.imported_ks,
            internal_ks: &self.state.internal_ks,
            contexts_ks: &self.state.contexts_ks,
            acl_ks: &self.state.acl_ks,
            seed_store: &self.state.seed_store,
            audit: &self.state.audit_sink,
            auth: &self.auth,
        }
    }

    /// The relationship DID's relationship credential naming `subject`, signed through the
    /// VTA's oracle as the relationship DID.
    async fn vrc(&self, subject: &str) -> Value {
        let key = persona_key_for(
            PersonaStores::from_state(&self.state),
            &self.auth,
            &self.relationship,
            Relationship::AssertionMethod,
        )
        .await
        .unwrap()
        .expect("the VTA holds the relationship key");
        let vc = DTGCredential::new_vrc(
            self.relationship.clone(),
            IssuerScope::Pairwise,
            subject.to_string(),
            Utc::now() - TimeDelta::minutes(5),
            None,
        )
        .with_id(urn());
        let mut vc = serde_json::to_value(vc).unwrap();
        let signer = VtaKeySigner::new(self.signing(), &key.key_id, &key.verification_method);
        let proof = affinidi_data_integrity::DataIntegrityProof::sign(
            &vc,
            &signer,
            affinidi_data_integrity::SignOptions::new().with_proof_purpose("assertionMethod"),
        )
        .await
        .expect("sign the VRC");
        vc["proof"] = serde_json::to_value(proof).unwrap();
        vc
    }

    /// The community's membership credential for `member`.
    async fn vmc(&self, member: &str) -> Value {
        let vc = DTGCredential::new_vmc(
            self.community.did.clone(),
            member.to_string(),
            Utc::now() - TimeDelta::days(1),
            None,
            false,
        )
        .with_id(urn());
        let mut v = serde_json::to_value(vc).unwrap();
        sign_object_for_assertion(&mut v, &self.community.holder())
            .await
            .unwrap();
        v
    }

    async fn store(&self, id: &str, vc: Value) {
        use crate::vault::model::{CredentialFormat, CredentialStatus, StoredCredential};
        crate::vault::storage::put(
            &self.state.vault_ks,
            &StoredCredential {
                id: id.into(),
                format: CredentialFormat::EddsaJcs2022,
                types: Vec::new(),
                schema_id: None,
                community_did: None,
                context_id: Some(CTX.into()),
                subject_did: None,
                issuer_did: None,
                purpose: None,
                status: CredentialStatus::Valid,
                valid_from: None,
                valid_until: None,
                received_at: Utc::now().to_rfc3339(),
                source: None,
                tags: Default::default(),
                body: serde_json::to_vec(&vc).unwrap(),
                lifecycle: vti_common::vault::VaultStatus::Active,
                archived_at: None,
                deleted_at: None,
                grace_until: None,
            },
        )
        .await
        .expect("store the credential");
    }

    fn open_payload(&self, member_link: bool) -> Value {
        let mut p = json!({
            "witness": self.witness.did(),
            "relationshipDid": self.relationship,
            "counterpartyDid": self.counterparty,
            "relationshipThreadId": "urn:uuid:9e8d7c6b-0000-4000-8000-000000000a01",
            "relationshipCredentialId": "vrc-1",
            "membership": { "credentialId": "vmc-1" },
        });
        if member_link {
            p["membership"]["memberDid"] = json!(self.member);
        }
        p
    }

    async fn open_as(&self, auth: &AuthClaims, payload: Value) -> TrustTaskOutcome {
        handle_open(
            &self.state,
            auth,
            doc(uris::TASK_VTA_WITNESS_OPEN_0_2, payload),
        )
        .await
    }

    async fn present_as(
        &self,
        auth: &AuthClaims,
        session: &str,
        response: &Value,
    ) -> TrustTaskOutcome {
        handle_present(
            &self.state,
            auth,
            doc(
                uris::TASK_VTA_WITNESS_PRESENT_0_2,
                json!({ "sessionId": session, "response": response }),
            ),
        )
        .await
    }

    async fn accept_as(
        &self,
        auth: &AuthClaims,
        session: &str,
        response: &Value,
    ) -> TrustTaskOutcome {
        handle_accept(
            &self.state,
            auth,
            doc(
                uris::TASK_VTA_WITNESS_ACCEPT_0_2,
                json!({ "sessionId": session, "response": response }),
            ),
        )
        .await
    }

    /// open → witness → present → witness, returning the session id, the session document, the
    /// witness's session answer, and its submit answer (the outcome).
    async fn run_to_outcome(&self, member_link: bool) -> (String, Value, Value, Value) {
        let opened = ok(&self
            .open_as(&self.auth, self.open_payload(member_link))
            .await);
        let session = opened["sessionId"].as_str().unwrap().to_string();
        let session_doc = opened["document"].clone();
        let session_answer = self.witness.carry(&self.relationship, &session_doc).await;
        let presented = ok(&self.present_as(&self.auth, &session, &session_answer).await);
        let outcome = self
            .witness
            .carry(&self.relationship, &presented["document"])
            .await;
        assert!(
            outcome["type"]
                .as_str()
                .is_some_and(|t| t.ends_with("submit/0.2#response")),
            "the witness accepted the submission: {outcome:#}"
        );
        (session, session_doc, session_answer, outcome)
    }
}

// ── The happy paths ─────────────────────────────────────────────────────

/// The whole family under the member link: the VTA signs the session and the submission as the
/// relationship DID (never as itself), the member presentation rides in the submit payload's
/// own `memberPresentation` (`witness/session/submit/0.2`),
/// the real witness mints a VWC, and the VTA verifies and stores it with its evidence.
#[tokio::test]
async fn witnessed_end_to_end_through_the_member_link() {
    let w = World::new(true).await;

    let opened = ok(&w
        .open_as(&w.auth, {
            let mut p = w.open_payload(true);
            p["storeAs"] = json!("vwc-alice-to-bob");
            p
        })
        .await);
    let session = opened["sessionId"].as_str().unwrap().to_string();
    let session_doc = opened["document"].clone();
    assert_eq!(session_doc["id"], session);
    assert_eq!(session_doc["threadId"], session);
    assert_eq!(session_doc["issuer"], w.relationship);
    assert_eq!(session_doc["recipient"], w.witness.did());
    assert_eq!(
        session_doc["payload"]["parties"],
        json!([w.relationship, w.counterparty])
    );
    assert!(
        session_doc["proof"]["verificationMethod"]
            .as_str()
            .unwrap()
            .starts_with(&format!("{}#", w.relationship)),
        "signed as the relationship DID, never as the VTA"
    );

    let session_answer = w.witness.carry(&w.relationship, &session_doc).await;
    let presented = ok(&w.present_as(&w.auth, &session, &session_answer).await);
    let submit = &presented["document"];
    assert_eq!(submit["issuer"], w.relationship);
    assert_eq!(submit["threadId"], session);
    assert!(
        submit["payload"].get("ext").is_none(),
        "no vendor-extension carriage: {submit:#}"
    );
    let member_vp = &submit["payload"]["memberPresentation"];
    assert_eq!(
        member_vp["holder"], w.member,
        "the member presentation is the member DID's"
    );
    assert_eq!(
        submit["payload"]["vp"]["verifiableCredential"]
            .as_array()
            .unwrap()
            .len(),
        1,
        "under the member link the VMC rides in the member presentation, not beside the VRC"
    );

    let outcome = w.witness.carry(&w.relationship, submit).await;
    let accepted = ok(&w.accept_as(&w.auth, &session, &outcome).await);
    assert_eq!(accepted["credentialId"], "vwc-alice-to-bob");
    assert_eq!(accepted["witness"], w.witness.did());
    assert_eq!(accepted["evidence"]["session"], session_doc);
    assert_eq!(accepted["evidence"]["outcome"], outcome);
    assert_eq!(
        accepted["vwcDigestMultibase"],
        outcome["payload"]["vwcDigestMultibase"]
    );

    // Stored in the relationship key's context, with both evidence documents.
    let stored = crate::vault::storage::get(&w.state.vault_ks, "vwc-alice-to-bob")
        .await
        .unwrap()
        .expect("the VWC is in the vault");
    assert_eq!(stored.context_id.as_deref(), Some(CTX));
    assert_eq!(stored.issuer_did.as_deref(), Some(w.witness.did()));
    assert_eq!(
        serde_json::from_slice::<Value>(&stored.body).unwrap(),
        outcome["payload"]["vwc"]
    );
    let tag = |k: &str| serde_json::from_str::<Value>(stored.tags.get(k).unwrap()).unwrap();
    assert_eq!(
        tag(crate::operations::witness::EVIDENCE_SESSION_TAG),
        session_doc
    );
    assert_eq!(
        tag(crate::operations::witness::EVIDENCE_OUTCOME_TAG),
        outcome
    );

    // The same outcome again is answered again, storing nothing (conventions §5).
    let again = ok(&w.accept_as(&w.auth, &session, &outcome).await);
    assert_eq!(again["credentialId"], accepted["credentialId"]);
    assert_eq!(again["evidence"], accepted["evidence"]);

    // An accepted session admits no further presentation.
    let out = w.present_as(&w.auth, &session, &session_answer).await;
    assert_eq!(code(&out), "vta/witness/present:sessionUnknown");
}

/// A membership credential naming the relationship DID rides in the relationship presentation,
/// with no member DID anywhere — and the derived handle is the VWC's own id.
#[tokio::test]
async fn witnessed_with_membership_naming_the_relationship_did() {
    let w = World::new(false).await;
    let (session, _, _, outcome) = w.run_to_outcome(false).await;
    let accepted = ok(&w.accept_as(&w.auth, &session, &outcome).await);
    assert_eq!(
        accepted["credentialId"], outcome["payload"]["vwc"]["id"],
        "without storeAs the handle is the VWC's id"
    );
}

/// A repeated present builds a fresh submission; the witness spends its challenge on the first
/// it accepts, so at most one VWC results (conventions §5).
#[tokio::test]
async fn a_repeated_present_is_safe() {
    let w = World::new(true).await;
    let opened = ok(&w.open_as(&w.auth, w.open_payload(true)).await);
    let session = opened["sessionId"].as_str().unwrap().to_string();
    let answer = w.witness.carry(&w.relationship, &opened["document"]).await;
    let first = ok(&w.present_as(&w.auth, &session, &answer).await);
    let second = ok(&w.present_as(&w.auth, &session, &answer).await);
    assert_ne!(first["document"]["id"], second["document"]["id"]);
    let outcome = w.witness.carry(&w.relationship, &second["document"]).await;
    ok(&w.accept_as(&w.auth, &session, &outcome).await);
    let refused = w.witness.carry(&w.relationship, &first["document"]).await;
    assert!(
        refused["payload"]["code"]
            .as_str()
            .is_some_and(|c| c.ends_with("challengeMismatch")),
        "{refused:#}"
    );
}

// ── Splices and forgeries ───────────────────────────────────────────────

/// No answer from another session, another witness, or a tampered one is read.
#[tokio::test]
async fn an_answer_from_anywhere_else_is_refused() {
    let w = World::new(true).await;
    let a = ok(&w.open_as(&w.auth, w.open_payload(true)).await);
    let b = ok(&w.open_as(&w.auth, w.open_payload(true)).await);
    let session_a = a["sessionId"].as_str().unwrap();
    let answer_b = w.witness.carry(&w.relationship, &b["document"]).await;

    // Session B's answer spliced into session A.
    let out = w.present_as(&w.auth, session_a, &answer_b).await;
    assert_eq!(code(&out), "vta/witness/present:responseInvalid");

    // A genuine answer with its challenge changed.
    let answer_a = w.witness.carry(&w.relationship, &a["document"]).await;
    let mut tampered = answer_a.clone();
    tampered["payload"]["challenge"] = json!("00".repeat(32));
    let out = w.present_as(&w.auth, session_a, &tampered).await;
    assert_eq!(code(&out), "vta/witness/present:responseInvalid");

    // Another witness answering the same thread.
    let impostor = Key::new();
    let mut forged: TrustTask<Value> = serde_json::from_value(answer_a.clone()).unwrap();
    forged.issuer = Some(impostor.did.clone());
    forged.proof = None;
    sign_in_place_with(&mut forged, &impostor.holder())
        .await
        .unwrap();
    let out = w
        .present_as(&w.auth, session_a, &serde_json::to_value(forged).unwrap())
        .await;
    assert_eq!(code(&out), "vta/witness/present:responseInvalid");

    // The genuine answer still works after all that.
    ok(&w.present_as(&w.auth, session_a, &answer_a).await);

    // A refusal is not an outcome.
    let refusal = json!({
        "id": urn(), "type": "https://trusttasks.org/spec/trust-task-error/0.5",
        "issuer": w.witness.did(), "recipient": w.relationship, "threadId": session_a,
        "payload": { "code": "witness/session/submit:presentationInvalid" },
    });
    let out = w.accept_as(&w.auth, session_a, &refusal).await;
    assert_eq!(code(&out), "vta/witness/accept:responseInvalid");
}

/// A genuinely signed answer whose VWC is not this session's is `vwcInvalid`, and nothing is
/// stored.
#[tokio::test]
async fn a_vwc_from_another_session_is_refused() {
    let w = World::new(true).await;
    let (_, _, _, other_outcome) = w.run_to_outcome(true).await;

    let opened = ok(&w.open_as(&w.auth, w.open_payload(true)).await);
    let session = opened["sessionId"].as_str().unwrap().to_string();
    let answer = w.witness.carry(&w.relationship, &opened["document"]).await;
    ok(&w.present_as(&w.auth, &session, &answer).await);

    // The witness's own key, answering this session with the other session's VWC.
    let mut forged: TrustTask<Value> = serde_json::from_value(json!({
        "id": urn(),
        "type": <trust_tasks_rs::specs::witness::session::submit::v0_2::Response
            as trust_tasks_rs::Payload>::TYPE_URI,
        "issuer": w.witness.did(),
        "recipient": w.relationship,
        "issuedAt": Utc::now().to_rfc3339(),
        "threadId": session,
        "payload": other_outcome["payload"].clone(),
    }))
    .unwrap();
    sign_in_place_with(&mut forged, &w.witness.key.holder())
        .await
        .unwrap();
    let out = w
        .accept_as(&w.auth, &session, &serde_json::to_value(forged).unwrap())
        .await;
    assert_eq!(code(&out), "vta/witness/accept:vwcInvalid");
    assert!(
        body(&out).to_string().contains("taskContext"),
        "{:#}",
        body(&out)
    );

    // Nothing stored under the other VWC's id beyond the session that produced it.
    let other_id = other_outcome["payload"]["vwc"]["id"].as_str().unwrap();
    assert!(
        crate::vault::storage::get(&w.state.vault_ks, other_id)
            .await
            .unwrap()
            .is_none(),
        "the earlier session was never accepted, and this one stored nothing"
    );
}

/// `sessionUnknown` is one answer: unknown, out of the caller's contexts, wrong state.
#[tokio::test]
async fn session_unknown_says_nothing_about_why() {
    let w = World::new(true).await;
    let opened = ok(&w.open_as(&w.auth, w.open_payload(true)).await);
    let session = opened["sessionId"].as_str().unwrap();
    let answer = w.witness.carry(&w.relationship, &opened["document"]).await;

    let unknown = w.present_as(&w.auth, "urn:uuid:nobody", &answer).await;
    let elsewhere = w
        .present_as(&claims(Role::Admin, OTHER), session, &answer)
        .await;
    let wrong_state = w.accept_as(&w.auth, session, &answer).await;
    assert_eq!(code(&unknown), "vta/witness/present:sessionUnknown");
    assert_eq!(code(&elsewhere), "vta/witness/present:sessionUnknown");
    assert_eq!(code(&wrong_state), "vta/witness/accept:sessionUnknown");
    assert_eq!(
        body(&unknown)["payload"]["message"],
        body(&elsewhere)["payload"]["message"]
    );
}

/// A session is continued only by the version that opened it (`vta/_shared/0.6` conventions):
/// a record whose session document is not a `witness/session/0.2` — one a 0.1 open left behind
/// — is `sessionUnknown` to the 0.2 tasks.
#[tokio::test]
async fn a_session_opened_at_another_version_is_unknown() {
    let w = World::new(true).await;
    let opened = ok(&w.open_as(&w.auth, w.open_payload(true)).await);
    let session = opened["sessionId"].as_str().unwrap();
    let answer = w.witness.carry(&w.relationship, &opened["document"]).await;

    let key = format!("session:{session}");
    let raw = w
        .state
        .witness_sessions_ks
        .get_raw(key.clone())
        .await
        .unwrap()
        .expect("the open session's record");
    let mut record: Value = serde_json::from_slice(&raw).unwrap();
    record["sessionDocument"]["type"] = json!("https://trusttasks.org/spec/witness/session/0.1");
    w.state
        .witness_sessions_ks
        .insert(key, &record)
        .await
        .unwrap();

    let out = w.present_as(&w.auth, session, &answer).await;
    assert_eq!(code(&out), "vta/witness/present:sessionUnknown");
}

// ── Custody and authorization ───────────────────────────────────────────

/// A caller who may not act where the relationship DID's key is held cannot act as it, and the
/// refusal reads the same as for a DID this VTA does not hold at all.
#[tokio::test]
async fn key_custody_refuses_another_contexts_relationship_did() {
    let w = World::new(true).await;
    let other = claims(Role::Admin, OTHER);
    let out = w.open_as(&other, w.open_payload(true)).await;
    assert_eq!(code(&out), "permissionDenied", "{:#}", body(&out));

    let mut p = w.open_payload(false);
    p["relationshipDid"] = json!(Key::new().did);
    let out = w.open_as(&w.auth, p).await;
    assert_eq!(code(&out), "permissionDenied");

    // A member DID this VTA does not hold.
    let mut p = w.open_payload(true);
    p["membership"]["memberDid"] = json!(Key::new().did);
    let out = w.open_as(&w.auth, p).await;
    assert_eq!(code(&out), "permissionDenied");
}

/// `witness-request` is required, and `sign` is not it: an `application` caller holds `sign`
/// and is refused.
#[tokio::test]
async fn sign_alone_does_not_satisfy_witness_request() {
    let w = World::new(true).await;
    assert!(vti_common::acl::role_has_capability(
        &Role::Application,
        Capability::Sign
    ));
    let out = w
        .open_as(&claims(Role::Application, CTX), w.open_payload(true))
        .await;
    assert_eq!(code(&out), "permissionDenied");
    assert!(body(&out).to_string().contains("WitnessRequest"));
}

// ── vta/witness/list ────────────────────────────────────────────────────

impl World {
    async fn list_as(&self, auth: &AuthClaims, payload: Value) -> TrustTaskOutcome {
        handle_list(
            &self.state,
            auth,
            doc(uris::TASK_VTA_WITNESS_LIST_0_1, payload),
        )
        .await
    }

    /// A whole round, accepted: the accept answer's payload.
    async fn witnessed(&self) -> Value {
        let (session, _, _, outcome) = self.run_to_outcome(true).await;
        ok(&self.accept_as(&self.auth, &session, &outcome).await)
    }
}

/// What accept answered is what list reads back: the same handle, witness, digest, and both
/// evidence documents byte for byte — never rebuilt or re-signed.
#[tokio::test]
async fn list_reads_back_what_accept_stored_byte_for_byte() {
    let w = World::new(true).await;
    let accepted = w.witnessed().await;

    let listed = ok(&w.list_as(&w.auth, json!({})).await);
    let entries = listed["witnessings"].as_array().unwrap();
    assert_eq!(entries.len(), 1, "{listed:#}");
    let e = &entries[0];
    assert_eq!(e["credentialId"], accepted["credentialId"]);
    assert_eq!(e["witness"], accepted["witness"]);
    assert_eq!(e["relationshipDid"], w.relationship);
    assert_eq!(e["vwcDigestMultibase"], accepted["vwcDigestMultibase"]);
    assert!(e["acceptedAt"].as_str().is_some());
    for part in ["session", "outcome"] {
        assert_eq!(
            serde_json::to_string(&e["evidence"][part]).unwrap(),
            serde_json::to_string(&accepted["evidence"][part]).unwrap(),
            "evidence.{part} is returned exactly as stored"
        );
    }
    assert_eq!(listed["truncated"], false);
    assert!(listed.get("cursor").is_none(), "{listed:#}");
}

/// Both filters apply, and a filter that matches nothing is an empty page.
#[tokio::test]
async fn list_applies_its_filters() {
    let w = World::new(true).await;
    w.witnessed().await;
    let count = |v: Value| v["witnessings"].as_array().unwrap().len();

    let rel = ok(&w
        .list_as(&w.auth, json!({ "relationshipDid": w.relationship }))
        .await);
    assert_eq!(count(rel), 1);
    let by_witness = ok(&w
        .list_as(&w.auth, json!({ "witness": w.witness.did() }))
        .await);
    assert_eq!(count(by_witness), 1);
    let other_rel = ok(&w
        .list_as(&w.auth, json!({ "relationshipDid": w.counterparty }))
        .await);
    assert_eq!(count(other_rel), 0);
    let other_witness = ok(&w
        .list_as(&w.auth, json!({ "witness": Key::new().did }))
        .await);
    assert_eq!(count(other_witness), 0);
}

/// A DID this agent does not hold, and one held where the caller cannot act, answer the same
/// empty page — never a refusal — so the listing says nothing about DIDs the caller cannot see.
#[tokio::test]
async fn list_answers_unreachable_and_unknown_alike() {
    let w = World::new(true).await;
    w.witnessed().await;

    let elsewhere = claims(Role::Admin, OTHER);
    let unreachable = w
        .list_as(&elsewhere, json!({ "relationshipDid": w.relationship }))
        .await;
    let unknown = w
        .list_as(&w.auth, json!({ "relationshipDid": Key::new().did }))
        .await;
    let everything_elsewhere = w.list_as(&elsewhere, json!({})).await;
    for out in [&unreachable, &unknown, &everything_elsewhere] {
        assert_eq!(
            ok(out),
            json!({ "witnessings": [], "truncated": false }),
            "{:#}",
            body(out)
        );
    }
}

/// Oldest first, `pageSize` honoured, a cursor that continues without repeating, and one it
/// cannot honour is `cursorInvalid`.
#[tokio::test]
async fn list_pages_oldest_first_with_an_opaque_cursor() {
    let w = World::new(true).await;
    let mut ids = Vec::new();
    for _ in 0..3 {
        ids.push(w.witnessed().await["credentialId"].clone());
    }

    let first = ok(&w.list_as(&w.auth, json!({ "pageSize": 2 })).await);
    assert_eq!(first["truncated"], true, "{first:#}");
    let cursor = first["cursor"]
        .as_str()
        .expect("a cursor to continue")
        .to_string();
    let second = ok(&w
        .list_as(&w.auth, json!({ "pageSize": 2, "cursor": cursor }))
        .await);
    assert_eq!(second["truncated"], false, "{second:#}");
    assert!(second.get("cursor").is_none());

    let seen: Vec<Value> = first["witnessings"]
        .as_array()
        .unwrap()
        .iter()
        .chain(second["witnessings"].as_array().unwrap())
        .map(|e| e["credentialId"].clone())
        .collect();
    assert_eq!(seen.len(), 3, "every stored VWC once: {seen:?}");
    let mut sorted = seen.clone();
    sorted.sort_by_key(|v| v.to_string());
    let mut expected = ids.clone();
    expected.sort_by_key(|v| v.to_string());
    assert_eq!(sorted, expected);
    let at: Vec<String> = first["witnessings"]
        .as_array()
        .unwrap()
        .iter()
        .chain(second["witnessings"].as_array().unwrap())
        .map(|e| e["acceptedAt"].as_str().unwrap().to_string())
        .collect();
    let mut ordered = at.clone();
    ordered.sort();
    assert_eq!(at, ordered, "oldest first");

    for bad in ["not-a-cursor", "w1.!!!", "w1.Zm9v"] {
        let out = w.list_as(&w.auth, json!({ "cursor": bad })).await;
        assert_eq!(code(&out), "vta/witness/list:cursorInvalid", "{bad}");
    }
}

/// Only active vault entries are listed: an archived VWC is not.
#[tokio::test]
async fn list_omits_an_archived_witness_credential() {
    let w = World::new(true).await;
    let accepted = w.witnessed().await;
    let id = accepted["credentialId"].as_str().unwrap();
    let mut stored = crate::vault::storage::get(&w.state.vault_ks, id)
        .await
        .unwrap()
        .unwrap();
    stored.lifecycle = vti_common::vault::VaultStatus::Archived;
    crate::vault::storage::put(&w.state.vault_ks, &stored)
        .await
        .unwrap();
    let listed = ok(&w.list_as(&w.auth, json!({})).await);
    assert_eq!(listed["witnessings"], json!([]));
}

/// Gated like the family: `sign` alone is not `witness-request`.
#[tokio::test]
async fn list_needs_witness_request_not_sign() {
    let w = World::new(true).await;
    let out = w.list_as(&claims(Role::Application, CTX), json!({})).await;
    assert_eq!(code(&out), "permissionDenied");
}

// ── open's other refusals ───────────────────────────────────────────────

#[tokio::test]
async fn open_refuses_what_cannot_succeed_before_anything_is_disclosed() {
    let w = World::new(true).await;

    let mut p = w.open_payload(true);
    p["relationshipCredentialId"] = json!("no-such-credential");
    assert_eq!(
        code(&w.open_as(&w.auth, p).await),
        "vta/witness/open:notFound"
    );

    // A VRC naming somebody else.
    let wrong = w.vrc(&Key::new().did).await;
    w.store("vrc-wrong", wrong).await;
    let mut p = w.open_payload(true);
    p["relationshipCredentialId"] = json!("vrc-wrong");
    assert_eq!(
        code(&w.open_as(&w.auth, p).await),
        "vta/witness/open:credentialMismatch"
    );

    // The VMC names the member DID, not the relationship DID.
    assert_eq!(
        code(&w.open_as(&w.auth, w.open_payload(false)).await),
        "vta/witness/open:credentialMismatch"
    );

    // The witness is one of the parties.
    let mut p = w.open_payload(true);
    p["witness"] = json!(w.counterparty);
    assert_eq!(code(&w.open_as(&w.auth, p).await), "malformedRequest");

    // Nothing above left a session behind.
    assert!(
        w.state
            .witness_sessions_ks
            .prefix_iter_raw("session:")
            .await
            .unwrap()
            .is_empty()
    );
}

/// A credential changed after open is not presented.
#[tokio::test]
async fn present_refuses_a_credential_changed_since_open() {
    let w = World::new(true).await;
    let opened = ok(&w.open_as(&w.auth, w.open_payload(true)).await);
    let session = opened["sessionId"].as_str().unwrap();
    let answer = w.witness.carry(&w.relationship, &opened["document"]).await;
    let reissued = w.vrc(&w.counterparty.clone()).await;
    w.store("vrc-1", reissued).await;
    let out = w.present_as(&w.auth, session, &answer).await;
    assert_eq!(code(&out), "vta/witness/present:credentialMismatch");
}