vta-sdk 0.55.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
//! A proof's key must be authorised for the purpose the proof declares.
//!
//! **VTI-KEY-022**: a verifier MUST check that the key used is authorised for
//! the purpose the material is relied on for, and MUST refuse where it is not.
//! For a W3C Data Integrity proof that purpose is its `proofPurpose`, and the
//! authorisation is the DID document's verification relationship of the same
//! name (Controlled Identifiers v1.0 §3.3, *Retrieve Verification Method*,
//! steps 10 and 11; restated for Trust Task documents by the framework's
//! "Proof Purpose and Verification Relationship").
//!
//! # Why this is not left to the upstream resolver trait
//!
//! `affinidi_data_integrity::VerificationMethodResolver::resolve_vm` receives
//! only the method URI. A resolver behind it cannot know what the proof claims
//! to be for, so every resolver here used to accept any key the DID document
//! listed — including one published for key agreement, or authorised only to
//! authenticate — as a key that could make any assertion. [`PurposeVmResolver`]
//! carries the purpose, and [`PurposeBound`] hands the upstream `verify` a
//! resolver fixed to one proof's purpose.
//!
//! # What is checked
//!
//! [`authorised_method`] requires, of the resolved document:
//!
//! 1. its `id` is the DID the method URI names;
//! 2. the relationship `proofPurpose` names lists the method — by absolute DID
//!    URL, by `#fragment` relative to the document id, or embedded;
//! 3. the method's `controller` is that DID.
//!
//! `keyAgreement` is never a signing purpose; [`ProofPurpose::parse`] refuses
//! it along with any unknown value. `did:key` has implicit relationships: its
//! key `did:key:<id>#<id>` is authorised for all four signing purposes.
//!
//! Refusals name the rule that failed, never the document, a DID or key
//! material — they reach logs.

use affinidi_data_integrity::{
    DataIntegrityError, DataIntegrityProof, ResolvedKey, VerificationMethodResolver,
};
use affinidi_did_common::Document;
use affinidi_did_common::verification_method::{VerificationMethod, VerificationRelationship};

/// A verification relationship a signature can be made under — the values a
/// proof's `proofPurpose` may take. `keyAgreement` is deliberately absent.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ProofPurpose {
    /// `assertionMethod` — an attestation a third party may rely on.
    AssertionMethod,
    /// `authentication` — the signer proves control of the identifier.
    Authentication,
    /// `capabilityInvocation`.
    CapabilityInvocation,
    /// `capabilityDelegation`.
    CapabilityDelegation,
}

impl ProofPurpose {
    /// Every purpose a signature can carry.
    pub const ALL: [ProofPurpose; 4] = [
        ProofPurpose::AssertionMethod,
        ProofPurpose::Authentication,
        ProofPurpose::CapabilityInvocation,
        ProofPurpose::CapabilityDelegation,
    ];

    /// The `proofPurpose` value, which is also the DID-document property
    /// naming the relationship.
    #[must_use]
    pub fn as_str(&self) -> &'static str {
        match self {
            ProofPurpose::AssertionMethod => "assertionMethod",
            ProofPurpose::Authentication => "authentication",
            ProofPurpose::CapabilityInvocation => "capabilityInvocation",
            ProofPurpose::CapabilityDelegation => "capabilityDelegation",
        }
    }

    /// Parse a proof's `proofPurpose`, refusing `keyAgreement`, an empty
    /// value and anything naming no signing relationship.
    pub fn parse(value: &str) -> Result<Self, DataIntegrityError> {
        match value {
            "assertionMethod" => Ok(ProofPurpose::AssertionMethod),
            "authentication" => Ok(ProofPurpose::Authentication),
            "capabilityInvocation" => Ok(ProofPurpose::CapabilityInvocation),
            "capabilityDelegation" => Ok(ProofPurpose::CapabilityDelegation),
            "keyAgreement" => Err(DataIntegrityError::MalformedProof(
                "proofPurpose keyAgreement never authorises a signature".to_string(),
            )),
            _ => Err(DataIntegrityError::MalformedProof(
                "proofPurpose names no signing verification relationship".to_string(),
            )),
        }
    }
}

impl std::fmt::Display for ProofPurpose {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Slugs whose documents the registry defines as the issuer's **attestation**
/// — an approver's decision a third party relies on — and so requires to be
/// signed for `assertionMethod`, by a key listed under that relationship:
///
/// - `auth/step-up/approve-response` — "the approver's attestation of a
///   decision" (0.1–0.5);
/// - `task-consent/decision` — "the approver's attestation, not an operational
///   message";
/// - `confirm/response` — the subject's signed confirmation.
///
/// Every other document is operational and is signed for `authentication`
/// (VTI-KEY-106, VTI-KEY-022).
pub const ATTESTATION_SLUGS: [&str; 3] = [
    "auth/step-up/approve-response",
    "task-consent/decision",
    "confirm/response",
];

/// The purpose a Trust Task document of type `type_uri` must be signed for.
///
/// `assertionMethod` only for a request document of a registry slug in
/// [`ATTESTATION_SLUGS`]; `authentication` for everything else, including the
/// `#response` variant of such a slug (the executor's reply, an operational
/// message) and a private registry's reuse of the slug (only
/// `https://trusttasks.org` slugs are classified). Nothing a requester
/// supplies other than the type decides it, so an operational document can
/// never be signed as an attestation.
#[must_use]
pub fn purpose_for_document_type(type_uri: &trust_tasks_rs::TypeUri) -> ProofPurpose {
    let on_registry =
        trust_tasks_rs::TypeUri::canonical(type_uri.slug(), type_uri.major(), type_uri.minor())
            .is_ok_and(|canonical| canonical == type_uri.bare());
    let is_attestation =
        !type_uri.is_response() && on_registry && ATTESTATION_SLUGS.contains(&type_uri.slug());
    if is_attestation {
        ProofPurpose::AssertionMethod
    } else {
        ProofPurpose::Authentication
    }
}

/// Resolves a verification method to its key **only if** the DID that names
/// it authorised it for `purpose` (see the module docs for the rules).
#[async_trait::async_trait]
pub trait PurposeVmResolver: Send + Sync {
    /// Resolve `vm` — an absolute DID URL — for a proof declaring `purpose`.
    async fn resolve_vm_for_purpose(
        &self,
        vm: &str,
        purpose: ProofPurpose,
    ) -> Result<ResolvedKey, DataIntegrityError>;
}

#[async_trait::async_trait]
impl<R: PurposeVmResolver + ?Sized> PurposeVmResolver for &R {
    async fn resolve_vm_for_purpose(
        &self,
        vm: &str,
        purpose: ProofPurpose,
    ) -> Result<ResolvedKey, DataIntegrityError> {
        (**self).resolve_vm_for_purpose(vm, purpose).await
    }
}

#[async_trait::async_trait]
impl<R: PurposeVmResolver + ?Sized> PurposeVmResolver for std::sync::Arc<R> {
    async fn resolve_vm_for_purpose(
        &self,
        vm: &str,
        purpose: ProofPurpose,
    ) -> Result<ResolvedKey, DataIntegrityError> {
        (**self).resolve_vm_for_purpose(vm, purpose).await
    }
}

/// A [`PurposeVmResolver`] fixed to one proof's purpose, as the upstream
/// [`VerificationMethodResolver`] `DataIntegrityProof::verify` takes:
///
/// ```ignore
/// proof.verify(&doc, &PurposeBound::for_proof(&resolver, &proof)?, options).await?;
/// ```
pub struct PurposeBound<R> {
    resolver: R,
    purpose: ProofPurpose,
}

impl<R> PurposeBound<R> {
    /// Bind `resolver` to `purpose`.
    pub fn new(resolver: R, purpose: ProofPurpose) -> Self {
        Self { resolver, purpose }
    }

    /// Bind `resolver` to the purpose `proof` declares, refusing a purpose no
    /// signature can carry.
    pub fn for_proof(resolver: R, proof: &DataIntegrityProof) -> Result<Self, DataIntegrityError> {
        Ok(Self::new(
            resolver,
            ProofPurpose::parse(&proof.proof_purpose)?,
        ))
    }

    /// The purpose every resolution is checked against.
    pub fn purpose(&self) -> ProofPurpose {
        self.purpose
    }
}

#[async_trait::async_trait]
impl<R: PurposeVmResolver> VerificationMethodResolver for PurposeBound<R> {
    async fn resolve_vm(&self, vm: &str) -> Result<ResolvedKey, DataIntegrityError> {
        self.resolver.resolve_vm_for_purpose(vm, self.purpose).await
    }
}

/// Split an absolute verification-method DID URL into its DID and fragment.
/// A relative reference, or a DID URL with no fragment, names no method.
pub fn split_vm(vm: &str) -> Result<(&str, &str), DataIntegrityError> {
    match vm.split_once('#') {
        Some((did, fragment)) if did.starts_with("did:") && !fragment.is_empty() => {
            Ok((did, fragment))
        }
        _ => Err(DataIntegrityError::Resolver(
            "verificationMethod must be an absolute DID URL with a fragment".to_string(),
        )),
    }
}

/// `did:key`'s implicit relationships: the only method is
/// `did:key:<id>#<id>`, authorised for every signing purpose. Refuses any
/// other method URI.
pub fn check_did_key_method(vm: &str) -> Result<(), DataIntegrityError> {
    let (did, fragment) = split_vm(vm)?;
    let id = did.strip_prefix("did:key:").ok_or_else(|| {
        DataIntegrityError::Resolver("verificationMethod is not a did:key".to_string())
    })?;
    if fragment != id {
        return Err(DataIntegrityError::Resolver(
            "verificationMethod is not the did:key's own key (fragment must repeat the key id)"
                .to_string(),
        ));
    }
    Ok(())
}

fn relationship(doc: &Document, purpose: ProofPurpose) -> &[VerificationRelationship] {
    match purpose {
        ProofPurpose::AssertionMethod => &doc.assertion_method,
        ProofPurpose::Authentication => &doc.authentication,
        ProofPurpose::CapabilityInvocation => &doc.capability_invocation,
        ProofPurpose::CapabilityDelegation => &doc.capability_delegation,
    }
}

/// The verification method `vm` names in `doc`, provided `doc` is `did`'s
/// document, the relationship `purpose` names lists the method, and the
/// method's controller is `did`.
pub fn authorised_method(
    doc: &Document,
    did: &str,
    vm: &str,
    purpose: ProofPurpose,
) -> Result<VerificationMethod, DataIntegrityError> {
    if doc.id.as_str() != did {
        return Err(DataIntegrityError::Resolver(
            "the resolved DID document's id is not the verificationMethod's DID".to_string(),
        ));
    }
    // A reference is an absolute DID URL or a fragment relative to `did`.
    let names_vm = |id: &str| match id.strip_prefix('#') {
        Some(fragment) => {
            vm.strip_prefix(did).and_then(|rest| rest.strip_prefix('#')) == Some(fragment)
        }
        None => id == vm,
    };
    let embedded = |r: &VerificationRelationship| match r {
        VerificationRelationship::VerificationMethod(m) if names_vm(m.id.as_str()) => {
            Some((**m).clone())
        }
        _ => None,
    };

    // `Some(None)`: listed by reference; `Some(Some(m))`: embedded.
    let listed = relationship(doc, purpose).iter().find_map(|r| match r {
        VerificationRelationship::Reference(id) if names_vm(id) => Some(None),
        other => embedded(other).map(Some),
    });
    let method = match listed {
        None => {
            return Err(DataIntegrityError::Resolver(format!(
                "verificationMethod is not listed under {purpose} in its DID document"
            )));
        }
        Some(Some(method)) => method,
        // A reference names a method defined in the document's
        // `verificationMethod` set. It is never resolved to a method embedded
        // under another relationship: that method is authorised for that
        // relationship only, and borrowing it here would let the purpose's
        // list vouch for a key defined for a different purpose.
        Some(None) => doc
            .verification_method
            .iter()
            .find(|m| names_vm(m.id.as_str()))
            .cloned()
            .ok_or_else(|| {
                DataIntegrityError::Resolver(
                    "verificationMethod is referenced but not defined under verificationMethod \
                     in its DID document"
                        .to_string(),
                )
            })?,
    };
    if method.controller.as_str() != did {
        return Err(DataIntegrityError::Resolver(
            "verificationMethod's controller is not the DID that names it".to_string(),
        ));
    }
    Ok(method)
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    const DID: &str = "did:web:issuer.example";

    fn doc(v: serde_json::Value) -> Document {
        serde_json::from_value(v).expect("DID document")
    }

    fn method(id: &str, controller: &str) -> serde_json::Value {
        json!({ "id": id, "type": "Multikey", "controller": controller,
                "publicKeyMultibase": "z6MkhaXgBZDvotDkL5257faiztiGiC2QtKLGpbnnEGta2doK" })
    }

    fn vm() -> String {
        format!("{DID}#key-1")
    }

    #[test]
    fn a_method_in_the_wrong_relationship_is_refused() {
        let d = doc(
            json!({ "id": DID, "verificationMethod": [method(&vm(), DID)],
                             "authentication": [vm()] }),
        );
        let err = authorised_method(&d, DID, &vm(), ProofPurpose::AssertionMethod).unwrap_err();
        assert!(
            err.to_string().contains("not listed under assertionMethod"),
            "{err}"
        );
        authorised_method(&d, DID, &vm(), ProofPurpose::Authentication).expect("listed");
    }

    #[test]
    fn a_key_agreement_key_is_never_a_signing_key() {
        let d = doc(
            json!({ "id": DID, "verificationMethod": [method(&vm(), DID)],
                             "keyAgreement": [vm()] }),
        );
        for p in ProofPurpose::ALL {
            assert!(authorised_method(&d, DID, &vm(), p).is_err(), "{p}");
        }
        assert!(ProofPurpose::parse("keyAgreement").is_err());
        assert!(ProofPurpose::parse("").is_err());
        assert!(ProofPurpose::parse("assertion").is_err());
    }

    #[test]
    fn a_method_of_another_did_is_refused() {
        // Embedded under the issuer's DID but controlled by someone else.
        let d =
            doc(json!({ "id": DID, "assertionMethod": [method(&vm(), "did:web:other.example")] }));
        let err = authorised_method(&d, DID, &vm(), ProofPurpose::AssertionMethod).unwrap_err();
        assert!(err.to_string().contains("controller"), "{err}");

        // A document that is not the DID's own.
        let d = doc(json!({ "id": "did:web:other.example",
                             "verificationMethod": [method(&vm(), DID)],
                             "assertionMethod": [vm()] }));
        let err = authorised_method(&d, DID, &vm(), ProofPurpose::AssertionMethod).unwrap_err();
        assert!(err.to_string().contains("document's id"), "{err}");

        // Another DID's key listed by the issuer.
        let other = "did:web:other.example#key-1";
        let d = doc(
            json!({ "id": DID, "verificationMethod": [method(other, "did:web:other.example")],
                             "assertionMethod": [other] }),
        );
        assert!(authorised_method(&d, DID, other, ProofPurpose::AssertionMethod).is_err());
    }

    #[test]
    fn a_relative_reference_resolves_against_the_document_id() {
        let d = doc(
            json!({ "id": DID, "verificationMethod": [method(&vm(), DID)],
                             "assertionMethod": ["#key-1"] }),
        );
        authorised_method(&d, DID, &vm(), ProofPurpose::AssertionMethod).expect("#key-1");
        let d = doc(
            json!({ "id": DID, "verificationMethod": [method(&vm(), DID)],
                             "assertionMethod": ["#key-2"] }),
        );
        assert!(authorised_method(&d, DID, &vm(), ProofPurpose::AssertionMethod).is_err());
    }

    #[test]
    fn an_embedded_method_counts_for_its_own_relationship() {
        let d = doc(json!({ "id": DID, "authentication": [method(&vm(), DID)] }));
        authorised_method(&d, DID, &vm(), ProofPurpose::Authentication).expect("embedded");
        assert!(authorised_method(&d, DID, &vm(), ProofPurpose::AssertionMethod).is_err());
    }

    #[test]
    fn a_did_key_names_only_its_own_key() {
        let id = "z6MkhaXgBZDvotDkL5257faiztiGiC2QtKLGpbnnEGta2doK";
        check_did_key_method(&format!("did:key:{id}#{id}")).expect("its own key");
        assert!(check_did_key_method(&format!("did:key:{id}#key-0")).is_err());
        assert!(check_did_key_method(&format!("did:key:{id}")).is_err());
    }

    #[test]
    fn refusals_carry_no_identifier() {
        let d = doc(json!({ "id": DID, "verificationMethod": [method(&vm(), DID)] }));
        let err = authorised_method(&d, DID, &vm(), ProofPurpose::AssertionMethod).unwrap_err();
        assert!(!err.to_string().contains(DID), "{err}");
    }
}