Skip to main content

acl_core/
did.rs

1//! DID resolution (spec §22): turn `did:key` AIDs into verifying keys
2//! without any network, and construct `did:web` resolution URLs.
3//!
4//! `did:key:z<base58btc(0xed 0x01 || ed25519_pubkey)>` per the did:key
5//! spec (W3C CC work). `did:web` URL construction follows did:web §2.2;
6//! actual fetching is the caller's transport concern.
7
8use crate::AclError;
9use bs58;
10use ed25519_dalek::VerifyingKey;
11
12/// ED25519 multicodec prefix: 0xed 0x01
13const ED25519_MULTICODEC: [u8; 2] = [0xed, 0x01];
14
15/// Parse a `did:key:z...` AID into an Ed25519 verifying key.
16pub fn did_key_to_verifying_key(did: &str) -> Result<VerifyingKey, AclError> {
17    let b58 = did
18        .strip_prefix("did:key:z")
19        .ok_or_else(|| AclError::BadKey)?;
20    let decoded = bs58::decode(b58)
21        .into_vec()
22        .map_err(|_| AclError::BadKey)?;
23    if decoded.len() != 34 || decoded[..2] != ED25519_MULTICODEC {
24        return Err(AclError::BadKey);
25    }
26    let mut pk = [0u8; 32];
27    pk.copy_from_slice(&decoded[2..]);
28    VerifyingKey::from_bytes(&pk).map_err(|_| AclError::BadKey)
29}
30
31/// Encode an Ed25519 verifying key as a `did:key` AID.
32pub fn verifying_key_to_did_key(vk: &VerifyingKey) -> String {
33    let mut payload = Vec::with_capacity(34);
34    payload.extend_from_slice(&ED25519_MULTICODEC);
35    payload.extend_from_slice(&vk.to_bytes());
36    format!("did:key:z{}", bs58::encode(payload).into_string())
37}
38
39/// Build the did:web resolution URL (did:web §2.2):
40///   did:web:example.com            → https://example.com/.well-known/did.json
41///   did:web:example.com:path:to    → https://example.com/path/to/did.json
42/// Returns the URL; fetching is the caller's job.
43pub fn did_web_url(did: &str) -> Result<String, AclError> {
44    let rest = did
45        .strip_prefix("did:web:")
46        .ok_or(AclError::BadKey)?;
47    if rest.is_empty() {
48        return Err(AclError::BadKey);
49    }
50    // path components after the first segment are %-encoded colons in did:web
51    let mut segments = rest.split(':');
52    let host = segments
53        .next()
54        .ok_or(AclError::BadKey)?
55        .replace("%3A", ":");
56    let path_parts: Vec<&str> = segments.collect();
57    if path_parts.is_empty() {
58        Ok(format!("https://{host}/.well-known/did.json"))
59    } else {
60        Ok(format!("https://{host}/{}:did.json", path_parts.join("/")))
61    }
62}
63
64#[cfg(test)]
65mod tests {
66    use super::*;
67    use crate::{Aid, Body, Envelope, Performative};
68    use ed25519_dalek::SigningKey;
69    use rand::Rng;
70
71    fn key() -> SigningKey {
72        let mut s = [0u8; 32];
73        rand::rng().fill_bytes(&mut s);
74        SigningKey::from_bytes(&s)
75    }
76
77    #[test]
78    fn did_key_roundtrip() {
79        let k = key();
80        let vk = k.verifying_key();
81        let did = verifying_key_to_did_key(&vk);
82        assert!(did.starts_with("did:key:z"));
83        // length varies with leading zero bytes; the roundtrip is the check
84        let resolved = did_key_to_verifying_key(&did).expect("resolve");
85        assert_eq!(resolved.to_bytes(), vk.to_bytes());
86    }
87
88    #[test]
89    fn known_vector_shape() {
90        // structural check: decode a hand-built payload
91        let mut payload = ED25519_MULTICODEC.to_vec();
92        payload.extend_from_slice(&[42u8; 32]);
93        let did = format!("did:key:z{}", bs58::encode(&payload).into_string());
94        let vk = did_key_to_verifying_key(&did).expect("resolve");
95        assert_eq!(vk.to_bytes(), [42u8; 32]);
96    }
97
98    #[test]
99    fn rejects_malformed() {
100        // not a did:key
101        assert!(did_key_to_verifying_key("did:web:x").is_err());
102        assert!(did_key_to_verifying_key("did:key:znotbase58!!!").is_err());
103        // wrong length
104        assert!(did_key_to_verifying_key("did:key:z1111").is_err());
105        // wrong multicodec (0x00 0x01 = not ed25519)
106        let mut payload = vec![0x00, 0x01];
107        payload.extend_from_slice(&[1u8; 32]);
108        let did = format!("did:key:z{}", bs58::encode(&payload).into_string());
109        assert!(did_key_to_verifying_key(&did).is_err());
110    }
111
112    #[test]
113    fn envelope_verify_via_did_key_aid() {
114        // the full loop: agent identified by did:key, envelope verified
115        // with ONLY the from field — no separate key exchange needed
116        let k = key();
117        let did = verifying_key_to_did_key(&k.verifying_key());
118        let mut env = Envelope::new(
119            Aid::new(&did),
120            Aid::new("did:key:zplaceholder"),
121            Performative::Inform,
122            Body::Text { text: "did works".into() },
123        );
124        env.sign(&k).unwrap();
125        let vk = did_key_to_verifying_key(&env.from.0).expect("resolve from AID");
126        assert!(env.verify(&vk).unwrap());
127    }
128
129    #[test]
130    fn did_web_urls() {
131        assert_eq!(
132            did_web_url("did:web:example.com").unwrap(),
133            "https://example.com/.well-known/did.json"
134        );
135        assert_eq!(
136            did_web_url("did:web:example.com:users:alice").unwrap(),
137            "https://example.com/users/alice:did.json"
138        );
139        // encoded port
140        assert_eq!(
141            did_web_url("did:web:example.com%3A8443").unwrap(),
142            "https://example.com:8443/.well-known/did.json"
143        );
144        assert!(did_web_url("did:key:z123").is_err());
145        assert!(did_web_url("did:web:").is_err());
146    }
147}