openvtc-core 0.3.1

OpenVTC Core Library
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
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
//! The whole exchange between an applicant and a vetter, message by message,
//! through the same [`super::inbound::handle`] the TUI's dispatch calls.
//!
//! Each party keeps its own book and account; the only thing that passes
//! between them is a DIDComm `Message`, built and signed the way the client
//! sends it. Nothing here touches a network: every DID is a `did:key`.

use affinidi_data_integrity::{DataIntegrityProof, SignOptions};
use affinidi_tdk::didcomm::Message;
use affinidi_tdk::secrets_resolver::secrets::Secret;
use chrono::{Duration, Utc};
use dtg_credentials::DTGCredential;
use serde_json::{Value, json};
use trust_tasks_rs::TrustTask;
use uuid::Uuid;
use vta_sdk::protocols::join_requests::{JOIN_REQUEST_MANIFEST_0_2_RESPONSE_TYPE, manifest};
use vta_sdk::protocols::vetting::{
    VETTED_PREDICATE, VETTER_ROLE, VETTING_DECLINE_TYPE, VETTING_REQUEST_ERR_INVALID_TICKET,
    VETTING_REQUEST_ERR_NOT_ELIGIBLE, VETTING_REQUEST_TYPE, VETTING_SESSION_TYPE,
    VETTING_VETTER_PROFILE_ERR_NOT_ELIGIBLE, VETTING_VETTER_RESEND_ERR_NOT_GRANTED, VettingMethod,
    VettingRelationship, VettingRequirements, decline, request, revoke_statement, session, vetters,
};
use vta_sdk::trust_task_proof::TrustTaskVmResolver;
use vta_sdk::vetting::card::sign_card;
use vta_sdk::vetting::statement::sign_statement;
use vta_sdk::vetting::status::StatusCheck;

use super::VettingBook;
use super::applicant::{
    ApplicantError, Application, ChosenFace, GrantStatus, NextStep, RequestDraft, RequestState,
    TicketUriError, VetterEligibility,
};
use super::book::{Knowledge, VetterPolicy};
use super::inbound::{Context, Handled, Notice, Reply, handle};
use super::queries::{CommunityAnswer, CommunityQuery, QueryKind};
use super::registry::{ProfileDraft, ProfileState};
use super::tickets::{DEFAULT_VALIDITY, Ticket};
use super::vetter::{Attestation, DeskState};
use super::wire::{
    self,
    tests::{did, secret},
};
use crate::config::account::{Account, CommunityRecord, PersonaId};
use crate::persona::disclosure::ReleasedClaim;

/// The community is a `did:key` too, so the role credentials it signs verify
/// offline. [`the_community_is_its_key`] holds the two together.
const COMMUNITY: &str = "did:key:z6MkkckEJvRiDoUSv2KFGPFuUoNjJbWTZUvWThqshF7g1u4p";
const COMMUNITY_SEED: u8 = 0xC0;
/// A `requirementsDigest` the published criterion accepts: base58btc, at least
/// 16 characters.
const DIGEST: &str = "zQmbWqxBEKC3P8tqsKc98xmWNzrzDtRLMiMPL8wBuTGsMnR";

/// A listing request with no filters at all.
fn unfiltered_list() -> vetters::list::v0_1::Payload {
    vetters::list::v0_1::Payload::try_from(vetters::list::v0_1::Payload::builder()).unwrap()
}

/// A spoken ticket in the published form — upper-case Crockford base32.
fn code_ticket(code: &str) -> request::v0_1::Ticket {
    request::v0_1::Ticket::ShortCodeTicket(
        request::v0_1::ShortCodeTicket::try_from(
            request::v0_1::ShortCodeTicket::builder().code(code),
        )
        .expect("a Crockford code"),
    )
}

/// A credential-issue's credential, verified as the dispatcher's off-loop job
/// verifies it; `None` for any other message.
async fn verified_delivery(
    message: &Message,
    sender: &str,
    resolver: &affinidi_did_resolver_cache_sdk::DIDCacheClient,
) -> Option<
    Result<
        crate::issued_credential::VerifiedIssuedCredential,
        crate::issued_credential::IssuedCredentialError,
    >,
> {
    if message.typ != vta_sdk::protocols::credential_exchange::ISSUE {
        return None;
    }
    crate::messaging::credential_in_issue(message)?;
    Some(
        crate::issued_credential::verify_issued_delivery(
            &message.body,
            sender,
            resolver,
            Utc::now(),
        )
        .await,
    )
}

/// A DID resolver. Every DID here is a `did:key`, which resolves locally.
async fn did_resolver() -> affinidi_did_resolver_cache_sdk::DIDCacheClient {
    affinidi_did_resolver_cache_sdk::DIDCacheClient::new(
        affinidi_did_resolver_cache_sdk::config::DIDCacheConfigBuilder::default().build(),
    )
    .await
    .expect("a DID resolver")
}

#[test]
fn the_community_is_its_key() {
    assert_eq!(did(&secret(COMMUNITY_SEED)), COMMUNITY);
}

/// A community role credential — a VAC conferring `role:<role>` in
/// `community`'s scope, `issuerScope` public, `maxAttenuation` 0 — signed by
/// `issuer`. `issuer` other than `community` is a forgery: authority in a scope
/// the signer does not govern.
fn role_vac(issuer: &Secret, community: &str, subject: &str, role: &str) -> DTGCredential {
    let now = Utc::now();
    DTGCredential::new_vac(
        did(issuer),
        dtg_credentials::IssuerScope::Public,
        subject.to_string(),
        community.to_string(),
        vec![vta_sdk::protocols::vetting::role_action(role)],
        now - chrono::Duration::minutes(1),
        now + chrono::Duration::days(365),
    )
    .unwrap()
    .with_max_attenuation(0)
    .unwrap()
    .with_id(wire::new_id())
}

/// A community role credential, signed by `issuer`.
async fn role_credential(issuer: &Secret, community: &str, subject: &str, role: &str) -> Value {
    let mut credential = role_vac(issuer, community, subject, role);
    credential.sign(issuer, None).await.unwrap();
    serde_json::to_value(&credential).unwrap()
}

/// `credential-exchange/issue` from `from`, as a community delivers.
/// `credential-exchange/issue` as a community pushes it: a Trust Task document
/// signed by `issuer` under `authentication`.
async fn delivery(credential: &Value, issuer: &Secret) -> Message {
    let document: TrustTask<Value> = serde_json::from_value(json!({
        "id": format!("urn:uuid:{}", wire::new_id()),
        "type": vta_sdk::protocols::credential_exchange::ISSUE,
        "issuer": did(issuer),
        "recipient": "did:key:zTheMember",
        "issuedAt": Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
        "payload": { "credential_response": { "credential": credential } },
    }))
    .expect("an issue document");
    signed(document, issuer).await
}

/// Sign a reply the way `wire::send_reply` does: presentation first.
async fn signed_reply(reply: Reply, signer: &Secret) -> Message {
    let mut document = reply.document;
    if let Some(eligibility) = reply.eligibility {
        wire::attach_eligibility(&mut document, signer, eligibility)
            .await
            .unwrap();
    }
    signed(document, signer).await
}

struct Party {
    secret: Secret,
    did: String,
    persona: PersonaId,
    book: VettingBook,
    account: Account,
    seen: crate::operational::SeenDocuments,
}

impl Party {
    fn new(seed: u8) -> Self {
        let secret = secret(seed);
        Self {
            did: did(&secret),
            secret,
            persona: PersonaId::new(),
            book: VettingBook::default(),
            account: Account::default(),
            seen: crate::operational::SeenDocuments::default(),
        }
    }

    fn member_of(mut self, community: &str) -> Self {
        let mut record = CommunityRecord::new_pending(
            community.to_string(),
            None,
            "openvtc/test".to_string(),
            self.persona,
            Uuid::new_v4(),
            Utc::now(),
        );
        record.activate(Utc::now());
        self.account.add_membership(record);
        self
    }

    /// The community names this party a vetter, and delivers the credential.
    async fn named_vetter(&mut self) {
        let credential = role_credential(
            &secret(COMMUNITY_SEED),
            COMMUNITY,
            &self.did.clone(),
            VETTER_ROLE,
        )
        .await;
        let handled = self
            .receive(
                &delivery(&credential, &secret(COMMUNITY_SEED)).await,
                COMMUNITY,
            )
            .await;
        assert!(matches!(handled.notice, Some(Notice::VetterGranted { .. })));
    }

    async fn receive(&mut self, message: &Message, sender: &str) -> Handled {
        self.try_receive(message, sender)
            .await
            .expect("a vetting message is claimed")
    }

    /// [`Self::receive`] for a message the vetting handler may not claim at all.
    async fn try_receive(&mut self, message: &Message, sender: &str) -> Option<Handled> {
        let resolver = TrustTaskVmResolver::did_key_only();
        let did_resolver = did_resolver().await;
        // As the dispatcher does off the loop: a delivered credential is
        // verified before the handler sees it.
        let issued = verified_delivery(message, sender, &did_resolver).await;
        let ctx = Context {
            account: &self.account,
            resolver: &resolver,
            did_resolver: &did_resolver,
            issued_credential: issued.as_ref(),
            community_answer: None,
            recipient: Some((self.persona, &self.did)),
            now: Utc::now(),
        };
        handle(&mut self.book, &ctx, &mut self.seen, message, sender).await
    }

    /// [`Self::receive`], with the community answer already checked off the
    /// loop, as the dispatcher passes it.
    async fn receive_checked(
        &mut self,
        message: &Message,
        sender: &str,
        answer: &Result<
            crate::operational::VerifiedOperational,
            crate::operational::OperationalError,
        >,
    ) -> Handled {
        let resolver = TrustTaskVmResolver::did_key_only();
        let did_resolver = did_resolver().await;
        let ctx = Context {
            account: &self.account,
            resolver: &resolver,
            did_resolver: &did_resolver,
            issued_credential: None,
            community_answer: Some(answer),
            recipient: Some((self.persona, &self.did)),
            now: Utc::now(),
        };
        handle(&mut self.book, &ctx, &mut self.seen, message, sender)
            .await
            .expect("a vetting message is claimed")
    }

    fn application(&mut self) -> &mut super::applicant::Application {
        self.book
            .application_mut(COMMUNITY, self.persona)
            .expect("application started")
    }
}

async fn signed(mut document: TrustTask<Value>, signer: &Secret) -> Message {
    wire::sign(&mut document, signer).await.unwrap();
    wire::to_message(&document).unwrap()
}

fn requirements() -> VettingRequirements {
    serde_json::from_value(json!({
        "version": "0.1",
        "statementType": VETTED_PREDICATE,
        "minStatements": 1,
        "minByMethod": { "inPerson": 1 },
        "acceptedMethods": ["inPerson", "video"],
        "requiredClaims": ["name.legal"],
        "eligibleVetters": { "role": "vetter" }
    }))
    .unwrap()
}

/// The community's manifest 0.2 body.
fn manifest_body() -> manifest::v0_2::Response {
    manifest_with(Some(requirements()), None)
}

/// A manifest 0.2 body carrying `vetting` and `branding`.
fn manifest_with(
    vetting: Option<VettingRequirements>,
    branding: Option<manifest::v0_2::CommunityBranding>,
) -> manifest::v0_2::Response {
    let criterion = manifest::v0_2::Criterion::try_from(
        manifest::v0_2::Criterion::builder()
            .id("vetted")
            .presentation_definition(serde_json::Map::new())
            .vetting(vetting)
            .requirements_digest(Some(
                manifest::v0_2::DigestMultibase::try_from(DIGEST).unwrap(),
            )),
    )
    .unwrap();
    manifest::v0_2::Response::try_from(
        manifest::v0_2::Response::builder()
            .community_did(COMMUNITY)
            .criteria(vec![criterion])
            .branding(branding),
    )
    .unwrap()
}

/// A manifest payload as the wire carries it, with `vetting.ext` / `vetting.extCritical`
/// added to the criterion — the members a generated type drops, so the test has to build them
/// on the raw JSON exactly as a community would send them.
fn manifest_raw_with_ext(ext: Value, critical: Option<Value>) -> Value {
    let mut raw = serde_json::to_value(manifest_body()).unwrap();
    let vetting = raw["criteria"][0]["vetting"].as_object_mut().unwrap();
    vetting.insert("ext".into(), ext);
    if let Some(c) = critical {
        vetting.insert("extCritical".into(), c);
    }
    raw
}

/// Real published parameters: the keys have to decode, because adopting the criterion starts
/// the applicant's engine against them.
fn hidden_params() -> Value {
    use openvtc_vetting_pcs::{scheme::key_text, vtc::Vtc};
    use rand::SeedableRng;
    let mut rng = rand::rngs::StdRng::seed_from_u64(0x0BED);
    let vtc = Vtc::new(
        COMMUNITY,
        "2026-10",
        serde_json::to_value(requirements()).unwrap(),
        &mut rng,
    )
    .expect("a community");
    json!({
        "suite": super::hidden::SUITE,
        "helperKey": key_text(vtc.hvk()).unwrap(),
        "tokenKey": key_text(vtc.tvk()).unwrap(),
        "vetterLabels": ["vetter/2026-10"],
        "tokenLabels": [vtc.current_token_label()]
    })
}

#[tokio::test]
async fn an_application_adopts_the_hidden_vetting_parameters_a_community_publishes() {
    let mut party = Party::new(1);
    party
        .book
        .start_application(COMMUNITY, party.persona, &party.did, Utc::now())
        .expect("an application starts");
    let raw = manifest_raw_with_ext(
        json!({ super::hidden::HIDDEN_VETTING_NS: hidden_params() }),
        Some(json!([super::hidden::HIDDEN_VETTING_NS])),
    );
    let changed = party
        .application()
        .adopt_manifest(&manifest_body(), &raw)
        .expect("the criterion is one this build implements");
    assert!(changed);
    let hidden = party
        .application()
        .hidden
        .clone()
        .expect("the parameters were adopted");
    let published = hidden_params();
    assert_eq!(hidden.helper_key, published["helperKey"].as_str().unwrap());
    assert_eq!(hidden.token_key, published["tokenKey"].as_str().unwrap());
    assert_eq!(hidden.vetter_labels, vec!["vetter/2026-10".to_string()]);
    // Adopting a hidden criterion mints this application's own key, which is what a vetter
    // attests and what the proof is built from.
    assert!(party.application().hidden_id().is_some());
    // The named members are adopted exactly as before.
    assert!(party.application().requirements.is_some());
}

#[tokio::test]
async fn a_critical_namespace_this_build_cannot_honour_stops_the_application() {
    let mut party = Party::new(1);
    party
        .book
        .start_application(COMMUNITY, party.persona, &party.did, Utc::now())
        .expect("an application starts");
    let raw = manifest_raw_with_ext(
        json!({ "com.example.some-scheme": { "a": 1 } }),
        Some(json!(["com.example.some-scheme"])),
    );
    let err = party
        .application()
        .adopt_manifest(&manifest_body(), &raw)
        .expect_err("a marked namespace we do not implement must refuse");
    assert!(matches!(
        err,
        super::applicant::ApplicantError::Hidden(super::hidden::HiddenError::UnsupportedExtension(
            _
        ))
    ));
    // Nothing was adopted: the application does not carry on against requirements whose
    // meaning it could not honour.
    assert!(party.application().hidden.is_none());
    assert!(party.application().requirements.is_none());
}

#[tokio::test]
async fn an_unmarked_namespace_this_build_does_not_implement_is_ignored() {
    let mut party = Party::new(1);
    party
        .book
        .start_application(COMMUNITY, party.persona, &party.did, Utc::now())
        .expect("an application starts");
    let raw = manifest_raw_with_ext(json!({ "com.example.hint": { "a": 1 } }), None);
    party
        .application()
        .adopt_manifest(&manifest_body(), &raw)
        .expect("an unmarked namespace is advisory");
    assert!(party.application().hidden.is_none());
    assert!(party.application().requirements.is_some());
}

/// The community's manifest answer to `to`, as a VTC sends an operational
/// document: signed with its authentication key, addressed, dated.
async fn manifest_reply(to: &str) -> Message {
    signed_manifest(to, manifest_body()).await
}

/// `body` as the community's signed manifest answer to `to`.
async fn signed_manifest(to: &str, body: impl serde::Serialize) -> Message {
    let document = crate::operational::test_support::sign(
        json!({
            "id": wire::new_id(),
            "type": JOIN_REQUEST_MANIFEST_0_2_RESPONSE_TYPE,
            "issuer": COMMUNITY,
            "recipient": to,
            "issuedAt": Utc::now().to_rfc3339(),
            "payload": body,
        }),
        &secret(COMMUNITY_SEED),
    )
    .await;
    Message::build(
        wire::new_id(),
        JOIN_REQUEST_MANIFEST_0_2_RESPONSE_TYPE.to_string(),
        document,
    )
    .from(COMMUNITY.to_string())
    .thid(wire::new_id())
    .finalize()
}

/// An applicant with requirements in hand, and a vetter with a ticket for them.
async fn ready() -> (Party, Party, request::v0_1::Ticket) {
    let mut applicant = Party::new(1);
    let mut vetter = Party::new(2).member_of(COMMUNITY);
    vetter.named_vetter().await;
    let now = Utc::now();
    applicant
        .book
        .start_application(COMMUNITY, applicant.persona, &applicant.did, now)
        .unwrap();
    let handled = applicant
        .receive(&manifest_reply(&applicant.did.clone()).await, COMMUNITY)
        .await;
    assert!(matches!(
        handled.notice,
        Some(Notice::RequirementsUpdated { .. })
    ));
    let ticket = Ticket::issue(COMMUNITY, vetter.persona, vec![], 1, DEFAULT_VALIDITY, now);
    let presented = ticket.code_presentation().unwrap();
    vetter.book.tickets.push(ticket);
    (applicant, vetter, presented)
}

async fn request(applicant: &mut Party, vetter: &Party, ticket: request::v0_1::Ticket) -> Message {
    let id = wire::new_id();
    let vetter_did = vetter.did.clone();
    let body = applicant
        .application()
        .prepare_request(
            &id,
            &vetter_did,
            ticket,
            RequestDraft::default(),
            Utc::now(),
        )
        .unwrap();
    let doc = wire::document(VETTING_REQUEST_TYPE, &applicant.did, &vetter.did, id, &body).unwrap();
    signed(doc, &applicant.secret).await
}

/// Request, accept and open a session. Returns the vetter's request id and the
/// session document.
async fn in_session(applicant: &mut Party, vetter: &mut Party) -> (String, TrustTask<Value>) {
    let ticket = vetter.book.tickets[0].code_presentation().unwrap();
    let message = request(applicant, vetter, ticket).await;
    let handled = vetter.receive(&message, &applicant.did).await;
    let Some(Notice::RequestAccepted { request_id, .. }) = handled.notice.clone() else {
        panic!("the request is accepted");
    };
    let reply = handled.reply.expect("an accepted request is answered");
    assert!(
        reply.eligibility.is_some(),
        "a named vetter presents the grant"
    );
    let message = signed_reply(reply, &vetter.secret).await;
    let handled = applicant.receive(&message, &vetter.did).await;
    assert!(matches!(
        handled.notice,
        Some(Notice::VetterAccepted {
            shown_eligible: true,
            ..
        })
    ));
    let accepted = applicant.application().requests.last().unwrap().clone();
    assert!(matches!(
        accepted.eligibility,
        Some(VetterEligibility::Shown { .. })
    ));

    let session_id = wire::new_id();
    let body = vetter
        .book
        .open_session(
            &request_id,
            VettingMethod::InPerson,
            vec!["name.legal".into()],
            vec![],
            &session_id,
            Utc::now(),
        )
        .unwrap();
    let doc = wire::document(
        VETTING_SESSION_TYPE,
        &vetter.did,
        &applicant.did,
        session_id,
        &body,
    )
    .unwrap();
    // The statement cites this document by task digest, which leaves out the
    // proof — so the unsigned document digests the same as the signed one the
    // applicant receives.
    vetter
        .book
        .record_session_document(&request_id, serde_json::to_value(&doc).unwrap())
        .unwrap();
    (request_id, doc)
}

#[tokio::test]
async fn an_applicant_is_vetted_end_to_end() {
    let (mut applicant, mut vetter, _) = ready().await;
    let resolver = TrustTaskVmResolver::did_key_only();
    let (request_id, session_doc) = in_session(&mut applicant, &mut vetter).await;

    // The session reaches the applicant; both screens show the same code.
    let message = signed(session_doc.clone(), &vetter.secret).await;
    let handled = applicant.receive(&message, &vetter.did).await;
    let Some(Notice::SessionOpened {
        session_id,
        match_code,
        ..
    }) = handled.notice.clone()
    else {
        panic!("the session opens");
    };
    assert_eq!(
        Some(match_code.as_str()),
        vetter.book.desk_entry(&request_id).unwrap().match_code()
    );
    assert!(
        handled.notice.unwrap().task().is_some(),
        "the applicant must act"
    );

    // The applicant signs a card and sends it back.
    let draft = applicant
        .application()
        .card_draft(
            &session_id,
            vec![
                session::v0_1::VettingCardClaim::try_from(
                    session::v0_1::VettingCardClaim::builder()
                        .type_("name.legal")
                        .value(json!("Alice Example"))
                        .provenance("selfAsserted"),
                )
                .unwrap(),
            ],
            Utc::now(),
        )
        .unwrap();
    let card = sign_card(draft, &applicant.secret).await.unwrap();
    applicant
        .application()
        .record_card(&session_id, &card, &resolver, Utc::now())
        .await
        .unwrap();
    // The card travels as it was signed: its digest is what the statement names.
    let doc = wire::response(&session_doc, &json!({ "card": card })).unwrap();
    let message = signed(doc, &applicant.secret).await;
    let handled = vetter.receive(&message, &applicant.did).await;
    assert!(matches!(handled.notice, Some(Notice::CardReceived { .. })));

    // The vetter checks the person and attests.
    let draft = vetter
        .book
        .statement_draft(
            &request_id,
            &vetter.did,
            Attestation {
                method: VettingMethod::InPerson,
                document_classes: vec!["passport".into()],
                claims_verified: vec!["name.legal".into()],
                liveness_confirmed: true,
                declared_relationship: VettingRelationship::None,
                attestation_text_digest: None,
            },
            Utc::now(),
        )
        .unwrap();
    let statement = sign_statement(draft, &vetter.secret).await.unwrap();
    let issued = vetter
        .book
        .record_statement(&request_id, &statement, &resolver, Utc::now())
        .await
        .unwrap();
    assert!(matches!(
        vetter.book.desk_entry(&request_id).unwrap().state,
        DeskState::Attested { .. }
    ));

    // The statement reaches the applicant, who now meets the requirements.
    let message = wire::credential_delivery(
        &vetter.did,
        &applicant.did,
        &statement,
        &session_id,
        &vetter.secret,
    )
    .await
    .unwrap();
    let handled = applicant.receive(&message, &vetter.did).await;
    assert!(matches!(
        handled.notice,
        Some(Notice::StatementReceived { .. })
    ));
    let application = applicant.application();
    assert!(application.checklist(Utc::now()).unwrap().satisfied());
    assert_eq!(application.presentable_statements(Utc::now()).len(), 1);
    assert_eq!(
        application.join_extensions(super::protocol::JoinProtocol::V0_2)["requirementsDigest"],
        DIGEST
    );
    assert!(
        application
            .join_extensions(super::protocol::JoinProtocol::V0_3)
            .get("requirementsDigest")
            .is_none(),
        "0.3 names the criterion in the submit, not in extensions"
    );

    // Later, the vetter withdraws it.
    let notice_id = wire::new_id();
    let (body, _) = vetter
        .book
        .withdrawal(
            &issued.id,
            Some(revoke_statement::v0_1::PayloadReason::Mistake),
            &notice_id,
            Utc::now(),
        )
        .unwrap();
    assert_eq!(
        body.statement_digest_multibase.as_str(),
        issued.digest_multibase
    );
    assert!(
        vetter
            .book
            .on_withdrawal_recorded(COMMUNITY, &notice_id, Utc::now())
            .is_some()
    );
}

/// What the face released, as the disclosure reports it.
fn released(name: Option<&str>) -> Vec<ReleasedClaim> {
    vec![
        ReleasedClaim {
            claim_type: "name.legal".into(),
            value: name.map(|n| json!(n)),
            provenance: Some("selfAsserted".into()),
            stale: false,
        },
        ReleasedClaim {
            claim_type: "email.work".into(),
            value: Some(json!("alice@example.com")),
            provenance: Some("selfAsserted".into()),
            stale: false,
        },
    ]
}

/// A card's identity comes from the persona's face, and every later card has
/// to show what the first one did.
#[tokio::test]
async fn cards_come_from_the_face_and_keep_showing_the_same_identity() {
    let (mut applicant, mut vetter, _) = ready().await;
    let resolver = TrustTaskVmResolver::did_key_only();
    let (_, session_doc) = in_session(&mut applicant, &mut vetter).await;
    let message = signed(session_doc, &vetter.secret).await;
    let handled = applicant.receive(&message, &vetter.did).await;
    let Some(Notice::SessionOpened { session_id, .. }) = handled.notice else {
        panic!("the session opens");
    };
    let signer = applicant.secret.clone();
    let app = applicant.application();
    assert_eq!(app.requested_claims(&session_id), vec!["name.legal"]);

    // Only the session's claim types go on the card, and each needs a value a
    // vetter can read.
    let claims = app
        .card_claims(&session_id, &released(Some("Alice Example")))
        .unwrap();
    assert_eq!(claims.len(), 1);
    assert_eq!(claims[0].value, json!("Alice Example"));
    assert!(matches!(
        app.card_claims(&session_id, &released(None)),
        Err(ApplicantError::ValueWithheld(t)) if t == "name.legal"
    ));
    assert!(matches!(
        app.card_claims(&session_id, &[]),
        Err(ApplicantError::MissingClaim(_))
    ));

    let draft = app
        .card_draft(&session_id, claims.clone(), Utc::now())
        .unwrap();
    let card = sign_card(draft, &signer).await.unwrap();
    let sent = app
        .record_card(&session_id, &card, &resolver, Utc::now())
        .await
        .unwrap();
    app.record_sent_card(&session_id, sent, &claims, Utc::now())
        .unwrap();
    // The generated card claim has no `PartialEq`; what was kept is compared as
    // what it serialises to.
    assert_eq!(
        serde_json::to_value(&app.identity_claims).unwrap(),
        serde_json::to_value(&claims).unwrap()
    );

    // The face has changed since: the next card is refused before it is signed.
    assert!(matches!(
        app.card_claims(&session_id, &released(Some("Alicia Example"))),
        Err(ApplicantError::IdentityChanged(t)) if t == "name.legal"
    ));
}

#[tokio::test]
async fn without_a_ticket_there_is_no_answer_at_all() {
    let (mut applicant, mut vetter, _) = ready().await;
    let message = request(&mut applicant, &vetter, code_ticket("0000-0000")).await;
    let handled = vetter.receive(&message, &applicant.did).await;
    assert!(handled.reply.is_none() && handled.notice.is_none());
    assert!(vetter.book.desk.is_empty());
}

#[tokio::test]
async fn a_bad_scanned_ticket_is_refused_and_the_applicant_hears_why() {
    let (mut applicant, mut vetter, _) = ready().await;
    let ticket_id = vetter.book.tickets[0].id.clone();
    let scanned = request::v0_1::Ticket::QrTicket(
        request::v0_1::QrTicket::try_from(
            request::v0_1::QrTicket::builder()
                .ticket_id(ticket_id)
                .secret("A".repeat(43)),
        )
        .unwrap(),
    );
    let message = request(&mut applicant, &vetter, scanned).await;
    let handled = vetter.receive(&message, &applicant.did).await;
    let reply = handled.reply.expect("a scanned ticket is answered");
    assert_eq!(
        reply.document.payload["code"],
        VETTING_REQUEST_ERR_INVALID_TICKET
    );
    // The vetter hears about it too. A refusal used to leave nothing at all on
    // their side, so the one person who can issue a fresh ticket saw an empty
    // desk and no way to find out that anybody had tried.
    let Some(Notice::RequestRefused {
        applicant: who,
        code,
    }) = handled.notice
    else {
        panic!("the vetter is told a request was turned away");
    };
    assert_eq!(who, applicant.did);
    assert_eq!(code, VETTING_REQUEST_ERR_INVALID_TICKET);

    let message = signed(reply.document, &vetter.secret).await;
    let handled = applicant.receive(&message, &vetter.did).await;
    let refused = handled.notice.expect("the applicant is told");
    assert!(matches!(refused, Notice::VetterRefused { .. }));
    // In words, not just the wire code: "vetting/request:invalidTicket" under
    // a vetter's name reads as a fault in the software rather than as a ticket
    // that needs replacing.
    let said = refused.describe();
    assert!(said.contains(VETTING_REQUEST_ERR_INVALID_TICKET), "{said}");
    assert!(said.contains("Ask them for a fresh one"), "{said}");
    assert!(matches!(
        applicant.application().requests[0].state,
        RequestState::Refused { .. }
    ));
}

#[tokio::test]
async fn someone_who_is_not_a_member_cannot_vet() {
    let (mut applicant, _, _) = ready().await;
    let mut outsider = Party::new(3);
    let ticket = Ticket::issue(
        COMMUNITY,
        outsider.persona,
        vec![],
        1,
        DEFAULT_VALIDITY,
        Utc::now(),
    );
    let presented = ticket.code_presentation().unwrap();
    outsider.book.tickets.push(ticket);
    let message = request(&mut applicant, &outsider, presented).await;
    let handled = outsider.receive(&message, &applicant.did).await;
    assert_eq!(
        handled.reply.unwrap().document.payload["code"],
        VETTING_REQUEST_ERR_NOT_ELIGIBLE
    );
}

/// A vetter grant is taken only from the community's signed delivery. The
/// same grant, correctly signed by the community, in a bare `issue` body —
/// the shape a VTC sent before every `issue` was a document — makes nobody a
/// vetter.
#[tokio::test]
async fn a_bare_vetter_grant_delivery_is_refused() {
    let mut member = Party::new(6).member_of(COMMUNITY);
    let credential = role_credential(
        &secret(COMMUNITY_SEED),
        COMMUNITY,
        &member.did.clone(),
        VETTER_ROLE,
    )
    .await;
    let bare = Message::build(
        wire::new_id(),
        vta_sdk::protocols::credential_exchange::ISSUE.to_string(),
        json!({ "credential_response": { "credential": credential } }),
    )
    .from(COMMUNITY.to_string())
    .finalize();
    let resolver = TrustTaskVmResolver::did_key_only();
    let did_resolver = did_resolver().await;
    let ctx = Context {
        account: &member.account,
        resolver: &resolver,
        did_resolver: &did_resolver,
        issued_credential: None,
        community_answer: None,
        recipient: Some((member.persona, &member.did)),
        now: Utc::now(),
    };
    let handled = handle(
        &mut member.book,
        &ctx,
        &mut crate::operational::SeenDocuments::default(),
        &bare,
        COMMUNITY,
    )
    .await;
    assert!(
        handled.is_none_or(|h| h.notice.is_none()),
        "a bare delivery grants nothing"
    );
    assert!(member.book.vetter_grants.is_empty());
}

/// And a signed delivery by anyone but the community is refused before the
/// grant inside is looked at, even when the grant itself is the community's.
#[tokio::test]
async fn a_vetter_grant_relayed_by_another_party_is_refused() {
    let mut member = Party::new(7).member_of(COMMUNITY);
    let credential = role_credential(
        &secret(COMMUNITY_SEED),
        COMMUNITY,
        &member.did.clone(),
        VETTER_ROLE,
    )
    .await;
    let relay = secret(0xD7);
    let handled = member
        .receive(&delivery(&credential, &relay).await, &did(&relay))
        .await;
    assert!(handled.notice.is_none() && member.book.vetter_grants.is_empty());
}

/// Membership is not enough: the community has to have named the member a
/// vetter, or requests are refused before anything is recorded.
#[tokio::test]
async fn a_member_the_community_has_not_named_cannot_vet() {
    let (mut applicant, _, _) = ready().await;
    let mut member = Party::new(4).member_of(COMMUNITY);
    let ticket = Ticket::issue(
        COMMUNITY,
        member.persona,
        vec![],
        1,
        DEFAULT_VALIDITY,
        Utc::now(),
    );
    let presented = ticket.code_presentation().unwrap();
    member.book.tickets.push(ticket);
    let message = request(&mut applicant, &member, presented).await;
    let handled = member.receive(&message, &applicant.did).await;
    assert_eq!(
        handled.reply.unwrap().document.payload["code"],
        VETTING_REQUEST_ERR_NOT_ELIGIBLE
    );
    assert!(member.book.desk.is_empty());
}

/// Only the community a grant names can deliver it, and only to the persona
/// it names. A member's ordinary role credential is left for the join handler,
/// so it keeps its place.
#[tokio::test]
async fn a_vetter_grant_is_kept_only_from_its_community() {
    let mut member = Party::new(5).member_of(COMMUNITY);
    let impostor = secret(0xC1);
    // Authority in a scope the signer does not govern is not a community role
    // credential at all, so the vetting handler does not even claim it.
    let forged = role_credential(&impostor, COMMUNITY, &member.did.clone(), VETTER_ROLE).await;
    let handled = member
        .try_receive(&delivery(&forged, &impostor).await, &did(&impostor))
        .await;
    assert!(handled.is_none_or(|h| h.notice.is_none()) && member.book.vetter_grants.is_empty());

    let for_someone_else = role_credential(
        &secret(COMMUNITY_SEED),
        COMMUNITY,
        "did:key:zSomeoneElse",
        VETTER_ROLE,
    )
    .await;
    let handled = member
        .receive(
            &delivery(&for_someone_else, &secret(COMMUNITY_SEED)).await,
            COMMUNITY,
        )
        .await;
    assert!(handled.notice.is_none() && member.book.vetter_grants.is_empty());

    let ordinary = role_credential(
        &secret(COMMUNITY_SEED),
        COMMUNITY,
        &member.did.clone(),
        "member",
    )
    .await;
    let resolver = TrustTaskVmResolver::did_key_only();
    let did_resolver = did_resolver().await;
    let issued: Option<
        Result<
            crate::issued_credential::VerifiedIssuedCredential,
            crate::issued_credential::IssuedCredentialError,
        >,
    > = None;
    let ctx = Context {
        account: &member.account,
        resolver: &resolver,
        did_resolver: &did_resolver,
        issued_credential: issued.as_ref(),
        community_answer: None,
        recipient: Some((member.persona, &member.did)),
        now: Utc::now(),
    };
    assert!(
        handle(
            &mut member.book,
            &ctx,
            &mut crate::operational::SeenDocuments::default(),
            &delivery(&ordinary, &secret(COMMUNITY_SEED)).await,
            COMMUNITY
        )
        .await
        .is_none(),
        "an ordinary role credential is not vetting's"
    );

    member.named_vetter().await;
    assert!(
        member
            .book
            .vetter_grant(COMMUNITY, member.persona, Utc::now())
            .is_some()
    );
}

/// An acceptance that shows nothing is still an acceptance — the check is
/// advisory — but the applicant is told.
#[tokio::test]
async fn an_acceptance_without_a_grant_shown_is_recorded_as_such() {
    let (mut applicant, mut vetter, ticket) = ready().await;
    let message = request(&mut applicant, &vetter, ticket).await;
    let handled = vetter.receive(&message, &applicant.did).await;
    let mut reply = handled.reply.unwrap();
    reply.eligibility = None;
    let message = signed_reply(reply, &vetter.secret).await;
    let handled = applicant.receive(&message, &vetter.did).await;
    assert!(matches!(
        handled.notice,
        Some(Notice::VetterAccepted {
            shown_eligible: false,
            ..
        })
    ));
    assert_eq!(
        applicant.application().requests[0].eligibility,
        Some(VetterEligibility::NotShown)
    );
}

#[tokio::test]
async fn a_vetter_can_decline_without_a_reason() {
    let (mut applicant, mut vetter, _) = ready().await;
    let (request_id, _) = in_session(&mut applicant, &mut vetter).await;
    let body = vetter
        .book
        .decline(
            &request_id,
            Some(decline::v0_1::PayloadCode::NotComfortable),
            None,
            Utc::now(),
        )
        .unwrap();
    let doc = wire::document(
        VETTING_DECLINE_TYPE,
        &vetter.did,
        &applicant.did,
        wire::new_id(),
        &body,
    )
    .unwrap();
    let message = signed(doc, &vetter.secret).await;
    let handled = applicant.receive(&message, &vetter.did).await;
    assert!(matches!(handled.notice, Some(Notice::Declined { .. })));
    assert!(applicant.application().checklist(Utc::now()).is_some());
}

#[tokio::test]
async fn a_membership_credential_is_left_for_the_join_handler() {
    let mut applicant = Party::new(1);
    let vmc = json!({ "credential_response": { "credential": {
        "type": ["VerifiableCredential", "MembershipCredential"],
        "issuer": COMMUNITY
    } } });
    let message = Message::build(
        wire::new_id(),
        vta_sdk::protocols::credential_exchange::ISSUE.to_string(),
        vmc,
    )
    .from(COMMUNITY.to_string())
    .finalize();
    let resolver = TrustTaskVmResolver::did_key_only();
    let did_resolver = did_resolver().await;
    let issued: Option<
        Result<
            crate::issued_credential::VerifiedIssuedCredential,
            crate::issued_credential::IssuedCredentialError,
        >,
    > = None;
    let ctx = Context {
        account: &applicant.account,
        resolver: &resolver,
        did_resolver: &did_resolver,
        issued_credential: issued.as_ref(),
        community_answer: None,
        recipient: Some((applicant.persona, &applicant.did)),
        now: Utc::now(),
    };
    assert!(
        handle(
            &mut applicant.book,
            &ctx,
            &mut crate::operational::SeenDocuments::default(),
            &message,
            COMMUNITY
        )
        .await
        .is_none()
    );
}

#[tokio::test]
async fn a_vetter_asks_for_the_claims_the_community_requires() {
    let mut vetter = Party::new(2).member_of(COMMUNITY);
    assert_eq!(
        vetter.book.required_claims_for(COMMUNITY, None),
        (vec!["name.legal".to_string()], false),
        "without the manifest, the fallback — and it says so"
    );
    let handled = vetter
        .receive(&manifest_reply(&vetter.did.clone()).await, COMMUNITY)
        .await;
    assert!(handled.changed, "the criteria are remembered");
    let (claims, known) = vetter.book.required_claims_for(COMMUNITY, Some(DIGEST));
    assert!(known);
    assert_eq!(
        claims,
        requirements()
            .required_claims
            .iter()
            .flatten()
            .map(|c| c.as_str().to_string())
            .collect::<Vec<_>>()
    );
    assert!(
        !vetter
            .receive(&manifest_reply(&vetter.did.clone()).await, COMMUNITY)
            .await
            .changed,
        "the same manifest again changes nothing"
    );
}

#[tokio::test]
async fn the_communitys_decision_sla_is_known_once_its_manifest_is() {
    let (applicant, _, _) = ready().await;
    let persona = applicant.persona;
    assert_eq!(applicant.book.decision_sla(COMMUNITY, persona), None);

    let mut with_sla = Party::new(4);
    with_sla
        .book
        .start_application(COMMUNITY, with_sla.persona, &with_sla.did, Utc::now())
        .unwrap();
    let mut requirements = requirements();
    requirements.decision_sla = Some("P21D".try_into().unwrap());
    let body = manifest_with(Some(requirements), None);
    let reply = signed_manifest(&with_sla.did.clone(), body).await;
    with_sla.receive(&reply, COMMUNITY).await;
    assert_eq!(
        with_sla.book.decision_sla(COMMUNITY, with_sla.persona),
        chrono::Duration::try_days(21)
    );
}

// ----------------------------------------------------------------------------
// Questions put to the community: the vetter registry, resends, the manifest
// ----------------------------------------------------------------------------

/// The community's answer to `request`, as its dispatcher sends it: unsigned
/// (transport authenticates it) and threaded on the request.
/// The community answering `request`, signed as a VTC signs its success
/// responses.
async fn community_answer<P: serde::Serialize>(request: &TrustTask<Value>, payload: &P) -> Message {
    let document = wire::response(request, payload).unwrap();
    let mut message = wire::to_message(&document).unwrap();
    message.body = crate::operational::test_support::sign(
        serde_json::to_value(&document).unwrap(),
        &secret(COMMUNITY_SEED),
    )
    .await;
    message
}

/// The community refusing `request` with `code`.
fn community_refusal(request: &TrustTask<Value>, code: &str) -> Message {
    wire::to_message(&wire::refusal(request, code, Some("because")).unwrap()).unwrap()
}

fn asked(request: &TrustTask<Value>, persona: PersonaId, kind: QueryKind) -> CommunityQuery {
    CommunityQuery {
        document_id: request.id.clone(),
        community: COMMUNITY.into(),
        persona,
        kind,
        sent_at: Utc::now(),
    }
}

fn listed_vetter() -> vetters::list::v0_1::ListedVetter {
    serde_json::from_value(json!({
        "vetterDid": "did:key:zCarol",
        "displayName": "Carol",
        "languages": ["en", "cs"],
        "location": { "country": "CZ", "city": "Prague" },
        "methods": ["inPerson", "video"],
        "acceptsDocumentation": ["passport"],
        "contactHint": "find me at the LPC vetting desk",
        "events": [{ "name": "LPC", "startDate": "2026-10-05", "endDate": "2026-10-07" }],
        "grantValidUntil": "2027-09-01T00:00:00Z",
        "updatedAt": "2026-09-01T00:00:00Z"
    }))
    .unwrap()
}

#[tokio::test]
async fn a_vetter_publishes_a_profile_and_hears_the_communitys_answer() {
    let mut vetter = Party::new(2).member_of(COMMUNITY);
    vetter.named_vetter().await;
    let now = Utc::now();
    let mut draft = ProfileDraft::new(&VetterPolicy::default());
    draft.listed = true;
    draft.languages = "en, cs".into();
    let body = draft.to_body().unwrap();

    // What the community receives is signed by the vetter, with the
    // authentication key and proofPurpose (trust-tasks 0.23: `proof`
    // REQUIRED, and this is the vetter acting on their own standing, not a
    // claim to be held to later — the same purpose a personhood challenge or
    // assertion is signed with), and opens as a profile.
    let mut request = wire::vetter_profile_request(&vetter.did, COMMUNITY, &body).unwrap();
    wire::sign(&mut request, &vetter.secret).await.unwrap();
    assert_eq!(
        request.proof.as_ref().unwrap().proof_purpose,
        "authentication"
    );
    // It travels in the binding envelope; the community takes that off first.
    let sent = wire::to_message(&request).unwrap();
    assert_eq!(sent.typ, crate::capabilities::TRUST_TASK_ENVELOPE_TYPE);
    let opened: wire::Opened<vetters::profile::v0_1::Payload> = wire::open(
        &crate::didcomm::open_didcomm_envelope(&sent).unwrap(),
        &vetter.did,
        &TrustTaskVmResolver::did_key_only(),
    )
    .await
    .unwrap();
    // The generated payload has no `PartialEq`; what was sent is compared as
    // what it serialises to.
    assert_eq!(
        serde_json::to_value(&opened.payload).unwrap(),
        serde_json::to_value(&body).unwrap()
    );

    vetter
        .book
        .record_profile_sent(COMMUNITY, vetter.persona, &body, now);
    vetter
        .book
        .ask(asked(&request, vetter.persona, QueryKind::VetterProfile));
    let stored = vetters::profile::v0_1::Response::try_from(
        vetters::profile::v0_1::Response::builder()
            .listed(true)
            .updated_at(now),
    )
    .unwrap();
    let handled = vetter
        .receive(&community_answer(&request, &stored).await, COMMUNITY)
        .await;
    assert!(handled.changed, "the stored state is kept");
    assert!(matches!(
        handled.notice,
        Some(Notice::ProfilePublished { listed: true, .. })
    ));
    assert!(matches!(
        handled.answer,
        Some(CommunityAnswer::ProfileStored { listed: true, .. })
    ));
    assert!(matches!(
        vetter
            .book
            .vetter_profile(COMMUNITY, vetter.persona)
            .unwrap()
            .state,
        ProfileState::Stored { listed: true, .. }
    ));

    // Published again, and refused: the community no longer counts the grant.
    let request = wire::vetter_profile_request(&vetter.did, COMMUNITY, &body).unwrap();
    vetter
        .book
        .record_profile_sent(COMMUNITY, vetter.persona, &body, now);
    vetter
        .book
        .ask(asked(&request, vetter.persona, QueryKind::VetterProfile));
    let handled = vetter
        .receive(
            &community_refusal(&request, VETTING_VETTER_PROFILE_ERR_NOT_ELIGIBLE),
            COMMUNITY,
        )
        .await;
    assert!(matches!(
        &handled.answer,
        Some(CommunityAnswer::Refused { kind: QueryKind::VetterProfile, code, .. })
            if code == VETTING_VETTER_PROFILE_ERR_NOT_ELIGIBLE
    ));
    let notice = handled.notice.expect("a refusal is explained");
    assert!(notice.describe().contains("live vetter credential"));
    assert!(matches!(
        vetter
            .book
            .vetter_profile(COMMUNITY, vetter.persona)
            .unwrap()
            .state,
        ProfileState::Refused { .. }
    ));
}

#[tokio::test]
async fn the_directory_answers_only_what_was_asked() {
    let mut applicant = Party::new(1);
    let page = vetters::list::v0_1::Response::try_from(
        vetters::list::v0_1::Response::builder()
            .vetters(vec![listed_vetter()])
            .next_cursor(Some(
                vetters::list::v0_1::ResponseNextCursor::try_from("page-2").unwrap(),
            )),
    )
    .unwrap();
    let request = wire::vetter_list_request(&applicant.did, COMMUNITY, &unfiltered_list()).unwrap();

    // Nobody asked: the page answers nothing.
    let handled = applicant
        .receive(&community_answer(&request, &page).await, COMMUNITY)
        .await;
    assert!(handled.answer.is_none());

    applicant
        .book
        .ask(asked(&request, applicant.persona, QueryKind::VetterList));
    // Another community cannot answer our question.
    let handled = applicant
        .receive(
            &community_answer(&request, &page).await,
            "did:key:zElsewhere",
        )
        .await;
    assert!(handled.answer.is_none());

    let handled = applicant
        .receive(&community_answer(&request, &page).await, COMMUNITY)
        .await;
    let Some(CommunityAnswer::Vetters {
        query, page: got, ..
    }) = handled.answer
    else {
        panic!("the page is handed to whoever asked");
    };
    assert_eq!(query, request.id);
    assert_eq!(
        serde_json::to_value(&got).unwrap(),
        serde_json::to_value(&page).unwrap()
    );
    assert!(!handled.changed, "a directory page is never saved");

    // Refused: the community would not answer this caller.
    let request = wire::vetter_list_request(&applicant.did, COMMUNITY, &unfiltered_list()).unwrap();
    applicant
        .book
        .ask(asked(&request, applicant.persona, QueryKind::VetterList));
    let handled = applicant
        .receive(&community_refusal(&request, "permissionDenied"), COMMUNITY)
        .await;
    assert!(matches!(
        &handled.answer,
        Some(CommunityAnswer::Refused { kind: QueryKind::VetterList, code, .. })
            if code == "permissionDenied"
    ));

    // An error that answers nothing we asked is left for the join handler.
    let stray = wire::vetter_list_request(&applicant.did, COMMUNITY, &unfiltered_list()).unwrap();
    let resolver = TrustTaskVmResolver::did_key_only();
    let did_resolver = did_resolver().await;
    let issued: Option<
        Result<
            crate::issued_credential::VerifiedIssuedCredential,
            crate::issued_credential::IssuedCredentialError,
        >,
    > = None;
    let ctx = Context {
        account: &applicant.account,
        resolver: &resolver,
        did_resolver: &did_resolver,
        issued_credential: issued.as_ref(),
        community_answer: None,
        recipient: Some((applicant.persona, &applicant.did)),
        now: Utc::now(),
    };
    assert!(
        handle(
            &mut applicant.book,
            &ctx,
            &mut crate::operational::SeenDocuments::default(),
            &community_refusal(&stray, "permissionDenied"),
            COMMUNITY
        )
        .await
        .is_none()
    );

    // An answer this client cannot read says so, rather than timing out.
    let request = wire::vetter_list_request(&applicant.did, COMMUNITY, &unfiltered_list()).unwrap();
    applicant
        .book
        .ask(asked(&request, applicant.persona, QueryKind::VetterList));
    let handled = applicant
        .receive(
            &community_answer(&request, &json!({ "vetters": "not a list" })).await,
            COMMUNITY,
        )
        .await;
    assert!(matches!(
        handled.answer,
        Some(CommunityAnswer::Unreadable {
            kind: QueryKind::VetterList,
            ..
        })
    ));
    assert!(applicant.book.queries.is_empty());
}

/// `message` as a community that follows the DIDComm binding (§5) sends it:
/// typed as the envelope, with the same document as the body.
fn enveloped(message: &Message) -> Message {
    let mut enveloped = message.clone();
    enveloped.typ = crate::capabilities::TRUST_TASK_ENVELOPE_TYPE.to_string();
    enveloped
}

/// A community answers in the response document's own type today and in the
/// binding envelope once it follows §5 fully (the follow-up to VTI #1687). Both
/// must reach the same handler, or the switch silently drops every answer.
#[tokio::test]
async fn a_community_answer_is_read_in_either_carriage() {
    let mut applicant = Party::new(1);
    let page = vetters::list::v0_1::Response::try_from(
        vetters::list::v0_1::Response::builder().vetters(vec![listed_vetter()]),
    )
    .unwrap();
    for in_envelope in [false, true] {
        let request =
            wire::vetter_list_request(&applicant.did, COMMUNITY, &unfiltered_list()).unwrap();
        applicant
            .book
            .ask(asked(&request, applicant.persona, QueryKind::VetterList));
        let reply = community_answer(&request, &page).await;
        let reply = if in_envelope {
            crate::didcomm::open_didcomm_envelope(&enveloped(&reply))
                .expect("an enveloped document opens")
        } else {
            assert!(
                crate::didcomm::open_didcomm_envelope(&reply).is_none(),
                "a document-typed reply needs no opening"
            );
            reply
        };
        let handled = applicant.receive(&reply, COMMUNITY).await;
        assert!(
            matches!(&handled.answer, Some(CommunityAnswer::Vetters { query, .. }) if *query == request.id),
            "answered in the envelope: {in_envelope}"
        );

        // And a refusal, in the same carriage.
        let request =
            wire::vetter_list_request(&applicant.did, COMMUNITY, &unfiltered_list()).unwrap();
        applicant
            .book
            .ask(asked(&request, applicant.persona, QueryKind::VetterList));
        let refusal = community_refusal(&request, "permissionDenied");
        let refusal = if in_envelope {
            crate::didcomm::open_didcomm_envelope(&enveloped(&refusal)).unwrap()
        } else {
            refusal
        };
        let handled = applicant.receive(&refusal, COMMUNITY).await;
        assert!(matches!(
            &handled.answer,
            Some(CommunityAnswer::Refused { kind: QueryKind::VetterList, code, .. })
                if code == "permissionDenied"
        ));
    }
    assert!(applicant.book.queries.is_empty());
}

/// A community refusing at the DIDComm layer — a problem-report, as a VTC sends
/// for a Trust Task typed as its task URI (VTI #1687) — refuses the question it
/// threads on at once, instead of leaving it to time out.
#[tokio::test]
async fn a_problem_report_refuses_the_question_it_threads_on() {
    let mut applicant = Party::new(1);
    let request = wire::vetter_list_request(&applicant.did, COMMUNITY, &unfiltered_list()).unwrap();
    applicant
        .book
        .ask(asked(&request, applicant.persona, QueryKind::VetterList));
    let report = |thid: &str| {
        Message::build(
            wire::new_id(),
            vta_sdk::protocols::PROBLEM_REPORT_TYPE.to_string(),
            json!({
                "code": "e.p.msg.bad-request",
                "comment": "unsupported message type: … — Trust Tasks must be carried in the \
                            DIDComm binding envelope",
            }),
        )
        .from(COMMUNITY.to_string())
        .thid(thid.to_string())
        .finalize()
    };

    let handled = applicant.receive(&report(&request.id), COMMUNITY).await;
    let Some(CommunityAnswer::Refused {
        query,
        kind: QueryKind::VetterList,
        code,
        message,
        ..
    }) = handled.answer
    else {
        panic!("the question is refused");
    };
    assert_eq!(query, request.id);
    assert_eq!(code, "e.p.msg.bad-request");
    assert!(message.unwrap().contains("binding envelope"));
    assert!(applicant.book.queries.is_empty());

    // One threading on nothing of vetting's is left for the join handler.
    let resolver = TrustTaskVmResolver::did_key_only();
    let did_resolver = did_resolver().await;
    let issued: Option<
        Result<
            crate::issued_credential::VerifiedIssuedCredential,
            crate::issued_credential::IssuedCredentialError,
        >,
    > = None;
    let ctx = Context {
        account: &applicant.account,
        resolver: &resolver,
        did_resolver: &did_resolver,
        issued_credential: issued.as_ref(),
        community_answer: None,
        recipient: Some((applicant.persona, &applicant.did)),
        now: Utc::now(),
    };
    assert!(
        handle(
            &mut applicant.book,
            &ctx,
            &mut crate::operational::SeenDocuments::default(),
            &report("urn:uuid:not-ours"),
            COMMUNITY
        )
        .await
        .is_none()
    );
}

#[tokio::test]
async fn a_resend_is_answered_or_refused_in_plain_words() {
    let mut member = Party::new(5).member_of(COMMUNITY);
    let request = wire::vetter_resend_request(&member.did, COMMUNITY).unwrap();
    member
        .book
        .ask(asked(&request, member.persona, QueryKind::VetterResend));
    let resent = vetters::resend::v0_1::Response::try_from(
        vetters::resend::v0_1::Response::builder()
            .credential_id("urn:uuid:grant")
            .valid_until(Utc::now() + Duration::days(300)),
    )
    .unwrap();
    let handled = member
        .receive(&community_answer(&request, &resent).await, COMMUNITY)
        .await;
    assert!(matches!(
        handled.answer,
        Some(CommunityAnswer::Resent { .. })
    ));
    assert!(matches!(handled.notice, Some(Notice::GrantResent { .. })));

    let request = wire::vetter_resend_request(&member.did, COMMUNITY).unwrap();
    member
        .book
        .ask(asked(&request, member.persona, QueryKind::VetterResend));
    let handled = member
        .receive(
            &community_refusal(&request, VETTING_VETTER_RESEND_ERR_NOT_GRANTED),
            COMMUNITY,
        )
        .await;
    assert!(matches!(
        handled.answer,
        Some(CommunityAnswer::Refused {
            kind: QueryKind::VetterResend,
            ..
        })
    ));
    let notice = handled.notice.expect("a refusal is explained");
    assert!(notice.describe().contains("has not named you a vetter"));
}

#[tokio::test]
async fn a_manifest_answers_whoever_asked_and_brings_the_communitys_branding() {
    let mut applicant = Party::new(1);
    let request = wire::manifest_request(
        &applicant.did,
        COMMUNITY,
        super::protocol::JoinProtocol::V0_2,
    )
    .unwrap();
    applicant
        .book
        .ask(asked(&request, applicant.persona, QueryKind::Manifest));
    let branding = manifest::v0_2::CommunityBranding::try_from(
        manifest::v0_2::CommunityBranding::builder()
            .display_name(Some(
                manifest::v0_2::CommunityBrandingDisplayName::try_from("Kernel Developers")
                    .unwrap(),
            ))
            .accent_color(Some(
                manifest::v0_2::CommunityBrandingAccentColor::try_from("#336699").unwrap(),
            )),
    )
    .unwrap();
    let body = manifest_with(Some(requirements()), Some(branding));
    let handled = applicant
        .receive(&community_answer(&request, &body).await, COMMUNITY)
        .await;
    assert!(matches!(
        handled.answer,
        Some(CommunityAnswer::Manifest { .. })
    ));
    assert!(matches!(
        applicant.book.knowledge(COMMUNITY),
        Knowledge::Vetting(_)
    ));
    let branding = applicant.book.branding(COMMUNITY).unwrap();
    assert_eq!(branding.display_name.as_deref(), Some("Kernel Developers"));
    assert_eq!(branding.accent_rgb(), Some((0x33, 0x66, 0x99)));
    assert!(applicant.book.queries.is_empty());
}

/// A community role credential carrying a status list entry, signed by
/// `issuer`. Signed as JSON, as a community's own signer does.
async fn role_credential_with_status(issuer: &Secret, subject: &str) -> Value {
    let credential = role_vac(issuer, COMMUNITY, subject, VETTER_ROLE);
    let mut value = serde_json::to_value(&credential).unwrap();
    value.as_object_mut().unwrap().remove("proof");
    value["credentialStatus"] = json!({
        "id": "https://vtc.example.com/v1/status-lists/revocation#7",
        "type": "BitstringStatusListEntry",
        "statusPurpose": "revocation",
        "statusListIndex": "7",
        "statusListCredential": "https://vtc.example.com/v1/status-lists/revocation"
    });
    let proof = DataIntegrityProof::sign(
        &value,
        issuer,
        SignOptions::new().with_proof_purpose("assertionMethod"),
    )
    .await
    .unwrap();
    value["proof"] = serde_json::to_value(proof).unwrap();
    value
}

#[tokio::test]
async fn a_verified_grant_is_handed_on_for_a_revocation_check() {
    let (mut applicant, mut vetter, ticket) = ready().await;
    let credential =
        role_credential_with_status(&secret(COMMUNITY_SEED), &vetter.did.clone()).await;
    // Receiving this grant would read its status list, which fails closed
    // with no list to fetch (see `a_grant_whose_status_cannot_be_read_is_not_kept`);
    // this test is about the applicant's side, so the vetter is handed the grant.
    vetter.book.keep_vetter_grant(super::book::VetterGrant {
        community: COMMUNITY.to_string(),
        persona: vetter.persona,
        credential_id: credential["id"].as_str().map(str::to_string),
        valid_until: credential["validUntil"]
            .as_str()
            .and_then(|s| chrono::DateTime::parse_from_rfc3339(s).ok())
            .map(|d| d.with_timezone(&Utc)),
        received_at: Utc::now(),
        credential: credential.clone(),
    });

    let message = request(&mut applicant, &vetter, ticket).await;
    let reply = vetter
        .receive(&message, &applicant.did)
        .await
        .reply
        .expect("accepted");
    let handled = applicant
        .receive(&signed_reply(reply, &vetter.secret).await, &vetter.did)
        .await;
    let check = handled
        .grant_check
        .expect("a verified grant with a status entry is checked");
    assert_eq!(check.issuer, COMMUNITY);
    assert_eq!(check.vetter, vetter.did);
    assert_eq!(check.credential_status["statusListIndex"], "7");
    let app = applicant.application();
    assert!(matches!(
        app.requests[0].grant_status,
        Some(GrantStatus::Checking { .. })
    ));

    app.record_grant_status(
        &check.request_document_id,
        &check.vetter,
        GrantStatus::from_check(StatusCheck::Revoked, Utc::now()),
    )
    .unwrap();
    assert!(matches!(
        app.requests[0].grant_status,
        Some(GrantStatus::Revoked { .. })
    ));
}

#[tokio::test]
async fn a_grant_that_names_no_status_list_is_not_called_unrevoked() {
    let (mut applicant, mut vetter, ticket) = ready().await;
    let message = request(&mut applicant, &vetter, ticket).await;
    let reply = vetter
        .receive(&message, &applicant.did)
        .await
        .reply
        .unwrap();
    let handled = applicant
        .receive(&signed_reply(reply, &vetter.secret).await, &vetter.did)
        .await;
    assert!(handled.grant_check.is_none());
    assert!(matches!(
        applicant.application().requests[0].grant_status,
        Some(GrantStatus::Unknown { .. })
    ));
}

#[tokio::test]
async fn a_scanned_ticket_link_is_enough_to_ask_and_another_communitys_is_refused() {
    let (mut applicant, mut vetter, _) = ready().await;
    let link = vetter.book.tickets[0].uri(&vetter.did).unwrap();
    let ticket = applicant.application().ticket_from_uri(&link).unwrap();
    assert_eq!(ticket.vetter, vetter.did);
    let message = request(&mut applicant, &vetter, ticket.presentation).await;
    let handled = vetter.receive(&message, &applicant.did).await;
    assert!(matches!(
        handled.notice,
        Some(Notice::RequestAccepted { .. })
    ));

    let elsewhere = Ticket::issue(
        "did:key:zOtherCommunity",
        vetter.persona,
        vec![],
        1,
        DEFAULT_VALIDITY,
        Utc::now(),
    );
    assert!(matches!(
        applicant
            .application()
            .ticket_from_uri(&elsewhere.uri(&vetter.did).unwrap()),
        Err(TicketUriError::OtherCommunity(c)) if c == "did:key:zOtherCommunity"
    ));
    assert!(matches!(
        applicant.application().ticket_from_uri("K7QF-2M9X"),
        Err(TicketUriError::Unreadable(_))
    ));
}

#[tokio::test]
async fn the_next_step_follows_the_application() {
    let fresh = Application::new(COMMUNITY, PersonaId::new(), "did:key:zA", Utc::now()).unwrap();
    assert_eq!(fresh.next_step(Utc::now()), NextStep::LearnRequirements);

    let (mut applicant, mut vetter, _) = ready().await;
    assert_eq!(
        applicant.application().next_step(Utc::now()),
        NextStep::ChooseFace
    );
    // Choosing one advances the step. The claims are only read from the face
    // when the first card goes out, so without `face` being recorded in its own
    // right the step still said "choose a face" right after one was chosen —
    // the screen told you to do the thing you had just done.
    applicant.application().face = Some(ChosenFace {
        profile_id: "p1".into(),
        name: "Work".into(),
    });
    assert_eq!(
        applicant.application().next_step(Utc::now()),
        NextStep::AskVetter
    );
    let (_, session_doc) = in_session(&mut applicant, &mut vetter).await;
    assert_eq!(
        applicant.application().next_step(Utc::now()),
        NextStep::WaitForVetters
    );
    let message = signed(session_doc.clone(), &vetter.secret).await;
    applicant.receive(&message, &vetter.did).await;
    assert_eq!(
        applicant.application().next_step(Utc::now()),
        NextStep::SendCard {
            session_id: session_doc.id.clone()
        }
    );
}

/// A community's answer is acted on only when the community signed it: an
/// unsigned manifest, or one whose content was changed after signing, is not
/// adopted — whoever the transport says sent it.
#[tokio::test]
async fn an_unsigned_or_altered_community_answer_is_not_acted_on() {
    let mut applicant = Party::new(1);
    applicant
        .book
        .start_application(COMMUNITY, applicant.persona, &applicant.did, Utc::now())
        .unwrap();

    let unsigned = Message::build(
        wire::new_id(),
        JOIN_REQUEST_MANIFEST_0_2_RESPONSE_TYPE.to_string(),
        json!({
            "type": JOIN_REQUEST_MANIFEST_0_2_RESPONSE_TYPE,
            "issuer": COMMUNITY,
            "payload": manifest_body(),
        }),
    )
    .from(COMMUNITY.to_string())
    .finalize();
    let handled = applicant.receive(&unsigned, COMMUNITY).await;
    assert!(!handled.changed && handled.notice.is_none());

    let mut altered = manifest_reply(&applicant.did.clone()).await;
    altered.body["payload"]["tampered"] = json!(true);
    let handled = applicant.receive(&altered, COMMUNITY).await;
    assert!(!handled.changed && handled.notice.is_none());

    // Signed by the community, but arriving as another sender's answer.
    let handled = applicant
        .receive(
            &manifest_reply(&applicant.did.clone()).await,
            "did:key:zElsewhere",
        )
        .await;
    assert!(!handled.changed && handled.notice.is_none());

    // The genuine answer is adopted.
    let handled = applicant
        .receive(&manifest_reply(&applicant.did.clone()).await, COMMUNITY)
        .await;
    assert!(matches!(
        handled.notice,
        Some(Notice::RequirementsUpdated { .. })
    ));
}

/// A community answer checked off the loop is taken from that check — not
/// resolved again — and one whose check failed or never ran is refused.
#[tokio::test]
async fn a_community_answer_is_taken_from_its_off_loop_check() {
    let mut applicant = Party::new(1);
    applicant
        .book
        .start_application(COMMUNITY, applicant.persona, &applicant.did, Utc::now())
        .unwrap();
    let reply = manifest_reply(&applicant.did.clone()).await;

    let refused = Err(crate::operational::OperationalError::NotChecked);
    let handled = applicant.receive_checked(&reply, COMMUNITY, &refused).await;
    assert!(!handled.changed && handled.notice.is_none());

    let checked = crate::operational::verify_operational(
        &reply.body,
        COMMUNITY,
        &[applicant.did.as_str()],
        &reply.typ,
        &did_resolver().await,
        &applicant.seen,
        Utc::now(),
    )
    .await;
    let handled = applicant.receive_checked(&reply, COMMUNITY, &checked).await;
    assert!(matches!(
        handled.notice,
        Some(Notice::RequirementsUpdated { .. })
    ));
}

/// A vetter role credential whose proof does not verify is not kept — here, a
/// genuine grant with its role claim changed after the community signed it.
#[tokio::test]
async fn a_tampered_vetter_grant_is_not_kept() {
    let mut member = Party::new(2).member_of(COMMUNITY);
    let mut credential = role_credential(
        &secret(COMMUNITY_SEED),
        COMMUNITY,
        &member.did.clone(),
        VETTER_ROLE,
    )
    .await;
    credential["validUntil"] = json!("2999-01-01T00:00:00Z");
    let handled = member
        .receive(
            &delivery(&credential, &secret(COMMUNITY_SEED)).await,
            COMMUNITY,
        )
        .await;
    assert!(handled.notice.is_none() && member.book.vetter_grants.is_empty());
}

/// A vetter grant naming a status list that cannot be read is not kept:
/// revocation fails closed.
#[tokio::test]
async fn a_grant_whose_status_cannot_be_read_is_not_kept() {
    let mut vetter = Party::new(2).member_of(COMMUNITY);
    let credential =
        role_credential_with_status(&secret(COMMUNITY_SEED), &vetter.did.clone()).await;
    let handled = vetter
        .receive(
            &delivery(&credential, &secret(COMMUNITY_SEED)).await,
            COMMUNITY,
        )
        .await;
    assert!(handled.notice.is_none() && vetter.book.vetter_grants.is_empty());
}

/// A community answer is operational: signed with the community's
/// authentication key, not its credential key, and taken once.
#[tokio::test]
async fn a_community_answer_is_taken_once_and_only_from_the_operational_key() {
    let mut applicant = Party::new(1);
    applicant
        .book
        .start_application(COMMUNITY, applicant.persona, &applicant.did, Utc::now())
        .unwrap();
    // `did:key` lists its one key under both relationships, so an
    // assertionMethod proof is refused for its purpose.
    let asserted = crate::proof_check::test_support::sign(
        json!({
            "id": wire::new_id(),
            "type": JOIN_REQUEST_MANIFEST_0_2_RESPONSE_TYPE,
            "issuer": COMMUNITY,
            "recipient": applicant.did,
            "issuedAt": Utc::now().to_rfc3339(),
            "payload": manifest_body(),
        }),
        &[&secret(COMMUNITY_SEED)],
    )
    .await;
    let message = Message::build(
        wire::new_id(),
        JOIN_REQUEST_MANIFEST_0_2_RESPONSE_TYPE.to_string(),
        asserted,
    )
    .from(COMMUNITY.to_string())
    .finalize();
    let handled = applicant.receive(&message, COMMUNITY).await;
    assert!(handled.notice.is_none());

    let reply = manifest_reply(&applicant.did.clone()).await;
    let handled = applicant.receive(&reply, COMMUNITY).await;
    assert!(matches!(
        handled.notice,
        Some(Notice::RequirementsUpdated { .. })
    ));
    let mut again = reply.clone();
    again.id = wire::new_id();
    let handled = applicant.receive(&again, COMMUNITY).await;
    assert!(
        !handled.changed && handled.notice.is_none(),
        "a replayed answer is refused"
    );

    // Addressed to somebody else.
    let other = manifest_reply("did:key:zSomeoneElse").await;
    let handled = applicant.receive(&other, COMMUNITY).await;
    assert!(!handled.changed && handled.notice.is_none());
}

/// A signed manifest nobody asked for — no query, no application, no
/// membership — is not learned, and nothing is written to the replay set.
#[tokio::test]
async fn an_unsolicited_manifest_writes_nothing() {
    let mut stranger = Party::new(7);
    let reply = manifest_reply(&stranger.did.clone()).await;
    let handled = stranger.receive(&reply, COMMUNITY).await;
    assert!(!handled.changed && handled.notice.is_none() && handled.answer.is_none());
    assert!(stranger.seen.is_empty(), "the replay set is untouched");
    assert!(matches!(
        stranger.book.knowledge(COMMUNITY),
        Knowledge::Unknown
    ));
}

impl Party {
    /// The account knows this party's persona, as a real account does — what
    /// a reply needs to sign as it.
    fn with_persona_record(mut self) -> Self {
        self.account.personas.insert(
            self.persona,
            crate::config::account::PersonaRecord {
                extra: serde_json::Map::new(),
                persona_id: self.persona,
                did: self.did.clone(),
                did_document: None,
                key_refs: Vec::new(),
                mediator_did: None,
                origin_context_id: String::new(),
                created_at: Utc::now(),
                label: None,
            },
        );
        self
    }
}

/// A 0.3 manifest answer is read into the book with its version and what each
/// criterion's admission is; a vetting criterion is still known as vetting.
#[tokio::test]
async fn a_v0_3_manifest_is_learned_with_its_version_and_admission() {
    use super::protocol::{Admission, JoinProtocol};
    let mut applicant = Party::new(1);
    let request = wire::manifest_request(&applicant.did, COMMUNITY, JoinProtocol::V0_3).unwrap();
    applicant
        .book
        .ask(asked(&request, applicant.persona, QueryKind::Manifest));
    let body = json!({
        "communityDid": COMMUNITY,
        "criteria": [
            { "id": "invited", "admission": "automatic", "invitationRequired": true,
              "requirementsDigest": DIGEST },
            { "id": "vetted", "admission": "review", "requirementsDigest": DIGEST,
              "vetting": serde_json::to_value(requirements()).unwrap() },
        ],
    });
    let handled = applicant
        .receive(&community_answer(&request, &body).await, COMMUNITY)
        .await;
    assert!(
        matches!(handled.answer, Some(CommunityAnswer::Manifest { .. })),
        "{:?}",
        handled.answer
    );
    assert_eq!(applicant.book.protocol_for(COMMUNITY), JoinProtocol::V0_3);
    let routes = applicant.book.routes(COMMUNITY);
    assert_eq!(routes.len(), 2);
    assert_eq!(routes[0].admission, Some(Admission::Automatic));
    assert_eq!(routes[0].invitation_required, Some(true));
    assert!(routes[1].vetting && routes[1].admission == Some(Admission::Review));
    assert!(matches!(
        applicant.book.knowledge(COMMUNITY),
        Knowledge::Vetting(_)
    ));
}

/// A community that does not serve 0.3 — answering `unsupportedVersion`, as a
/// 0.2 VTC does — is asked again in 0.2, and the person waiting keeps waiting
/// instead of hearing a refusal. A refusal of 0.2 too is reported as one.
#[tokio::test]
async fn a_manifest_refused_as_an_unsupported_version_is_asked_again_in_0_2() {
    use super::protocol::JoinProtocol;
    let mut applicant = Party::new(1).with_persona_record();
    let request = wire::manifest_request(&applicant.did, COMMUNITY, JoinProtocol::V0_3).unwrap();
    applicant
        .book
        .ask(asked(&request, applicant.persona, QueryKind::Manifest));

    let handled = applicant
        .receive(
            &community_refusal(&request, "unsupportedVersion"),
            COMMUNITY,
        )
        .await;
    assert!(
        handled.answer.is_none(),
        "not an answer: {:?}",
        handled.answer
    );
    let reply = handled.reply.expect("asked again");
    assert_eq!(
        reply.document.type_uri.to_string(),
        JoinProtocol::V0_2.manifest_type()
    );
    assert_eq!(reply.persona, applicant.persona);
    assert_eq!(applicant.book.protocol_for(COMMUNITY), JoinProtocol::V0_2);
    assert!(
        applicant
            .book
            .waiting_on(COMMUNITY, QueryKind::Manifest)
            .is_some_and(|q| q.document_id == reply.document.id),
        "the new question is the one waited on"
    );

    let handled = applicant
        .receive(
            &community_refusal(&reply.document, "unsupportedVersion"),
            COMMUNITY,
        )
        .await;
    assert!(handled.reply.is_none(), "nothing older to ask in");
    assert!(matches!(
        handled.answer,
        Some(CommunityAnswer::Refused {
            kind: QueryKind::Manifest,
            ..
        })
    ));
}