vta-service 0.62.0

Service 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
//! A **persona**: a DID this agent holds for a person in one of their trust contexts, and
//! the key it signs with as that DID.
//!
//! # Why one resolver
//!
//! In a data room a member is a DID: the subject of the invitation the room issued, the
//! identity on their MLS leaf, the subject of their membership and authority credentials,
//! and the signer of anything they narrow those credentials into. All four must be the
//! same DID, and it must be one the member's own agent holds the key for — otherwise the
//! agent cannot act for them, and somebody else's key is standing in for theirs.
//!
//! That DID is **never the interface client's** (a `pnm` session's `did:key`, a wallet
//! extension's, an agent's). A client key lives in the client: this agent cannot sign as it,
//! it changes whenever the client is reinstalled or rotated, and a person using two clients
//! would be two members. So every room path that asks "who is the member?" asks this
//! module, and the answer is a persona the caller may act as — or nothing.
//!
//! # The rule
//!
//! [`persona_signing_key`] answers for `did` and the caller's `auth`:
//!
//! - **A `did:webvh` this agent minted** (`webvh` builds only): the caller must be able to
//!   act in the DID's context. The method is read from the DID's **own log** — no
//!   resolution: this agent published it, and an answer that depends on the network is one
//!   a host can shape — as the first `assertionMethod` entry, under the DID itself, whose
//!   public key is an active Ed25519 key record **of that same context**.
//! - **A `did:key`**: an active Ed25519 key record with that public key, in a context the
//!   caller may act in (or, for a record with no context, a caller who is super-admin).
//! - **A `did:peer`**: its document is derived from the identifier with no I/O, exactly as a
//!   verifier derives it. The method is the first entry of the wanted relationship, under
//!   the DID itself, whose public key is an active Ed25519 key record in a context the caller
//!   may act in — the `did:key` rule, applied per method. This is the shape of a pairwise
//!   **relationship DID** (`did:peer:2`, its signing key `V`, its key-agreement key `E`),
//!   whose keys a client may keep at its VTA.
//!
//! Anything else is `None`, and `None` deliberately does not say why: an unknown DID and one
//! held in a context the caller cannot reach answer alike, so a refusal never tells a caller
//! which DIDs this agent holds for other people. Callers turn `None` into one refusal and
//! must keep it one.
//!
//! # What it is not
//!
//! **This agent's own DID is not a persona.** It is shared infrastructure: every principal's
//! rooms would carry the same identifier, linking them to one another, and acting as it is
//! not bounded by any context a caller acts in. The one task that may still sign as the
//! agent — `rooms/owner/register` naming it as `ownerDid`, which predates personas — handles
//! that case itself ([`crate::operations::room_host::owner_signing_key`]), outside this rule.
//!
//! **It confers nothing.** It decides *which* key; whoever then signs goes through the gated
//! oracle ([`crate::operations::keys::sign_payload`]), which re-checks the key's context, the
//! caller's key scope and the context's signing policy. No key material is derived here.

use serde_json::Value;
use vti_common::error::AppError;
use vti_common::store::KeyspaceHandle;

use crate::auth::AuthClaims;

/// The key, and the verification method it is published as, that this agent signs with
/// **as** a persona.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PersonaKey {
    /// The key record the gated oracle signs with.
    pub key_id: String,
    /// The method the persona's DID document lists the key under, which a proof names.
    pub verification_method: String,
}

/// The stores [`persona_signing_key`] reads.
#[derive(Clone, Copy)]
pub struct PersonaStores<'a> {
    pub keys_ks: &'a KeyspaceHandle,
    /// The `did:webvh` logs this agent publishes. A build without `webvh` publishes none,
    /// so a `did:webvh` is never a persona there.
    #[cfg(feature = "webvh")]
    pub webvh_ks: &'a KeyspaceHandle,
}

impl<'a> PersonaStores<'a> {
    /// The stores, from the running service.
    pub fn from_state(state: &'a crate::server::AppState) -> Self {
        Self {
            keys_ks: &state.keys_ks,
            #[cfg(feature = "webvh")]
            webvh_ks: &state.webvh_ks,
        }
    }
}

/// The verification relationship a persona's key is wanted for.
///
/// A credential the persona issues, or a record body it authors, is an attestation
/// (`assertionMethod`); a room request it sends as itself — `rooms/keys/act`, and the
/// documents `read` / `browse` / `backfill` send — proves control of the identifier
/// (`authentication`). A verifier checks the key against the relationship the proof
/// declares (VTI-KEY-022), so the method a proof names must be listed under that one.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Relationship {
    /// `assertionMethod`.
    AssertionMethod,
    /// `authentication`.
    Authentication,
}

impl Relationship {
    /// The DID-document property, which is also the `proofPurpose` value.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::AssertionMethod => "assertionMethod",
            Self::Authentication => "authentication",
        }
    }
}

/// The key this agent signs with as persona `did`, if `did` is a persona `auth` may act as.
///
/// `None` for a DID this agent does not hold **and** for one it holds in a context the
/// caller cannot act in — indistinguishably, see the module docs.
pub async fn persona_signing_key(
    stores: PersonaStores<'_>,
    auth: &AuthClaims,
    did: &str,
) -> Result<Option<PersonaKey>, AppError> {
    persona_key_for(stores, auth, did, Relationship::AssertionMethod).await
}

/// [`persona_signing_key`], for the key the persona's document lists under `relationship`.
///
/// Whether `did` is a persona the caller may act as does not depend on the relationship:
/// the context rules are the same, and only which method a proof names differs.
pub async fn persona_key_for(
    stores: PersonaStores<'_>,
    auth: &AuthClaims,
    did: &str,
    relationship: Relationship,
) -> Result<Option<PersonaKey>, AppError> {
    // A DID URL is not a DID. Accepting `did#fragment` here would let a caller name a
    // persona by a string no credential or leaf carries.
    if did.contains('#') {
        return Ok(None);
    }

    if let Some(id) = did.strip_prefix("did:key:") {
        let record = held_ed25519(stores.keys_ks, id, &|ctx| match ctx {
            Some(ctx) => auth.has_context_access(ctx),
            None => auth.is_super_admin(),
        })
        .await?;
        return Ok(record.map(|record| PersonaKey {
            key_id: record.key_id,
            verification_method: format!("did:key:{id}#{id}"),
        }));
    }

    if did.starts_with("did:peer:") {
        return peer_persona_key(stores.keys_ks, auth, did, relationship).await;
    }

    #[cfg(feature = "webvh")]
    if did.starts_with("did:webvh:") {
        return webvh_persona_key(stores.keys_ks, stores.webvh_ks, auth, did, relationship).await;
    }

    Ok(None)
}

/// The `did:peer` arm of [`persona_key_for`]: the document is derived from the identifier —
/// "pure computation", as the verifier's own `did:peer` path does — and each method of the
/// relationship is matched against the caller's key records as a `did:key` is.
async fn peer_persona_key(
    keys_ks: &KeyspaceHandle,
    auth: &AuthClaims,
    did: &str,
    relationship: Relationship,
) -> Result<Option<PersonaKey>, AppError> {
    use affinidi_did_resolver_traits::{PeerResolver, Resolver};
    let Ok(parsed) = affinidi_did_common::DID::try_from(did) else {
        return Ok(None);
    };
    let Some(Ok(document)) = PeerResolver.resolve(&parsed) else {
        return Ok(None);
    };
    let document = serde_json::to_value(&document)
        .map_err(|e| AppError::Internal(format!("encode the document of {did}: {e}")))?;
    held_method(keys_ks, did, &document, relationship, |ctx| match ctx {
        Some(ctx) => auth.has_context_access(ctx),
        None => auth.is_super_admin(),
    })
    .await
}

/// The `did:webvh` arm of [`persona_signing_key`].
#[cfg(feature = "webvh")]
async fn webvh_persona_key(
    keys_ks: &KeyspaceHandle,
    webvh_ks: &KeyspaceHandle,
    auth: &AuthClaims,
    did: &str,
    relationship: Relationship,
) -> Result<Option<PersonaKey>, AppError> {
    let Some(record) = crate::webvh_store::get_did(webvh_ks, did).await? else {
        return Ok(None);
    };
    if !auth.has_context_access(&record.context_id) {
        return Ok(None);
    }
    let Some(log) = crate::webvh_store::get_did_log(webvh_ks, did).await? else {
        return Ok(None);
    };
    let document = crate::operations::protocol::document::current_document_from_log(&log)
        .map_err(|e| AppError::Internal(format!("read the current document of {did}: {e}")))?;
    // Of the DID's own context only: a public key someone copied into their document must
    // not reach a record another context holds.
    held_method(keys_ks, did, &document, relationship, |ctx| {
        ctx == Some(record.context_id.as_str())
    })
    .await
}

/// The first method `document` lists under `relationship`, under `did` itself, whose public
/// key is an active Ed25519 key record in a context `in_scope` accepts.
async fn held_method(
    keys_ks: &KeyspaceHandle,
    did: &str,
    document: &Value,
    relationship: Relationship,
    in_scope: impl Fn(Option<&str>) -> bool + Sync,
) -> Result<Option<PersonaKey>, AppError> {
    let rel = relationship.as_str();
    // Every method, by id, with its public key — a relationship may list ids or embed the
    // method itself.
    let mut methods: Vec<(String, String)> = Vec::new();
    let mut add = |m: &Value| {
        if let (Some(id), Some(pk)) = (
            m.get("id").and_then(Value::as_str),
            m.get("publicKeyMultibase").and_then(Value::as_str),
        ) {
            methods.push((id.to_string(), pk.to_string()));
        }
    };
    for m in document["verificationMethod"]
        .as_array()
        .into_iter()
        .flatten()
    {
        add(m);
    }
    for m in document[rel].as_array().into_iter().flatten() {
        add(m);
    }
    let absolute = |id: &str| {
        if id.starts_with('#') {
            format!("{did}{id}")
        } else {
            id.to_string()
        }
    };
    for entry in document[rel].as_array().into_iter().flatten() {
        let id = match entry {
            Value::String(s) => s.as_str(),
            other => match other.get("id").and_then(Value::as_str) {
                Some(s) => s,
                None => continue,
            },
        };
        let id = absolute(id);
        // Only the DID's own methods: a key named under another DID is not this persona's.
        if !id.starts_with(&format!("{did}#")) {
            continue;
        }
        let Some((_, public_key)) = methods.iter().find(|(m, _)| absolute(m) == id) else {
            continue;
        };
        if let Some(held) = held_ed25519(keys_ks, public_key, &in_scope).await? {
            return Ok(Some(PersonaKey {
                key_id: held.key_id,
                verification_method: id,
            }));
        }
    }
    Ok(None)
}

/// An active Ed25519 key record holding `public_key`, in a context `in_scope` accepts.
///
/// Compared as key bytes, not as strings: a key published with its multicodec prefix and
/// one recorded without it are the same key.
async fn held_ed25519(
    keys_ks: &KeyspaceHandle,
    public_key: &str,
    in_scope: &(dyn Fn(Option<&str>) -> bool + Sync),
) -> Result<Option<vta_sdk::keys::KeyRecord>, AppError> {
    use vta_sdk::did_key::decode_ed25519_public_key_multibase as decode;
    let Ok(wanted) = decode(public_key) else {
        return Ok(None);
    };
    for (_, value) in keys_ks.prefix_iter_raw("key:").await? {
        let Ok(record) = serde_json::from_slice::<vta_sdk::keys::KeyRecord>(&value) else {
            continue;
        };
        if record.key_type == vta_sdk::keys::KeyType::Ed25519
            && record.status == vta_sdk::keys::KeyStatus::Active
            && decode(&record.public_key).is_ok_and(|k| k == wanted)
            && in_scope(record.context_id.as_deref())
        {
            return Ok(Some(record));
        }
    }
    Ok(None)
}

/// Personas as this agent mints them, for tests across the room modules.
#[cfg(test)]
pub(crate) mod test_fixture {
    use super::*;
    use serde_json::Value;

    /// A persona: a DID, the key record it signs with, and its public key.
    pub(crate) struct Persona {
        pub did: String,
        pub key_id: String,
        pub public_key: [u8; 32],
        /// The persona's DID document, for a test resolver to serve.
        pub document: Value,
    }

    /// Mint an Ed25519 key in `context` through the real path, as an admin of everything.
    pub(crate) async fn mint_key(
        keys_ks: &KeyspaceHandle,
        internal_ks: &KeyspaceHandle,
        contexts_ks: &KeyspaceHandle,
        acl_ks: &KeyspaceHandle,
        seed: &std::sync::Arc<dyn vti_secrets::SeedStore>,
        audit: &vta_audit::SharedAuditSink,
        context: &str,
        key_id: &str,
    ) -> [u8; 32] {
        let created = crate::operations::keys::create_key(
            keys_ks,
            internal_ks,
            contexts_ks,
            seed,
            audit,
            acl_ks,
            &crate::test_support::super_admin_claims(),
            crate::operations::keys::CreateKeyParams {
                key_type: vta_keys::KeyType::Ed25519,
                internal: true,
                derivation_path: None,
                key_id: Some(key_id.into()),
                mnemonic: None,
                label: None,
                context_id: Some(context.into()),
            },
            "test",
        )
        .await
        .expect("mint a key");
        vta_sdk::did_key::decode_ed25519_public_key_multibase(&created.public_key)
            .expect("the minted key")
    }

    /// A `did:key` persona in `context`: the key record is named after nothing in
    /// particular, because the resolver matches by key, never by name.
    #[allow(clippy::too_many_arguments)]
    pub(crate) async fn did_key_persona(
        keys_ks: &KeyspaceHandle,
        internal_ks: &KeyspaceHandle,
        contexts_ks: &KeyspaceHandle,
        acl_ks: &KeyspaceHandle,
        seed: &std::sync::Arc<dyn vti_secrets::SeedStore>,
        audit: &vta_audit::SharedAuditSink,
        context: &str,
        key_id: &str,
    ) -> Persona {
        let raw = mint_key(
            keys_ks,
            internal_ks,
            contexts_ks,
            acl_ks,
            seed,
            audit,
            context,
            key_id,
        )
        .await;
        let id = vta_sdk::did_key::ed25519_multibase_pubkey(&raw);
        let did = format!("did:key:{id}");
        let vm = format!("{did}#{id}");
        Persona {
            document: serde_json::json!({
                "@context": ["https://www.w3.org/ns/did/v1"],
                "id": did,
                "verificationMethod": [{
                    "id": vm, "type": "Multikey", "controller": did, "publicKeyMultibase": id,
                }],
                "authentication": [vm],
                "assertionMethod": [vm],
            }),
            did,
            key_id: key_id.into(),
            public_key: raw,
        }
    }

    /// A `did:webvh` persona in `context`: a real published log whose document numbers its
    /// signing method `#key-1` (as the templates do), over a key minted through the real
    /// path into `context`.
    #[cfg(feature = "webvh")]
    #[allow(clippy::too_many_arguments)]
    pub(crate) async fn webvh_persona(
        keys_ks: &KeyspaceHandle,
        internal_ks: &KeyspaceHandle,
        contexts_ks: &KeyspaceHandle,
        acl_ks: &KeyspaceHandle,
        webvh_ks: &KeyspaceHandle,
        seed: &std::sync::Arc<dyn vti_secrets::SeedStore>,
        audit: &vta_audit::SharedAuditSink,
        context: &str,
        key_id: &str,
    ) -> Persona {
        use didwebvh_rs::create::{CreateDIDConfig, create_did};
        use didwebvh_rs::parameters::Parameters as WebVHParameters;

        let raw = mint_key(
            keys_ks,
            internal_ks,
            contexts_ks,
            acl_ks,
            seed,
            audit,
            context,
            key_id,
        )
        .await;
        let published = vta_sdk::did_key::ed25519_multibase_pubkey(&raw);

        // The log's own update key is separate from the persona's signing key.
        let mut update = affinidi_tdk::secrets_resolver::secrets::Secret::generate_ed25519(
            None,
            Some(&[9u8; 32]),
        );
        let update_pub = update.get_public_keymultibase().expect("update key");
        update.id = format!("did:key:{update_pub}#{update_pub}");
        let document = serde_json::json!({
            "@context": ["https://www.w3.org/ns/did/v1"],
            "id": "{DID}",
            "verificationMethod": [
                { "id": "{DID}#key-1", "type": "Multikey", "controller": "{DID}",
                  "publicKeyMultibase": published },
            ],
            "authentication": ["{DID}#key-1"],
            "assertionMethod": ["{DID}#key-1"],
        });
        let cfg = CreateDIDConfig::builder()
            .address(format!(
                "https://example.invalid/{context}/{key_id}/did.jsonl"
            ))
            .authorization_key(update)
            .did_document(document)
            .parameters(WebVHParameters {
                update_keys: Some(std::sync::Arc::new(vec![update_pub.into()])),
                ..Default::default()
            })
            .build()
            .expect("create config");
        let result = create_did(cfg).await.expect("create did");
        let did = result.did().to_string();
        let log = serde_json::to_string(result.log_entry()).expect("serialise log");
        crate::webvh_store::store_did_log(webvh_ks, &did, &log)
            .await
            .expect("store log");
        let now = chrono::Utc::now();
        crate::webvh_store::store_did(
            webvh_ks,
            &vta_sdk::webvh::WebvhDidRecord {
                did: did.clone(),
                server_id: "serverless".into(),
                mnemonic: String::new(),
                scid: "irrelevant".into(),
                context_id: context.into(),
                portable: false,
                log_entry_count: 1,
                pre_rotation_count: 0,
                next_fragment_id: 2,
                created_at: now,
                updated_at: now,
            },
        )
        .await
        .expect("store did record");
        let document = crate::operations::protocol::document::current_document_from_log(&log)
            .expect("the published document");
        Persona {
            did,
            key_id: key_id.into(),
            public_key: raw,
            document,
        }
    }
}

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

    struct Fixture {
        ts: crate::test_support::TestStore,
        seed: std::sync::Arc<dyn vti_secrets::SeedStore>,
    }

    impl Fixture {
        async fn new() -> Self {
            let ts = crate::test_support::open_test_store().await;
            for (id, name) in [("alice", "Alice"), ("bob", "Bob")] {
                crate::contexts::create_context(&ts.contexts_ks, id, name)
                    .await
                    .expect("create context");
            }
            Self {
                ts,
                seed: std::sync::Arc::new(crate::test_support::TestSeedStore(vec![7u8; 32])),
            }
        }

        fn stores(&self) -> PersonaStores<'_> {
            PersonaStores {
                keys_ks: &self.ts.keys_ks,
                #[cfg(feature = "webvh")]
                webvh_ks: &self.ts.webvh_ks,
            }
        }

        async fn did_key(&self, context: &str, key_id: &str) -> Persona {
            did_key_persona(
                &self.ts.keys_ks,
                &self.ts.internal_ks,
                &self.ts.contexts_ks,
                &self.ts.acl_ks,
                &self.seed,
                &self.ts.audit,
                context,
                key_id,
            )
            .await
        }

        #[cfg(feature = "webvh")]
        async fn webvh(&self, context: &str, key_id: &str) -> Persona {
            webvh_persona(
                &self.ts.keys_ks,
                &self.ts.internal_ks,
                &self.ts.contexts_ks,
                &self.ts.acl_ks,
                &self.ts.webvh_ks,
                &self.seed,
                &self.ts.audit,
                context,
                key_id,
            )
            .await
        }
    }

    /// A `did:webvh` minted in the caller's context is a persona the caller may act as, and
    /// its key is the one its own log publishes for `assertionMethod`.
    #[cfg(feature = "webvh")]
    #[tokio::test]
    async fn a_webvh_persona_in_the_callers_context_resolves() {
        let f = Fixture::new().await;
        let alice = f.webvh("alice", "alice-persona").await;
        let caller = crate::test_support::admin_claims_for_context("alice");
        let key = persona_signing_key(f.stores(), &caller, &alice.did)
            .await
            .unwrap()
            .expect("alice's persona");
        assert_eq!(key.key_id, alice.key_id);
        assert_eq!(key.verification_method, format!("{}#key-1", alice.did));
    }

    /// Someone else's persona and a DID nobody holds answer alike, so the answer does not
    /// say which DIDs this agent holds for other people.
    #[cfg(feature = "webvh")]
    #[tokio::test]
    async fn another_contexts_persona_reads_like_an_unknown_one() {
        let f = Fixture::new().await;
        let bob_webvh = f.webvh("bob", "bob-persona").await;
        let bob_key = f.did_key("bob", "bob-did-key").await;
        let caller = crate::test_support::admin_claims_for_context("alice");
        for did in [
            bob_webvh.did.as_str(),
            bob_key.did.as_str(),
            "did:webvh:QmNobody:nowhere.example",
            "did:key:z6MkhaXgBZDvotDkL5257faiztiGiC2QtKLGpbnnEGta2doK",
        ] {
            assert_eq!(
                persona_signing_key(f.stores(), &caller, did).await.unwrap(),
                None,
                "{did}"
            );
        }
    }

    /// A held `did:key` is a persona in its own context and nowhere else.
    #[tokio::test]
    async fn a_held_did_key_is_a_persona_only_in_its_context() {
        let f = Fixture::new().await;
        let alice = f.did_key("alice", "alice-key").await;
        let id = alice.did.strip_prefix("did:key:").unwrap();
        let key = persona_signing_key(
            f.stores(),
            &crate::test_support::admin_claims_for_context("alice"),
            &alice.did,
        )
        .await
        .unwrap()
        .expect("held in alice");
        assert_eq!(key.key_id, "alice-key");
        assert_eq!(key.verification_method, format!("{}#{id}", alice.did));
        assert_eq!(
            vta_sdk::did_key::ed25519_multibase_pubkey(&alice.public_key),
            id
        );

        assert_eq!(
            persona_signing_key(
                f.stores(),
                &crate::test_support::admin_claims_for_context("bob"),
                &alice.did,
            )
            .await
            .unwrap(),
            None
        );
    }

    /// An interface client's `did:key` — a key that lives in the client, not here — is no
    /// persona, whoever asks.
    #[tokio::test]
    async fn a_client_held_did_key_is_not_a_persona() {
        let f = Fixture::new().await;
        let caller = crate::test_support::admin_claims_for_context("alice");
        assert_eq!(
            persona_signing_key(f.stores(), &caller, &caller.did)
                .await
                .unwrap(),
            None
        );
        assert_eq!(
            persona_signing_key(
                f.stores(),
                &crate::test_support::super_admin_claims(),
                &caller.did
            )
            .await
            .unwrap(),
            None
        );
    }

    /// A DID URL is not a DID: naming a persona by `did#fragment` is not naming it.
    #[tokio::test]
    async fn a_did_url_is_not_a_persona() {
        let f = Fixture::new().await;
        let alice = f.did_key("alice", "alice-key-2").await;
        let id = alice.did.strip_prefix("did:key:").unwrap();
        assert_eq!(
            persona_signing_key(
                f.stores(),
                &crate::test_support::admin_claims_for_context("alice"),
                &format!("{}#{id}", alice.did),
            )
            .await
            .unwrap(),
            None
        );
    }
}