trust-tasks-proof 0.31.13

Pluggable ProofVerifier implementations for the Trust Tasks framework. Backends are gated by Cargo features; ships with an Affinidi Data Integrity backend (EdDSA suites) by default.
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
//! A proof verifies only when the issuer's DID document lists its
//! `verificationMethod` under the relationship its `proofPurpose` names
//! (W3C Data Integrity; Controlled Identifiers v1.0 §3.3), and the method
//! belongs to the issuer.
//!
//! Documents are seeded straight into the resolver's cache, so each test
//! states the exact DID document it is about. `did:key` and `did:peer` are
//! resolved by the cache's own local resolvers.

#![cfg(feature = "affinidi")]

use std::sync::Arc;

use affinidi_data_integrity::{DataIntegrityProof, SignOptions};
use affinidi_did_resolver_cache_sdk::{config::DIDCacheConfigBuilder, DIDCacheClient};
use affinidi_secrets_resolver::secrets::Secret;
use serde_json::{json, Value};
use trust_tasks_proof::affinidi::{
    CachedDidResolver, ProofPurpose, ProofPurposeResolver, PurposeBound, Verifier,
};
use trust_tasks_rs::VerificationError;

const DID: &str = "did:web:issuer.example";
const OTHER: &str = "did:web:other.example";
const SEED: [u8; 32] = [9u8; 32];

fn public_multibase() -> String {
    Secret::generate_ed25519(None, Some(&SEED))
        .get_public_keymultibase()
        .expect("multikey")
}

/// A verification method for the seeded key.
fn method(id: &str, controller: &str) -> Value {
    json!({
        "id": id,
        "type": "Multikey",
        "controller": controller,
        "publicKeyMultibase": public_multibase(),
    })
}

async fn client_with(did: &str, doc: Value) -> DIDCacheClient {
    let doc: affinidi_did_common::Document = serde_json::from_value(doc).expect("DID document");
    let mut client = DIDCacheClient::new(DIDCacheConfigBuilder::default().build())
        .await
        .expect("local DIDCacheClient");
    client.add_did_document(did, doc).await;
    client
}

async fn verifier_with(did: &str, doc: Value) -> Verifier {
    let client = client_with(did, doc).await;
    Verifier::with_resolver(Arc::new(CachedDidResolver::new(Arc::new(client))))
}

/// A Trust Task document from `issuer`, signed by the seeded key as `vm`
/// with `proofPurpose` `purpose`.
async fn signed(issuer: &str, vm: &str, purpose: &str) -> Value {
    let doc = json!({
        "id": "urn:uuid:purpose-1",
        "type": "https://example.com/spec/heartbeat/0.1",
        "issuer": issuer,
        "recipient": "did:web:auditor.example",
        "issuedAt": "2026-01-01T00:00:00Z",
        "payload": { "nonce": 1 },
    });
    let secret = Secret::generate_ed25519(Some(vm), Some(&SEED));
    let proof = DataIntegrityProof::sign(
        &doc,
        &secret,
        SignOptions::new().with_proof_purpose(purpose),
    )
    .await
    .expect("sign");
    let mut doc = doc;
    doc["proof"] = serde_json::to_value(proof).unwrap();
    doc
}

fn refusal(err: VerificationError, rule: &str) {
    let msg = err.to_string();
    assert!(
        msg.contains(rule),
        "expected refusal naming {rule:?}, got: {msg}"
    );
    assert!(
        !msg.contains(&public_multibase()),
        "a refusal must not carry key material: {msg}"
    );
}

// ─── Wrong relationship ─────────────────────────────────────────────────

#[tokio::test]
async fn an_authentication_only_key_cannot_make_an_assertion() {
    let vm = format!("{DID}#key-1");
    let verifier = verifier_with(
        DID,
        json!({ "id": DID, "verificationMethod": [method(&vm, DID)], "authentication": [vm] }),
    )
    .await;

    let err = verifier
        .verify_raw(&signed(DID, &vm, "assertionMethod").await)
        .await
        .unwrap_err();
    refusal(err, "not listed under assertionMethod");

    verifier
        .verify_raw(&signed(DID, &vm, "authentication").await)
        .await
        .expect("the same key verifies for the purpose it is listed under");
}

#[tokio::test]
async fn an_assertion_only_key_cannot_authenticate() {
    let vm = format!("{DID}#key-1");
    let verifier = verifier_with(
        DID,
        json!({ "id": DID, "verificationMethod": [method(&vm, DID)], "assertionMethod": [vm] }),
    )
    .await;
    let err = verifier
        .verify_raw(&signed(DID, &vm, "authentication").await)
        .await
        .unwrap_err();
    refusal(err, "not listed under authentication");
}

#[tokio::test]
async fn a_key_agreement_key_signs_for_nothing() {
    let vm = format!("{DID}#key-1");
    let verifier = verifier_with(
        DID,
        json!({ "id": DID, "verificationMethod": [method(&vm, DID)], "keyAgreement": [vm] }),
    )
    .await;
    for purpose in ["assertionMethod", "authentication", "capabilityInvocation"] {
        assert!(verifier
            .verify_raw(&signed(DID, &vm, purpose).await)
            .await
            .is_err());
    }
    let err = verifier
        .verify_raw(&signed(DID, &vm, "keyAgreement").await)
        .await
        .unwrap_err();
    refusal(err, "keyAgreement never authorises a signature");
}

#[tokio::test]
async fn a_key_listed_under_no_relationship_signs_for_nothing() {
    let vm = format!("{DID}#key-1");
    let verifier = verifier_with(
        DID,
        json!({ "id": DID, "verificationMethod": [method(&vm, DID)] }),
    )
    .await;
    let err = verifier
        .verify_raw(&signed(DID, &vm, "assertionMethod").await)
        .await
        .unwrap_err();
    refusal(err, "not listed under assertionMethod");
}

#[tokio::test]
async fn an_unknown_purpose_is_refused() {
    let vm = format!("{DID}#key-1");
    let verifier = verifier_with(
        DID,
        json!({ "id": DID, "verificationMethod": [method(&vm, DID)], "assertionMethod": [vm] }),
    )
    .await;
    let err = verifier
        .verify_raw(&signed(DID, &vm, "somethingElse").await)
        .await
        .unwrap_err();
    refusal(err, "names no signing verification relationship");
}

// ─── Another DID's key ──────────────────────────────────────────────────

#[tokio::test]
async fn a_method_controlled_by_another_did_is_refused() {
    // The issuer's document embeds, under assertionMethod, a method named
    // under the issuer's DID but controlled by someone else.
    let vm = format!("{DID}#key-1");
    let verifier = verifier_with(
        DID,
        json!({ "id": DID, "assertionMethod": [method(&vm, OTHER)] }),
    )
    .await;
    let err = verifier
        .verify_raw(&signed(DID, &vm, "assertionMethod").await)
        .await
        .unwrap_err();
    refusal(err, "controller is not the DID that names it");
}

#[tokio::test]
async fn another_dids_key_listed_by_the_issuer_is_refused() {
    // The issuer lists a key of another DID under assertionMethod; a proof
    // naming that key is not the issuer's proof.
    let other_vm = format!("{OTHER}#key-1");
    let verifier = verifier_with(
        DID,
        json!({
            "id": DID,
            "verificationMethod": [method(&other_vm, OTHER)],
            "assertionMethod": [other_vm],
        }),
    )
    .await;
    let err = verifier
        .verify_raw(&signed(DID, &other_vm, "assertionMethod").await)
        .await
        .unwrap_err();
    assert!(
        matches!(err, VerificationError::IssuerMismatch(_)),
        "{err:?}"
    );
}

#[tokio::test]
async fn a_document_for_another_did_is_refused() {
    // The resolver returns a document whose id is not the DID resolved.
    let vm = format!("{DID}#key-1");
    let verifier = verifier_with(
        DID,
        json!({
            "id": OTHER,
            "verificationMethod": [method(&vm, DID)],
            "assertionMethod": [vm],
        }),
    )
    .await;
    let err = verifier
        .verify_raw(&signed(DID, &vm, "assertionMethod").await)
        .await
        .unwrap_err();
    refusal(err, "id is not the verificationMethod's DID");
}

// ─── References ─────────────────────────────────────────────────────────

#[tokio::test]
async fn a_relative_reference_resolves_against_the_document_id() {
    let vm = format!("{DID}#key-1");
    let verifier = verifier_with(
        DID,
        json!({
            "id": DID,
            "verificationMethod": [method(&vm, DID)],
            "assertionMethod": ["#key-1"],
        }),
    )
    .await;
    verifier
        .verify_raw(&signed(DID, &vm, "assertionMethod").await)
        .await
        .expect("#key-1 names the issuer's key-1");

    // …and a relative reference to a different fragment does not.
    let verifier = verifier_with(
        DID,
        json!({
            "id": DID,
            "verificationMethod": [method(&vm, DID)],
            "assertionMethod": ["#key-2"],
        }),
    )
    .await;
    assert!(verifier
        .verify_raw(&signed(DID, &vm, "assertionMethod").await)
        .await
        .is_err());
}

#[tokio::test]
async fn an_embedded_method_verifies_for_its_relationship_only() {
    let vm = format!("{DID}#key-1");
    let verifier = verifier_with(
        DID,
        json!({ "id": DID, "capabilityInvocation": [method(&vm, DID)] }),
    )
    .await;
    verifier
        .verify_raw(&signed(DID, &vm, "capabilityInvocation").await)
        .await
        .expect("embedded under capabilityInvocation");
    assert!(verifier
        .verify_raw(&signed(DID, &vm, "assertionMethod").await)
        .await
        .is_err());
}

/// A reference under the purpose's relationship resolves only against the
/// document's `verificationMethod` set, never to a method embedded under a
/// different relationship: that method was defined for that purpose alone.
#[tokio::test]
async fn a_reference_does_not_borrow_a_method_embedded_under_another_relationship() {
    let vm = format!("{DID}#key-1");
    let verifier = verifier_with(
        DID,
        json!({ "id": DID, "keyAgreement": [method(&vm, DID)], "assertionMethod": [vm] }),
    )
    .await;
    let err = verifier
        .verify_raw(&signed(DID, &vm, "assertionMethod").await)
        .await
        .unwrap_err();
    refusal(err, "not defined under verificationMethod");
}

// ─── did:key and did:peer ───────────────────────────────────────────────

fn did_key() -> (String, String) {
    let mb = public_multibase();
    (format!("did:key:{mb}"), format!("did:key:{mb}#{mb}"))
}

#[tokio::test]
async fn a_did_key_signs_for_every_signing_purpose() {
    let (did, vm) = did_key();
    let cached = Verifier::with_resolver(Arc::new(CachedDidResolver::new(Arc::new(
        DIDCacheClient::new(DIDCacheConfigBuilder::default().build())
            .await
            .unwrap(),
    ))));
    let offline = Verifier::for_did_key();
    for purpose in ProofPurpose::ALL {
        let doc = signed(&did, &vm, purpose.as_str()).await;
        offline
            .verify_raw(&doc)
            .await
            .unwrap_or_else(|e| panic!("did:key {purpose} offline: {e}"));
        cached
            .verify_raw(&doc)
            .await
            .unwrap_or_else(|e| panic!("did:key {purpose} via the cache: {e}"));
    }
    assert!(offline
        .verify_raw(&signed(&did, &vm, "keyAgreement").await)
        .await
        .is_err());
}

#[tokio::test]
async fn a_did_key_names_only_its_own_key() {
    let (did, _) = did_key();
    let err = Verifier::for_did_key()
        .verify_raw(&signed(&did, &format!("{did}#key-0"), "assertionMethod").await)
        .await
        .unwrap_err();
    refusal(err, "fragment must repeat the key id");
}

#[tokio::test]
async fn a_did_peer_v_key_signs_for_authentication_and_assertion_only() {
    // did:peer:2 with one V (verification) key: the resolver lists it under
    // authentication and assertionMethod as `#key-1`.
    let did = format!("did:peer:2.V{}", public_multibase());
    let vm = format!("{did}#key-1");
    let verifier = Verifier::with_resolver(Arc::new(CachedDidResolver::new(Arc::new(
        DIDCacheClient::new(DIDCacheConfigBuilder::default().build())
            .await
            .unwrap(),
    ))));
    for purpose in ["assertionMethod", "authentication"] {
        verifier
            .verify_raw(&signed(&did, &vm, purpose).await)
            .await
            .unwrap_or_else(|e| panic!("did:peer V key for {purpose}: {e}"));
    }
    assert!(verifier
        .verify_raw(&signed(&did, &vm, "capabilityInvocation").await)
        .await
        .is_err());
}

// ─── PurposeBound, for callers of DataIntegrityProof::verify ─────────────

#[tokio::test]
async fn purpose_bound_applies_the_rule_to_the_upstream_verify() {
    let vm = format!("{DID}#key-1");
    let client = client_with(
        DID,
        json!({ "id": DID, "verificationMethod": [method(&vm, DID)], "authentication": [vm] }),
    )
    .await;
    let resolver = CachedDidResolver::new(Arc::new(client));
    let mut doc = signed(DID, &vm, "assertionMethod").await;
    let proof: DataIntegrityProof = serde_json::from_value(doc["proof"].take()).unwrap();
    doc.as_object_mut().unwrap().remove("proof");

    let purpose = ProofPurpose::parse(&proof.proof_purpose).unwrap();
    assert!(proof
        .verify(
            &doc,
            &PurposeBound::new(&resolver, purpose),
            Default::default()
        )
        .await
        .is_err());
    assert!(resolver
        .resolve_vm_for_purpose(&vm, ProofPurpose::Authentication)
        .await
        .is_ok());
}

// ─── Migration: a key listed under both relationships ───────────────────

#[tokio::test]
async fn a_key_listed_for_both_purposes_verifies_either() {
    // The shape VTC and VTA DID documents publish today: `#key-0` under both
    // authentication and assertionMethod. Proofs made before and after the
    // move to `authentication` both verify.
    let vm = format!("{DID}#key-0");
    let verifier = verifier_with(
        DID,
        json!({
            "id": DID,
            "verificationMethod": [method(&vm, DID)],
            "authentication": [vm],
            "assertionMethod": [vm],
        }),
    )
    .await;
    for purpose in ["assertionMethod", "authentication"] {
        verifier
            .verify_raw(&signed(DID, &vm, purpose).await)
            .await
            .unwrap_or_else(|e| panic!("{purpose}: {e}"));
    }
}

// ─── Sign side ──────────────────────────────────────────────────────────

#[tokio::test]
async fn signing_refuses_a_purpose_no_verifier_accepts() {
    use trust_tasks_proof::affinidi::{sign_trust_task, SignError};
    let (did, vm) = did_key();
    let secret = Secret::generate_ed25519(Some(&vm), Some(&SEED));
    let doc = json!({ "id": "urn:uuid:s", "type": "https://example.com/spec/heartbeat/0.1",
        "issuer": did, "payload": {} });
    for purpose in ["keyAgreement", "nonsense"] {
        let err = sign_trust_task(
            &doc,
            &secret,
            SignOptions::new().with_proof_purpose(purpose),
        )
        .await
        .unwrap_err();
        assert!(
            matches!(err, SignError::DataIntegrity(_)),
            "{purpose}: {err}"
        );
    }
}