affinidi-did-resolver-cache-sdk 0.8.2

Affinidi DID Resolver SDK
Documentation
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
pub mod network_resolvers;
use crate::{DIDCacheClient, MethodName, errors::DIDCacheError};
#[cfg(any(
    not(feature = "did-webvh"),
    not(feature = "did-cheqd"),
    not(feature = "did-scid")
))]
use affinidi_did_common::DIDMethod;
use affinidi_did_common::{DID, Document};

impl DIDCacheClient {
    /// Resolves a DID to a DID Document by looking up the method's resolver chain.
    ///
    /// Resolvers for the method are tried front-to-back. Each returns `None` if
    /// it declines, `Some(Ok(doc))` on success, or `Some(Err(e))` on failure.
    /// The first resolver that returns `Some` wins.
    pub(crate) async fn local_resolve(&self, did: &DID) -> Result<Document, DIDCacheError> {
        let method_name: MethodName = MethodName::from(&did.method());

        if let Some(chain) = self.resolvers.get(&method_name) {
            for resolver in chain.iter() {
                if let Some(result) = resolver.resolve(did).await {
                    return result.map_err(|e| DIDCacheError::DIDError(e.to_string()));
                }
            }
        }

        // Preserve UnsupportedMethod errors for known but feature-disabled methods
        match did.method() {
            #[cfg(not(feature = "did-webvh"))]
            DIDMethod::Webvh { .. } => Err(DIDCacheError::UnsupportedMethod(
                "did:webvh is not enabled".to_string(),
            )),
            #[cfg(not(feature = "did-cheqd"))]
            DIDMethod::Cheqd { .. } => Err(DIDCacheError::UnsupportedMethod(
                "did:cheqd is not enabled".to_string(),
            )),
            #[cfg(not(feature = "did-scid"))]
            DIDMethod::Scid { .. } => Err(DIDCacheError::UnsupportedMethod(
                "did:scid is not enabled".to_string(),
            )),
            _ => Err(DIDCacheError::DIDError(format!(
                "No resolver registered for DID method '{}'",
                did.method()
            ))),
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::{DIDCacheClient, MethodName, config};
    use affinidi_did_common::DID;
    use affinidi_did_common::Document;
    use affinidi_did_resolver_traits::{AsyncResolver, Resolution, ResolverError};
    use std::future::Future;
    use std::pin::Pin;

    const DID_ETHR: &str = "did:ethr:0xb9c5714089478a327f09197987f16f9e5d936e8a";
    #[cfg(feature = "did-jwk")]
    const DID_JWK: &str = "did:jwk:eyJjcnYiOiJQLTI1NiIsImt0eSI6IkVDIiwieCI6ImFjYklRaXVNczNpOF91c3pFakoydHBUdFJNNEVVM3l6OTFQSDZDZEgyVjAiLCJ5IjoiX0tjeUxqOXZXTXB0bm1LdG00NkdxRHo4d2Y3NEk1TEtncmwyR3pIM25TRSJ9";
    // ED25519
    const DID_KEY: &str = "did:key:z6MkiToqovww7vYtxm1xNM15u9JzqzUFZ1k7s7MazYJUyAxv";
    const DID_PEER: &str = "did:peer:2.Vz6MkiToqovww7vYtxm1xNM15u9JzqzUFZ1k7s7MazYJUyAxv.EzQ3shQLqRUza6AMJFbPuMdvFRFWm1wKviQRnQSC1fScovJN4s.SeyJ0IjoiRElEQ29tbU1lc3NhZ2luZyIsInMiOnsidXJpIjoiaHR0cHM6Ly8xMjcuMC4wLjE6NzAzNyIsImEiOlsiZGlkY29tbS92MiJdLCJyIjpbXX19";
    const DID_PKH: &str = "did:pkh:solana:4sGjMW1sUnHzSxGspuhpqLDx6wiyjNtZ:CKg5d12Jhpej1JqtmxLJgaFqqeYjxgPqToJ4LBdvG9Ev";
    #[cfg(feature = "did-webvh")]
    const DID_WEBVH: &str = "did:webvh:Qmd1FCL9Vj2vJ433UDfC9MBstK6W6QWSQvYyeNn8va2fai:identity.foundation:didwebvh-implementations:implementations:affinidi-didwebvh-rs";
    #[cfg(feature = "did-cheqd")]
    const DID_CHEQD: &str = "did:cheqd:testnet:cad53e1d-71e0-48d2-9352-39cc3d0fac99";
    #[cfg(feature = "did-scid")]
    const DID_SCID: &str = "did:scid:vh:1:Qmd1FCL9Vj2vJ433UDfC9MBstK6W6QWSQvYyeNn8va2fai?src=identity.foundation/didwebvh-implementations/implementations/affinidi-didwebvh-rs";

    #[tokio::test]
    async fn local_resolve_ethr() {
        let config = config::DIDCacheConfigBuilder::default().build();
        let client = DIDCacheClient::new(config).await.unwrap();

        let did: DID = DID_ETHR.parse().unwrap();
        let did_document = client.local_resolve(&did).await.unwrap();

        assert_eq!(did_document.id.as_str(), DID_ETHR);

        assert_eq!(did_document.authentication.len(), 2);
        assert_eq!(did_document.assertion_method.len(), 2);

        assert_eq!(did_document.verification_method.len(), 2,);
    }

    #[tokio::test]
    #[cfg(feature = "did-jwk")]
    async fn local_resolve_jwk() {
        let config = config::DIDCacheConfigBuilder::default().build();
        let client = DIDCacheClient::new(config).await.unwrap();

        let did: DID = DID_JWK.parse().unwrap();
        let did_document = client.local_resolve(&did).await.unwrap();

        assert_eq!(did_document.id.as_str(), DID_JWK);

        assert_eq!(did_document.authentication.len(), 1);
        assert_eq!(did_document.assertion_method.len(), 1);
        assert_eq!(did_document.key_agreement.len(), 1);
        assert_eq!(did_document.capability_invocation.len(), 1);
        assert_eq!(did_document.capability_delegation.len(), 1);

        assert_eq!(did_document.verification_method.len(), 1);
        assert_eq!(
            did_document
                .verification_method
                .first()
                .unwrap()
                .property_set["publicKeyMultibase"],
            "zDnaepnC2eBkx4oZkNLGDnVK8ofKzoGk1Yui8fzC6FLoV1F1e"
        );
    }

    #[tokio::test]
    async fn local_resolve_key() {
        let config = config::DIDCacheConfigBuilder::default().build();
        let client = DIDCacheClient::new(config).await.unwrap();

        let did: DID = DID_KEY.parse().unwrap();
        let did_document = client.local_resolve(&did).await.unwrap();

        assert_eq!(did_document.id.as_str(), DID_KEY);

        assert_eq!(did_document.authentication.len(), 1);
        assert_eq!(did_document.assertion_method.len(), 1);
        assert_eq!(did_document.key_agreement.len(), 1);

        assert_eq!(did_document.verification_method.len(), 2);
    }

    #[tokio::test]
    async fn local_resolve_peer() {
        let config = config::DIDCacheConfigBuilder::default().build();
        let client = DIDCacheClient::new(config).await.unwrap();

        let did: DID = DID_PEER.parse().unwrap();
        let did_document = client.local_resolve(&did).await.unwrap();
        let verification_method = did_document.verification_method;
        let service = did_document.service;

        assert_eq!(did_document.id.as_str(), DID_PEER);

        assert_eq!(did_document.authentication.len(), 1);
        assert_eq!(did_document.assertion_method.len(), 1);
        assert_eq!(did_document.key_agreement.len(), 1);

        assert_eq!(verification_method.len(), 2);
        let first_public_key =
            &verification_method.first().unwrap().property_set["publicKeyMultibase"];

        let last_public_key =
            &verification_method.last().unwrap().property_set["publicKeyMultibase"];

        assert_eq!(
            first_public_key.as_str().expect("Not a string"),
            "z6MkiToqovww7vYtxm1xNM15u9JzqzUFZ1k7s7MazYJUyAxv"
        );
        assert_eq!(
            last_public_key.as_str().expect("Not a string"),
            "zQ3shQLqRUza6AMJFbPuMdvFRFWm1wKviQRnQSC1fScovJN4s"
        );

        assert_eq!(service.len(), 1);
        assert!(
            service
                .first()
                .unwrap()
                .id
                .as_ref()
                .is_some_and(|u| u.as_str() == [DID_PEER, "#service"].concat())
        );
    }

    #[tokio::test]
    async fn local_resolve_pkh() {
        let config = config::DIDCacheConfigBuilder::default().build();
        let client = DIDCacheClient::new(config).await.unwrap();

        let did: DID = DID_PKH.parse().unwrap();
        let did_document = client.local_resolve(&did).await.unwrap();
        let verification_method = did_document.verification_method;
        let vm_properties_first = verification_method.first().unwrap().property_set.clone();
        let vm_properties_last = verification_method.last().unwrap().property_set.clone();

        assert_eq!(did_document.id.as_str(), DID_PKH);

        assert_eq!(did_document.authentication.len(), 2);
        assert_eq!(did_document.assertion_method.len(), 2);

        assert_eq!(verification_method.len(), 2);
        // The last part of the DID is the public key
        let parts: Vec<&str> = DID_PKH.split(':').collect();
        assert_eq!(
            vm_properties_first["publicKeyBase58"],
            parts.last().unwrap().to_string()
        );
        assert_eq!(
            vm_properties_first["blockchainAccountId"],
            parts[2..parts.len()].join(":")
        );
        assert_eq!(
            vm_properties_last["blockchainAccountId"],
            parts[2..parts.len()].join(":")
        );
        assert!(vm_properties_last["publicKeyJwk"].is_object(),);
    }

    #[tokio::test]
    #[cfg(feature = "did-webvh")]
    #[ignore = "requires external network (identity.foundation)"]
    async fn local_resolve_webvh() {
        let config = config::DIDCacheConfigBuilder::default().build();
        let client = DIDCacheClient::new(config).await.unwrap();

        let did: DID = DID_WEBVH.parse().unwrap();
        let did_document = client.local_resolve(&did).await.unwrap();

        assert_eq!(did_document.id.as_str(), DID_WEBVH);
    }

    #[tokio::test]
    #[cfg(feature = "did-cheqd")]
    #[ignore = "requires external network (cheqd.net)"]
    async fn local_resolve_cheqd() {
        let config = config::DIDCacheConfigBuilder::default().build();
        let client = DIDCacheClient::new(config).await.unwrap();

        let did_document = client.resolve(DID_CHEQD).await.unwrap();

        assert_eq!(did_document.did.as_str(), DID_CHEQD);

        assert_eq!(did_document.doc.authentication.len(), 1);
        assert_eq!(did_document.doc.assertion_method.len(), 0);

        assert_eq!(did_document.doc.verification_method.len(), 1);
    }

    #[tokio::test]
    #[cfg(feature = "did-scid")]
    #[ignore = "requires external network (identity.foundation)"]
    async fn local_resolve_scid() {
        let config = config::DIDCacheConfigBuilder::default().build();
        let client = DIDCacheClient::new(config).await.unwrap();

        let did_document = client.resolve(DID_SCID).await.unwrap();
        assert_eq!(
            did_document.did.as_str(),
            "did:webvh:Qmd1FCL9Vj2vJ433UDfC9MBstK6W6QWSQvYyeNn8va2fai:identity.foundation:didwebvh-implementations:implementations:affinidi-didwebvh-rs"
        );
    }

    // -----------------------------------------------------------------------
    // Test resolvers
    // -----------------------------------------------------------------------

    /// A test resolver that handles `did:test:*` DIDs.
    struct TestResolver;

    impl AsyncResolver for TestResolver {
        fn name(&self) -> &str {
            "TestResolver"
        }

        fn resolve<'a>(
            &'a self,
            did: &'a DID,
        ) -> Pin<Box<dyn Future<Output = Resolution> + Send + 'a>> {
            Box::pin(async move {
                let did_str = did.to_string();
                if !did_str.starts_with("did:test:") {
                    return None;
                }
                // Return a minimal valid document
                let doc_json = format!(
                    r#"{{"id":"{}","verificationMethod":[],"authentication":[],"assertionMethod":[],"keyAgreement":[],"capabilityInvocation":[],"capabilityDelegation":[],"service":[]}}"#,
                    did_str
                );
                Some(
                    serde_json::from_str::<Document>(&doc_json)
                        .map_err(|e| ResolverError::InvalidDocument(e.to_string())),
                )
            })
        }
    }

    /// A resolver that intercepts did:key and returns a stub document,
    /// proving custom resolvers take priority over built-ins.
    struct OverrideKeyResolver;

    impl AsyncResolver for OverrideKeyResolver {
        fn name(&self) -> &str {
            "OverrideKeyResolver"
        }

        fn resolve<'a>(
            &'a self,
            did: &'a DID,
        ) -> Pin<Box<dyn Future<Output = Resolution> + Send + 'a>> {
            Box::pin(async move {
                let did_str = did.to_string();
                if !did_str.starts_with("did:key:") {
                    return None;
                }
                // Return a stub document with 0 verification methods
                // (built-in KeyResolver returns 2 for Ed25519)
                let doc_json = format!(
                    r#"{{"id":"{}","verificationMethod":[],"authentication":[],"assertionMethod":[],"keyAgreement":[],"capabilityInvocation":[],"capabilityDelegation":[],"service":[]}}"#,
                    did_str
                );
                Some(
                    serde_json::from_str::<Document>(&doc_json)
                        .map_err(|e| ResolverError::InvalidDocument(e.to_string())),
                )
            })
        }
    }

    // -----------------------------------------------------------------------
    // API tests
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn custom_resolver_for_new_method() {
        let config = config::DIDCacheConfigBuilder::default().build();
        let mut client = DIDCacheClient::new(config).await.unwrap();

        // Register a resolver for a method with no built-in
        client.set_resolver(
            MethodName::Other("test".to_string()),
            Box::new(TestResolver),
        );
        let did: DID = "did:test:alice".parse().unwrap();
        let doc = client.local_resolve(&did).await.unwrap();
        assert_eq!(doc.id.as_str(), "did:test:alice");
    }

    #[tokio::test]
    async fn custom_resolver_overrides_builtin() {
        let config = config::DIDCacheConfigBuilder::default().build();
        let mut client = DIDCacheClient::new(config).await.unwrap();

        // Built-in KeyResolver returns 2 verification methods for Ed25519
        let did: DID = DID_KEY.parse().unwrap();
        let doc = client.local_resolve(&did).await.unwrap();
        assert_eq!(doc.verification_method.len(), 2);

        // Replace built-in with override that returns 0 verification methods
        client.set_resolver(MethodName::Key, Box::new(OverrideKeyResolver));
        let doc = client.local_resolve(&did).await.unwrap();
        // Custom resolver wins — 0 VMs instead of 2
        assert_eq!(doc.verification_method.len(), 0);
        assert_eq!(doc.id.as_str(), DID_KEY);
    }

    #[tokio::test]
    async fn unregistered_method_returns_error() {
        let config = config::DIDCacheConfigBuilder::default().build();
        let client = DIDCacheClient::new(config).await.unwrap();

        // did:test is not registered by default
        let did: DID = "did:test:alice".parse().unwrap();
        let result = client.local_resolve(&did).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn prepend_resolver_enforces_uniqueness() {
        let config = config::DIDCacheConfigBuilder::default().build();
        let mut client = DIDCacheClient::new(config).await.unwrap();

        // First registration succeeds
        let result = client.prepend_resolver(
            MethodName::Other("test".to_string()),
            Box::new(TestResolver),
        );
        assert!(result.is_ok());

        // Duplicate name fails
        let result = client.prepend_resolver(
            MethodName::Other("test".to_string()),
            Box::new(TestResolver),
        );
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn append_resolver_enforces_uniqueness() {
        let config = config::DIDCacheConfigBuilder::default().build();
        let mut client = DIDCacheClient::new(config).await.unwrap();

        let result = client.append_resolver(
            MethodName::Other("test".to_string()),
            Box::new(TestResolver),
        );
        assert!(result.is_ok());

        let result = client.append_resolver(
            MethodName::Other("test".to_string()),
            Box::new(TestResolver),
        );
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn find_and_remove_resolver() {
        let config = config::DIDCacheConfigBuilder::default().build();
        let mut client = DIDCacheClient::new(config).await.unwrap();

        // KeyResolver is registered at construction
        let idx = client.find_resolver(&MethodName::Key, "KeyResolver");
        assert_eq!(idx, Some(0));

        // Remove it
        let removed = client.remove_resolver(&MethodName::Key, 0);
        assert!(removed.is_some());
        assert_eq!(removed.unwrap().name(), "KeyResolver");

        // Now it's gone
        assert!(
            client
                .find_resolver(&MethodName::Key, "KeyResolver")
                .is_none()
        );

        // did:key resolution should fail
        let did: DID = DID_KEY.parse().unwrap();
        assert!(client.local_resolve(&did).await.is_err());
    }

    #[tokio::test]
    async fn clear_resolvers_removes_all() {
        let config = config::DIDCacheConfigBuilder::default().build();
        let mut client = DIDCacheClient::new(config).await.unwrap();

        // Verify key resolution works
        let did: DID = DID_KEY.parse().unwrap();
        assert!(client.local_resolve(&did).await.is_ok());

        // Clear and verify it fails
        client.clear_resolvers(&MethodName::Key);
        assert!(client.local_resolve(&did).await.is_err());
    }

    #[tokio::test]
    async fn prepend_gives_priority_over_existing() {
        let config = config::DIDCacheConfigBuilder::default().build();
        let mut client = DIDCacheClient::new(config).await.unwrap();

        // Built-in KeyResolver returns 2 VMs
        let did: DID = DID_KEY.parse().unwrap();
        let doc = client.local_resolve(&did).await.unwrap();
        assert_eq!(doc.verification_method.len(), 2);

        // Prepend override (0 VMs) — it goes before built-in
        client
            .prepend_resolver(MethodName::Key, Box::new(OverrideKeyResolver))
            .unwrap();
        let doc = client.local_resolve(&did).await.unwrap();
        assert_eq!(doc.verification_method.len(), 0);

        // Built-in is still there at index 1
        assert_eq!(
            client.find_resolver(&MethodName::Key, "KeyResolver"),
            Some(1)
        );
        assert_eq!(
            client.find_resolver(&MethodName::Key, "OverrideKeyResolver"),
            Some(0)
        );
    }
}