Skip to main content

vgi_core/
did.rs

1//! DID-document key extraction.
2//!
3//! Signers are declared as DIDs; their signing keys are resolved from the
4//! `assertionMethod` relationship of their DID documents at verification time,
5//! so key rotation never requires touching the repository.
6
7use serde_json::Value;
8
9/// Multicodec prefix for an Ed25519 public key in `publicKeyMultibase`.
10pub const ED25519_MULTICODEC_PREFIX: [u8; 2] = [0xED, 0x01];
11
12/// Multicodec prefix for a P-256 public key in `publicKeyMultibase`
13/// (`p256-pub`, `0x1200` as a varint), carried as a 33-byte compressed SEC1
14/// point.
15pub const P256_MULTICODEC_PREFIX: [u8; 2] = [0x80, 0x24];
16
17/// A signing key a DID document publishes, in the encoding the multicodec
18/// names. Compared byte for byte against the key a signature embeds.
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
20pub enum PublishedKey {
21    /// An Ed25519 public key.
22    Ed25519([u8; 32]),
23    /// A P-256 public key as a compressed SEC1 point.
24    P256([u8; 33]),
25}
26
27impl PublishedKey {
28    /// The raw key bytes.
29    #[must_use]
30    pub fn as_bytes(&self) -> &[u8] {
31        match self {
32            Self::Ed25519(key) => key,
33            Self::P256(key) => key,
34        }
35    }
36}
37
38impl From<[u8; 32]> for PublishedKey {
39    fn from(key: [u8; 32]) -> Self {
40        Self::Ed25519(key)
41    }
42}
43
44/// Extract the Ed25519 public keys a DID document authorizes for signing —
45/// [`signing_keys_from_doc`] restricted to Ed25519, for the callers that sign
46/// with an Ed25519 key.
47pub fn ed25519_signing_keys_from_doc(doc: &Value) -> Vec<[u8; 32]> {
48    signing_keys_from_doc(doc)
49        .into_iter()
50        .filter_map(|key| match key {
51            PublishedKey::Ed25519(key) => Some(key),
52            PublishedKey::P256(_) => None,
53        })
54        .collect()
55}
56
57/// Extract the public keys a DID document authorizes for signing: the methods
58/// its `assertionMethod` relationship lists (`publicKeyMultibase`, multicodec
59/// `0xED01` for Ed25519 or `0x1200` for compressed P-256).
60///
61/// A commit signature is an assertion made as the DID, so a key the document
62/// merely *contains* is not enough: a key agreement, recovery or custodian key
63/// listed in `verificationMethod` but not under `assertionMethod` was never
64/// authorized to sign as the DID, and must not verify commits as it.
65///
66/// An entry is either a reference to one of the document's own
67/// `verificationMethod`s — absolute (`did:…#key-0`) or relative (`#key-0`) —
68/// or a method embedded in the relationship. A reference to a method the
69/// document does not contain is not followed. A method whose `controller`
70/// names a different DID is skipped: its key is someone else's to use.
71pub fn signing_keys_from_doc(doc: &Value) -> Vec<PublishedKey> {
72    let did = doc.get("id").and_then(Value::as_str).unwrap_or_default();
73    let absolute = |id: &str| {
74        if id.starts_with('#') {
75            format!("{did}{id}")
76        } else {
77            id.to_string()
78        }
79    };
80    let own_key = |method: &Value| -> Option<PublishedKey> {
81        if let Some(controller) = method.get("controller")
82            && controller.as_str() != Some(did)
83        {
84            return None;
85        }
86        let encoded = method.get("publicKeyMultibase")?.as_str()?;
87        let (_base, bytes) = multibase::decode(encoded).ok()?;
88        if let Some(raw) = bytes.strip_prefix(&ED25519_MULTICODEC_PREFIX) {
89            return <[u8; 32]>::try_from(raw).ok().map(PublishedKey::Ed25519);
90        }
91        let raw = bytes.strip_prefix(&P256_MULTICODEC_PREFIX)?;
92        let point = <[u8; 33]>::try_from(raw).ok()?;
93        matches!(point[0], 0x02 | 0x03).then_some(PublishedKey::P256(point))
94    };
95    let methods: Vec<(String, &Value)> = doc
96        .get("verificationMethod")
97        .and_then(Value::as_array)
98        .into_iter()
99        .flatten()
100        .filter_map(|method| Some((absolute(method.get("id")?.as_str()?), method)))
101        .collect();
102
103    let mut keys: Vec<PublishedKey> = Vec::new();
104    for entry in doc
105        .get("assertionMethod")
106        .and_then(Value::as_array)
107        .into_iter()
108        .flatten()
109    {
110        let key = match entry {
111            Value::String(reference) => {
112                let id = absolute(reference);
113                methods
114                    .iter()
115                    .find(|(method_id, _)| *method_id == id)
116                    .and_then(|(_, method)| own_key(method))
117            }
118            embedded => own_key(embedded),
119        };
120        if let Some(key) = key
121            && !keys.contains(&key)
122        {
123            keys.push(key);
124        }
125    }
126    keys
127}
128
129#[cfg(test)]
130mod tests {
131    use super::*;
132    use serde_json::json;
133
134    const DID: &str = "did:example:signer";
135
136    fn encoded(seed: u8) -> ([u8; 32], String) {
137        let public = ed25519_dalek::SigningKey::from_bytes(&[seed; 32])
138            .verifying_key()
139            .to_bytes();
140        let mut multicodec = ED25519_MULTICODEC_PREFIX.to_vec();
141        multicodec.extend_from_slice(&public);
142        (
143            public,
144            multibase::encode(multibase::Base::Base58Btc, &multicodec),
145        )
146    }
147
148    #[test]
149    fn assertion_method_keys_are_extracted() {
150        let (public, key) = encoded(7);
151        let doc = json!({
152            "id": DID,
153            "verificationMethod": [
154                { "id": format!("{DID}#key-0"), "controller": DID, "publicKeyMultibase": key },
155                { "id": format!("{DID}#key-x"), "publicKeyMultibase": "zInvalid!" },
156                { "id": format!("{DID}#key-jwk") }
157            ],
158            "assertionMethod": [
159                format!("{DID}#key-0"), format!("{DID}#key-x"), format!("{DID}#key-jwk")
160            ]
161        });
162        assert_eq!(ed25519_signing_keys_from_doc(&doc), vec![public]);
163    }
164
165    #[test]
166    fn relative_references_and_embedded_methods_count() {
167        let (relative, relative_key) = encoded(1);
168        let (embedded, embedded_key) = encoded(2);
169        let doc = json!({
170            "id": DID,
171            "verificationMethod": [
172                { "id": "#key-0", "controller": DID, "publicKeyMultibase": relative_key }
173            ],
174            "assertionMethod": [
175                "#key-0",
176                { "id": "#key-1", "controller": DID, "publicKeyMultibase": embedded_key }
177            ]
178        });
179        assert_eq!(
180            ed25519_signing_keys_from_doc(&doc),
181            vec![relative, embedded]
182        );
183    }
184
185    /// VGI-02: an Ed25519 key the document lists for some other purpose was
186    /// never authorized to sign as the DID.
187    #[test]
188    fn a_key_not_listed_under_assertion_method_is_not_a_signing_key() {
189        let (signing, signing_key) = encoded(1);
190        let (_, other_key) = encoded(2);
191        let doc = json!({
192            "id": DID,
193            "verificationMethod": [
194                { "id": format!("{DID}#key-0"), "controller": DID, "publicKeyMultibase": signing_key },
195                { "id": format!("{DID}#recovery"), "controller": DID, "publicKeyMultibase": other_key }
196            ],
197            "authentication": [format!("{DID}#recovery")],
198            "capabilityInvocation": [format!("{DID}#recovery")],
199            "assertionMethod": [format!("{DID}#key-0")]
200        });
201        assert_eq!(ed25519_signing_keys_from_doc(&doc), vec![signing]);
202    }
203
204    #[test]
205    fn a_document_without_assertion_method_has_no_signing_keys() {
206        let (_, key) = encoded(1);
207        let doc = json!({
208            "id": DID,
209            "verificationMethod": [
210                { "id": format!("{DID}#key-0"), "controller": DID, "publicKeyMultibase": key }
211            ],
212            "authentication": [format!("{DID}#key-0")]
213        });
214        assert!(ed25519_signing_keys_from_doc(&doc).is_empty());
215    }
216
217    #[test]
218    fn a_method_controlled_by_another_did_is_skipped() {
219        let (_, key) = encoded(1);
220        let doc = json!({
221            "id": DID,
222            "verificationMethod": [{
223                "id": format!("{DID}#key-0"),
224                "controller": "did:example:someone-else",
225                "publicKeyMultibase": key
226            }],
227            "assertionMethod": [
228                format!("{DID}#key-0"),
229                { "id": "#key-1", "controller": "did:example:someone-else", "publicKeyMultibase": key }
230            ]
231        });
232        assert!(ed25519_signing_keys_from_doc(&doc).is_empty());
233    }
234
235    fn p256_encoded(prefix: u8) -> ([u8; 33], String) {
236        let mut point = [0x5A; 33];
237        point[0] = prefix;
238        let mut multicodec = P256_MULTICODEC_PREFIX.to_vec();
239        multicodec.extend_from_slice(&point);
240        (
241            point,
242            multibase::encode(multibase::Base::Base58Btc, &multicodec),
243        )
244    }
245
246    #[test]
247    fn compressed_p256_keys_are_extracted_alongside_ed25519() {
248        let (ed25519, ed25519_key) = encoded(1);
249        let (p256, p256_key) = p256_encoded(0x03);
250        let (_, uncompressed_tag) = p256_encoded(0x04);
251        let doc = json!({
252            "id": DID,
253            "assertionMethod": [
254                { "id": "#key-0", "controller": DID, "publicKeyMultibase": ed25519_key },
255                { "id": "#key-1", "controller": DID, "publicKeyMultibase": p256_key },
256                { "id": "#key-2", "controller": DID, "publicKeyMultibase": uncompressed_tag }
257            ]
258        });
259        assert_eq!(
260            signing_keys_from_doc(&doc),
261            vec![PublishedKey::Ed25519(ed25519), PublishedKey::P256(p256)]
262        );
263        assert_eq!(ed25519_signing_keys_from_doc(&doc), vec![ed25519]);
264    }
265
266    #[test]
267    fn a_reference_to_a_method_the_document_lacks_is_not_followed() {
268        let doc = json!({ "id": DID, "assertionMethod": ["did:example:other#key-0"] });
269        assert!(ed25519_signing_keys_from_doc(&doc).is_empty());
270    }
271}