vta-sdk 0.63.0

SDK for Verifiable Trust Agents operating in Verifiable Trust Communities
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
//! The Vetting Statement: what a vetter signs after checking an applicant.
//!
//! A DTG **Verifiable Statement Credential** (`StatementCredential`) under the
//! registry predicate [`VETTED_PREDICATE`]
//! (`https://registry.trustoverip.org/dtg/vsc/vetted/1`), whose
//! `credentialSubject.object.value` is a [`VettedObjectValue`]
//! (vetting/session/0.1, "The statement"). It is not an endorsement: the vetter
//! records a check it carried out, and the predicate — not a type string —
//! carries that meaning.
//!
//! [`sign_statement`] issues a vetter's statement. The registry's `vetted/1`
//! also admits the community itself as issuer, recording its own identity
//! check under its own DID; [`verify_statement`] reads either. The two differ
//! in the three vetter-only members (`identityCommitment`,
//! `cardDigestMultibase`, `declaredRelationship`): a vetter's statement carries
//! all three and the community's own carries none. Everything that treats a
//! statement as a vetter's — [`sign_statement`],
//! [`VerifiedVettingStatement::check_against_card`],
//! [`VerifiedVettingStatement::check_against_session`] and the community's
//! admission counting, through `VettedObjectValue::vetter_members` — requires
//! all three.
//!
//! A vetter's statement is issued from the **vetter's member DID** (accountable within the community),
//! declaring `issuerScope` `directed` or `public` — the profile's minimum is
//! `directed` — to the applicant's join DID, with a bounded `validUntil`, and
//! citing the `vetting/session` document by both `taskContext` (its `id`) and
//! `taskDigestMultibase` (its task digest), which the profile REQUIRES. Building
//! and parsing go through `dtg-credentials`, the workspace's DTG SDK, so the
//! v1 context, the `type` rule and the profile are checked by the same code
//! that issues them.

use affinidi_secrets_resolver::secrets::Secret;
use chrono::{DateTime, Utc};
use dtg_credentials::{DTGCredential, VETTED_V1};
use serde_json::Value;

pub use dtg_credentials::IssuerScope;

use super::card::{CLOCK_SKEW, VerifiedVettingCard};
use super::{VettingError, did_of, digest, verify_attached_proof};
#[cfg(doc)]
use crate::protocols::vetting::VETTED_PREDICATE;
use crate::protocols::vetting::{CheckShape, VettedObjectValue};
use crate::trust_task_proof::TrustTaskVmResolver;

const WHAT: &str = "vetting statement";

/// Everything needed to issue a statement.
#[derive(Debug, Clone)]
pub struct StatementDraft {
    /// `urn:uuid:…` — what a revocation notice names.
    pub id: String,
    /// The vetter's member DID.
    pub issuer: String,
    /// The correlation scope the vetter declares for `issuer`: `directed`
    /// (the community and its applicants recognise the member DID) or
    /// `public`. `pairwise` is refused — the `vetted/1` profile's minimum is
    /// `directed`.
    pub issuer_scope: IssuerScope,
    /// The applicant's join DID (the verified card's publisher).
    pub subject: String,
    /// The attestation: `credentialSubject.object.value`.
    pub value: VettedObjectValue,
    /// Normally now.
    pub valid_from: DateTime<Utc>,
    /// `validFrom` + the community's `maxStatementAge`.
    pub valid_until: DateTime<Utc>,
    /// The `vetting/session` document that opened the session, exactly as the
    /// vetter sent it. Its `id` becomes `taskContext` and its task digest
    /// `taskDigestMultibase`, so the two cannot disagree.
    pub session: Value,
}

/// Build and sign a statement. `signer` must be a key of `draft.issuer`.
///
/// # Errors
///
/// [`VettingError::WrongSigner`], [`VettingError::Malformed`] (a value that
/// breaks its shared definition, a `pairwise` scope, or a session document
/// without an `id`), [`VettingError::Expired`] (empty window) or
/// [`VettingError::Sign`].
pub async fn sign_statement(draft: StatementDraft, signer: &Secret) -> Result<Value, VettingError> {
    let malformed = |detail: String| VettingError::Malformed { what: WHAT, detail };
    if did_of(&signer.id) != draft.issuer {
        return Err(VettingError::WrongSigner {
            what: WHAT,
            role: "issuer",
        });
    }
    draft
        .value
        .check_shape()
        .map_err(|e| malformed(e.to_string()))?;
    // A vetter's statement is always made over a card and declares the
    // vetter's relationship. Only a statement the community issues for itself
    // carries none of the vetter-only members, and it does not issue through
    // here.
    if draft.value.vetter_members().is_none() {
        return Err(malformed(
            "a vetter's statement carries identityCommitment, cardDigestMultibase and \
             declaredRelationship"
                .into(),
        ));
    }
    if draft.valid_until <= draft.valid_from {
        return Err(VettingError::Expired(WHAT));
    }
    let value =
        serde_json::to_value(&draft.value).map_err(|e| VettingError::Sign(e.to_string()))?;
    let mut credential = DTGCredential::new_vetted_vsc(
        draft.issuer,
        draft.issuer_scope,
        draft.subject,
        value,
        &draft.session,
        draft.valid_from,
        Some(draft.valid_until),
    )
    .map_err(|e| malformed(e.to_string()))?
    .with_id(draft.id);
    credential
        .sign(signer, None)
        .await
        .map_err(|e| VettingError::Sign(e.to_string()))?;
    serde_json::to_value(&credential).map_err(|e| VettingError::Sign(e.to_string()))
}

/// A statement whose proof, type, profile, window and shape all check.
///
/// What this does **not** establish: that the issuer is an eligible vetter of
/// the community, or that the statement has not been withdrawn. Those are facts
/// only the community holds.
#[derive(Debug, Clone)]
pub struct VerifiedVettingStatement {
    id: String,
    issuer: String,
    issuer_scope: IssuerScope,
    subject: String,
    value: VettedObjectValue,
    valid_from: DateTime<Utc>,
    valid_until: DateTime<Utc>,
    task_context: String,
    task_digest_multibase: String,
    has_status: bool,
    digest_multibase: String,
}

impl VerifiedVettingStatement {
    /// The statement `id`.
    #[must_use]
    pub fn id(&self) -> &str {
        &self.id
    }
    /// The vetter's DID (proven: it signed).
    #[must_use]
    pub fn issuer(&self) -> &str {
        &self.issuer
    }
    /// The `issuerScope` the vetter declared: `directed` or `public`.
    #[must_use]
    pub fn issuer_scope(&self) -> IssuerScope {
        self.issuer_scope
    }
    /// The applicant's join DID.
    #[must_use]
    pub fn subject(&self) -> &str {
        &self.subject
    }
    /// The attestation: `credentialSubject.object.value`.
    #[must_use]
    pub fn value(&self) -> &VettedObjectValue {
        &self.value
    }
    /// Start of validity.
    #[must_use]
    pub fn valid_from(&self) -> DateTime<Utc> {
        self.valid_from
    }
    /// End of validity.
    #[must_use]
    pub fn valid_until(&self) -> DateTime<Utc> {
        self.valid_until
    }
    /// The `vetting/session` document id.
    #[must_use]
    pub fn task_context(&self) -> &str {
        &self.task_context
    }
    /// The `vetting/session` document's task digest.
    #[must_use]
    pub fn task_digest_multibase(&self) -> &str {
        &self.task_digest_multibase
    }
    /// Whether the statement names a `credentialStatus` entry to check.
    #[must_use]
    pub fn has_status(&self) -> bool {
        self.has_status
    }
    /// `digestMultibase` of the statement — what a revocation notice names.
    #[must_use]
    pub fn digest_multibase(&self) -> &str {
        &self.digest_multibase
    }

    /// Check this statement was issued over `card`: same subject, community,
    /// commitment and card digest. The applicant's client runs this before
    /// filing a statement, so a vetter that attested to a different card is
    /// caught immediately rather than at the community.
    ///
    /// # Errors
    ///
    /// [`VettingError::Binding`] naming the member that differs.
    pub fn check_against_card(&self, card: &VerifiedVettingCard) -> Result<(), VettingError> {
        let c = card.card();
        if self.subject != c.publisher.as_str() {
            return Err(VettingError::Binding("subject"));
        }
        if self.value.community != c.community.as_str() {
            return Err(VettingError::Binding("community"));
        }
        let Some(vetter) = self.value.vetter_members() else {
            return Err(VettingError::Binding("identityCommitment"));
        };
        if vetter.identity_commitment != c.identity_commitment.as_str() {
            return Err(VettingError::Binding("identityCommitment"));
        }
        if vetter.card_digest_multibase != card.digest_multibase() {
            return Err(VettingError::Binding("cardDigestMultibase"));
        }
        Ok(())
    }

    /// Check this statement cites `session` — the `vetting/session` document
    /// the vetter sent — by both `taskContext` and `taskDigestMultibase`, and,
    /// being a vetter's statement, carries the vetter-only members
    /// (`identityCommitment`, `cardDigestMultibase`, `declaredRelationship`).
    /// A vetting session is always run over a card, so a statement without
    /// them did not come out of it.
    ///
    /// # Errors
    ///
    /// [`VettingError::Binding`] naming `identityCommitment` (no vetter-only
    /// members), `taskContext` or `taskDigestMultibase`.
    pub fn check_against_session(&self, session: &Value) -> Result<(), VettingError> {
        if self.value.vetter_members().is_none() {
            return Err(VettingError::Binding("identityCommitment"));
        }
        if session.get("id").and_then(Value::as_str) != Some(self.task_context.as_str()) {
            return Err(VettingError::Binding("taskContext"));
        }
        let expected = dtg_credentials::task_digest_multibase_json(session)
            .map_err(|e| VettingError::Digest(e.to_string()))?;
        let same = dtg_credentials::digests_match(&self.task_digest_multibase, &expected)
            .map_err(|e| VettingError::Digest(e.to_string()))?;
        if !same {
            return Err(VettingError::Binding("taskDigestMultibase"));
        }
        Ok(())
    }
}

/// Verify a statement as received — by the applicant on delivery, or by the
/// community inside a join presentation.
///
/// The credential must parse as a DTG credential under the v1 context — which
/// holds it to the `vetted/1` profile: `taskContext` and `taskDigestMultibase`
/// present, `issuerScope` at least `directed` — carry the predicate
/// [`VETTED_PREDICATE`], and have an `object.value` that is a
/// [`VettedObjectValue`].
///
/// # Errors
///
/// The first failed check: [`VettingError::Malformed`], [`VettingError::Expired`],
/// [`VettingError::Proof`] or [`VettingError::WrongSigner`].
pub async fn verify_statement(
    value: &Value,
    now: DateTime<Utc>,
    resolver: &TrustTaskVmResolver,
) -> Result<VerifiedVettingStatement, VettingError> {
    let malformed = |detail: String| VettingError::Malformed { what: WHAT, detail };
    // Shape without the proof, which may be a set (VTI-57) and is verified
    // over the statement as received.
    let credential = super::dtg_shape(value).map_err(|e| malformed(e.to_string()))?;
    let statement = credential
        .statement()
        .ok_or_else(|| malformed("not a StatementCredential".into()))?;
    if statement.predicate != VETTED_V1 {
        return Err(malformed(format!(
            "predicate `{}` is not {VETTED_V1}",
            statement.predicate
        )));
    }
    let object = statement
        .object
        .value()
        .ok_or_else(|| malformed("no object.value".into()))?;
    let vetted: VettedObjectValue = serde_json::from_value(object.clone())
        .map_err(|e| malformed(format!("object.value: {e}")))?;
    vetted
        .check_shape()
        .map_err(|e| malformed(format!("object.value: {e}")))?;
    let id = credential
        .id()
        .ok_or_else(|| malformed("no id — a statement must be revocable by name".into()))?
        .to_string();
    // Both are guaranteed by the profile check the parse ran; read defensively.
    let task_context = credential
        .task_context()
        .ok_or_else(|| malformed("no taskContext naming the session".into()))?
        .to_string();
    let task_digest_multibase = credential
        .task_digest_multibase()
        .ok_or_else(|| malformed("no taskDigestMultibase binding the session".into()))?
        .to_string();
    let valid_until = credential
        .valid_until()
        .ok_or_else(|| malformed("no validUntil — statements are bounded evidence".into()))?;
    if credential.valid_from() > now + CLOCK_SKEW || now > valid_until {
        return Err(VettingError::Expired(WHAT));
    }
    let issuer = credential.issuer().to_string();

    let signer = verify_attached_proof(WHAT, value, "assertionMethod", resolver).await?;
    if signer != issuer {
        return Err(VettingError::WrongSigner {
            what: WHAT,
            role: "issuer",
        });
    }

    Ok(VerifiedVettingStatement {
        id,
        issuer,
        issuer_scope: credential.issuer_scope(),
        subject: statement.id.clone(),
        value: vetted,
        valid_from: credential.valid_from(),
        valid_until,
        task_context,
        task_digest_multibase,
        has_status: credential.credential().credential_status.is_some(),
        digest_multibase: digest(value)?,
    })
}

#[cfg(test)]
pub(crate) mod tests {
    use super::*;
    use crate::protocols::vetting::{VETTED_PREDICATE, VettingMethod, VettingRelationship};
    use crate::vetting::card::{
        CardExpectations, sign_card,
        tests::{CHALLENGE, COMMUNITY, draft},
        verify_card,
    };
    use crate::vetting::test_support::{did, secret};
    use chrono::Duration;
    use serde_json::json;

    pub(crate) fn vetted_value(commitment: &str, card_digest: &str) -> VettedObjectValue {
        VettedObjectValue {
            community: COMMUNITY.into(),
            method: VettingMethod::Video,
            document_classes: vec!["passport".try_into().unwrap()],
            claims_verified: vec!["name.legal".try_into().unwrap()],
            liveness_confirmed: true,
            identity_commitment: Some(commitment.into()),
            card_digest_multibase: Some(card_digest.into()),
            declared_relationship: Some(VettingRelationship::CommunityColleague),
            attestation_text_digest: None,
        }
    }

    /// A `vetting/session` document, as the vetter sent it.
    pub(crate) fn session_document(vetter: &str, applicant: &str) -> Value {
        json!({
            "id": "urn:uuid:session-1",
            "type": "https://trusttasks.org/spec/vetting/session/0.1",
            "threadId": "urn:uuid:session-1",
            "parentThreadId": "urn:uuid:request-1",
            "issuer": vetter,
            "recipient": applicant,
            "issuedAt": "2026-09-17T15:00:00Z",
            "payload": { "method": "video" }
        })
    }

    async fn verified_card(applicant: &Secret, vetter: &Secret) -> VerifiedVettingCard {
        let now = Utc::now();
        let signed = sign_card(draft(applicant, vetter, now), applicant)
            .await
            .unwrap();
        let required = vec!["name.legal".to_string()];
        let (a, v) = (did(applicant), did(vetter));
        verify_card(
            &signed,
            &CardExpectations {
                audience: &v,
                publisher: &a,
                community: COMMUNITY,
                challenge: CHALLENGE,
                domain: COMMUNITY,
                required_claims: &required,
                now,
            },
            &TrustTaskVmResolver::did_key_only(),
        )
        .await
        .unwrap()
    }

    pub(crate) fn statement_draft(
        vetter: &Secret,
        subject: &str,
        value: VettedObjectValue,
    ) -> StatementDraft {
        let now = Utc::now();
        StatementDraft {
            id: "urn:uuid:statement-1".into(),
            issuer: did(vetter),
            issuer_scope: IssuerScope::Directed,
            subject: subject.into(),
            value,
            valid_from: now,
            valid_until: now + Duration::days(120),
            session: session_document(&did(vetter), subject),
        }
    }

    #[tokio::test]
    async fn a_statement_verifies_and_binds_to_its_card_and_session() {
        let (applicant, vetter) = (secret(1), secret(2));
        let card = verified_card(&applicant, &vetter).await;
        let e = vetted_value(&card.card().identity_commitment, card.digest_multibase());
        let draft = statement_draft(&vetter, &did(&applicant), e);
        let session = draft.session.clone();
        let signed = sign_statement(draft, &vetter).await.unwrap();
        assert_eq!(
            signed["@context"],
            json!([
                dtg_credentials::W3C_VC_V2_CONTEXT,
                dtg_credentials::DTG_CONTEXT_V1
            ])
        );
        assert_eq!(
            signed["type"],
            json!([
                "VerifiableCredential",
                "DTGCredential",
                "StatementCredential"
            ])
        );
        assert_eq!(signed["issuerScope"], "directed");
        assert_eq!(signed["taskContext"], "urn:uuid:session-1");
        assert!(signed["taskDigestMultibase"].is_string());
        assert_eq!(signed["credentialSubject"]["predicate"], VETTED_PREDICATE);
        assert!(
            signed["credentialSubject"]["object"]["value"]
                .get("type")
                .is_none()
        );

        let verified = verify_statement(&signed, Utc::now(), &TrustTaskVmResolver::did_key_only())
            .await
            .unwrap();
        assert_eq!(verified.issuer(), did(&vetter));
        assert_eq!(verified.issuer_scope(), IssuerScope::Directed);
        assert_eq!(verified.value().method, VettingMethod::Video);
        verified.check_against_card(&card).unwrap();
        verified.check_against_session(&session).unwrap();

        let mut other = session;
        other["issuedAt"] = json!("2026-09-17T15:01:00Z");
        assert!(matches!(
            verified.check_against_session(&other),
            Err(VettingError::Binding("taskDigestMultibase"))
        ));
    }

    #[tokio::test]
    async fn an_altered_value_breaks_the_proof() {
        let (applicant, vetter) = (secret(1), secret(2));
        let e = vetted_value("zCommitment", "zCard");
        let mut signed = sign_statement(statement_draft(&vetter, &did(&applicant), e), &vetter)
            .await
            .unwrap();
        signed["credentialSubject"]["object"]["value"]["method"] = json!("inPerson");
        let err = verify_statement(&signed, Utc::now(), &TrustTaskVmResolver::did_key_only())
            .await
            .unwrap_err();
        assert!(matches!(err, VettingError::Proof { .. }), "{err:?}");
    }

    #[tokio::test]
    async fn a_statement_over_a_different_card_is_caught() {
        let (applicant, vetter) = (secret(1), secret(2));
        let card = verified_card(&applicant, &vetter).await;
        let e = vetted_value("zDifferentCommitment", card.digest_multibase());
        let signed = sign_statement(statement_draft(&vetter, &did(&applicant), e), &vetter)
            .await
            .unwrap();
        let verified = verify_statement(&signed, Utc::now(), &TrustTaskVmResolver::did_key_only())
            .await
            .unwrap();
        assert!(matches!(
            verified.check_against_card(&card),
            Err(VettingError::Binding("identityCommitment"))
        ));
    }

    #[tokio::test]
    async fn only_the_named_issuer_may_sign() {
        let (applicant, vetter, other) = (secret(1), secret(2), secret(3));
        let e = vetted_value("zC", "zD");
        let err = sign_statement(statement_draft(&vetter, &did(&applicant), e), &other)
            .await
            .unwrap_err();
        assert!(matches!(err, VettingError::WrongSigner { .. }));
    }

    #[tokio::test]
    async fn an_expired_statement_is_refused() {
        let (applicant, vetter) = (secret(1), secret(2));
        let e = vetted_value("zC", "zD");
        let signed = sign_statement(statement_draft(&vetter, &did(&applicant), e), &vetter)
            .await
            .unwrap();
        let later = Utc::now() + Duration::days(200);
        let err = verify_statement(&signed, later, &TrustTaskVmResolver::did_key_only())
            .await
            .unwrap_err();
        assert!(matches!(err, VettingError::Expired(_)));
    }

    /// vetting/session/0.1: a `pairwise` declaration cannot describe a vetter
    /// truthfully, so it is refused at issue.
    #[tokio::test]
    async fn a_pairwise_vetter_cannot_issue() {
        let (applicant, vetter) = (secret(1), secret(2));
        let mut draft = statement_draft(&vetter, &did(&applicant), vetted_value("zC", "zD"));
        draft.issuer_scope = IssuerScope::Pairwise;
        assert!(matches!(
            sign_statement(draft, &vetter).await.unwrap_err(),
            VettingError::Malformed { .. }
        ));
    }

    #[tokio::test]
    async fn a_statement_under_another_predicate_is_not_a_vetting_statement() {
        let (applicant, vetter) = (secret(1), secret(2));
        let now = Utc::now();
        let mut vsc = DTGCredential::new_endorses_vsc(
            did(&vetter),
            IssuerScope::Directed,
            did(&applicant),
            serde_json::to_value(vetted_value("zC", "zD")).unwrap(),
            now,
            Some(now + Duration::days(30)),
        )
        .unwrap()
        .with_id("urn:uuid:not-a-vetting".to_string());
        vsc.sign(&vetter, None).await.unwrap();
        let signed = serde_json::to_value(&vsc).unwrap();
        assert!(matches!(
            verify_statement(&signed, now, &TrustTaskVmResolver::did_key_only())
                .await
                .unwrap_err(),
            VettingError::Malformed { .. }
        ));
    }

    /// A community recording its own identity check: none of the vetter-only
    /// members.
    async fn community_desk_check(community: &Secret, subject: &str) -> Value {
        let now = Utc::now();
        let mut value = vetted_value("zC", "zD");
        value.community = did(community);
        value.identity_commitment = None;
        value.card_digest_multibase = None;
        value.declared_relationship = None;
        let request = json!({
            "id": "urn:uuid:issue-request-1",
            "type": "https://trusttasks.org/spec/vtc/endorsements/issue/0.1",
            "issuer": "did:key:z6MkAdmin",
            "recipient": did(community),
            "issuedAt": "2026-10-01T09:30:00Z",
            "payload": { "subjectDid": subject }
        });
        let mut vsc = DTGCredential::new_vetted_vsc(
            did(community),
            IssuerScope::Public,
            subject.into(),
            serde_json::to_value(&value).unwrap(),
            &request,
            now,
            Some(now + Duration::days(365)),
        )
        .unwrap()
        .with_id("urn:uuid:desk-check-1".to_string());
        vsc.sign(community, None).await.unwrap();
        serde_json::to_value(&vsc).unwrap()
    }

    /// Registry `vetted/1`: the community may issue for itself, and its
    /// statement carries none of `identityCommitment`, `cardDigestMultibase`
    /// and `declaredRelationship`. It parses and verifies — but it is not a
    /// vetter's statement, so it has no vetter members and no session check
    /// accepts it.
    #[tokio::test]
    async fn a_community_statement_without_vetter_members_verifies_but_binds_no_session() {
        let (community, applicant) = (secret(5), secret(1));
        let signed = community_desk_check(&community, &did(&applicant)).await;
        let value = &signed["credentialSubject"]["object"]["value"];
        for member in [
            "identityCommitment",
            "cardDigestMultibase",
            "declaredRelationship",
        ] {
            assert!(value.get(member).is_none(), "{member}");
        }

        let verified = verify_statement(&signed, Utc::now(), &TrustTaskVmResolver::did_key_only())
            .await
            .unwrap();
        assert_eq!(verified.issuer(), did(&community));
        assert_eq!(verified.issuer_scope(), IssuerScope::Public);
        assert!(verified.value().has_no_vetter_members());
        assert_eq!(verified.value().vetter_members(), None);
        assert!(matches!(
            verified.check_against_session(&session_document(&did(&community), &did(&applicant))),
            Err(VettingError::Binding("identityCommitment"))
        ));
    }

    /// VTI-57: a two-key community signs its statement once per key, so its
    /// `proof` is a set. The shape parse used to refuse the array as malformed.
    #[tokio::test]
    async fn vti_57_a_statement_carrying_a_proof_set_verifies() {
        let (community, applicant) = (secret(6), secret(1));
        let mut signed = community_desk_check(&community, &did(&applicant)).await;
        let first = signed["proof"].clone();
        let mut proofless = signed.clone();
        proofless.as_object_mut().unwrap().remove("proof");
        let second = affinidi_data_integrity::DataIntegrityProof::sign(
            &proofless,
            &community,
            affinidi_data_integrity::SignOptions::new().with_proof_purpose("assertionMethod"),
        )
        .await
        .unwrap();
        signed["proof"] = json!([first, serde_json::to_value(second).unwrap()]);

        let verified = verify_statement(&signed, Utc::now(), &TrustTaskVmResolver::did_key_only())
            .await
            .expect("a proof-set statement verifies");
        assert_eq!(verified.issuer(), did(&community));
    }

    /// A vetter's statement is always made over a card: one without the
    /// vetter-only members is refused at issue, and fails the session check.
    #[tokio::test]
    async fn a_vetter_statement_without_the_vetter_members_is_refused() {
        let (applicant, vetter) = (secret(1), secret(2));
        let without = || {
            let mut value = vetted_value("zC", "zD");
            value.identity_commitment = None;
            value.card_digest_multibase = None;
            value.declared_relationship = None;
            value
        };
        assert!(matches!(
            sign_statement(
                statement_draft(&vetter, &did(&applicant), without()),
                &vetter
            )
            .await
            .unwrap_err(),
            VettingError::Malformed { .. }
        ));

        // Signed by hand, bypassing `sign_statement`: the session check still
        // refuses it, even though the citation itself is right.
        let now = Utc::now();
        let session = session_document(&did(&vetter), &did(&applicant));
        let value = without();
        let mut vsc = DTGCredential::new_vetted_vsc(
            did(&vetter),
            IssuerScope::Directed,
            did(&applicant),
            serde_json::to_value(&value).unwrap(),
            &session,
            now,
            Some(now + Duration::days(30)),
        )
        .unwrap()
        .with_id("urn:uuid:no-card".to_string());
        vsc.sign(&vetter, None).await.unwrap();
        let signed = serde_json::to_value(&vsc).unwrap();
        let verified = verify_statement(&signed, now, &TrustTaskVmResolver::did_key_only())
            .await
            .unwrap();
        assert!(matches!(
            verified.check_against_session(&session),
            Err(VettingError::Binding("identityCommitment"))
        ));
    }

    /// The retired shape: an `EndorsementCredential` under the old context.
    #[tokio::test]
    async fn a_pre_v1_statement_is_refused() {
        let legacy = json!({
            "@context": ["https://www.w3.org/ns/credentials/v2"],
            "id": "urn:uuid:legacy",
            "type": ["VerifiableCredential", "DTGCredential", "EndorsementCredential"],
            "issuer": "did:key:z6MkVetter",
            "validFrom": "2026-09-01T00:00:00Z",
            "validUntil": "2027-01-01T00:00:00Z",
            "taskContext": "urn:uuid:session-1",
            "credentialSubject": { "id": "did:key:z6MkApplicant", "endorsement": {} }
        });
        assert!(matches!(
            verify_statement(&legacy, Utc::now(), &TrustTaskVmResolver::did_key_only())
                .await
                .unwrap_err(),
            VettingError::Malformed { .. }
        ));
    }
}