Skip to main content

vouch_core/
did_web.rs

1//! did:web identifiers and trusted-root shorthand, parsed strictly and the same
2//! way as the Python reference (`vouch.did_web.parse_did_web` and
3//! `vouch.trusted_roots.normalize_root`).
4//!
5//! The core never fetches a DID document; these rules only decide whether an
6//! identifier is well formed and which DID a trusted root names.
7
8use crate::error::{CoreError, Result};
9
10/// A did:web identifier split into its host, optional port and path segments.
11#[derive(Debug, Clone, PartialEq, Eq)]
12pub struct DidWeb {
13    pub host: String,
14    pub port: Option<u16>,
15    pub segments: Vec<String>,
16}
17
18fn bad(msg: &str) -> CoreError {
19    CoreError::InvalidDid(msg.to_string())
20}
21
22/// One LDH label: 1 to 63 ASCII letters, digits or hyphens, with no leading or
23/// trailing hyphen (punycode "xn--" labels are LDH).
24fn is_ldh_label(label: &str) -> bool {
25    let b = label.as_bytes();
26    !b.is_empty()
27        && b.len() <= 63
28        && b.iter().all(|c| c.is_ascii_alphanumeric() || *c == b'-')
29        && b[0] != b'-'
30        && b[b.len() - 1] != b'-'
31}
32
33/// A number the way C's `strtoul(.., 0)` reads one inside `inet_aton`: "0x"
34/// hex, a leading "0" octal, else decimal. None when it is not a number.
35fn c_number(part: &str) -> Option<u64> {
36    let (digits, radix) =
37        if let Some(h) = part.strip_prefix("0x").or_else(|| part.strip_prefix("0X")) {
38            (h, 16)
39        } else if part.len() > 1 && part.starts_with('0') {
40            (&part[1..], 8)
41        } else {
42            (part, 10)
43        };
44    if digits.is_empty() {
45        // "0x" alone is not a number; "0" is handled as decimal above.
46        return None;
47    }
48    u64::from_str_radix(digits, radix).ok()
49}
50
51/// True when `host` is an IPv4 address in any form `inet_aton` accepts
52/// ("127.0.0.1", "127.1", "0x7f000001", "017700000001", ...).
53fn is_inet_aton_address(host: &str) -> bool {
54    let parts: Vec<&str> = host.split('.').collect();
55    if parts.is_empty() || parts.len() > 4 {
56        return false;
57    }
58    let mut values = Vec::with_capacity(parts.len());
59    for p in &parts {
60        match c_number(p) {
61            Some(v) => values.push(v),
62            None => return false,
63        }
64    }
65    let (last, head) = values.split_last().expect("non-empty");
66    if head.iter().any(|v| *v > 255) {
67        return false;
68    }
69    let bits = 8 * (5 - parts.len() as u32);
70    *last < (1u64 << bits)
71}
72
73fn hex_val(c: u8) -> Option<u8> {
74    (c as char).to_digit(16).map(|d| d as u8)
75}
76
77/// Split a did:web identifier into host, port and path segments, strictly:
78///
79/// - the host is one or more LDH labels, at most 253 characters, with no empty
80///   label (so no trailing dot) and no non-ASCII character;
81/// - the host is not an IP address in any form;
82/// - the only percent-encoding allowed in the host part is "%3A" before a port,
83///   and the port is 1 to 65535 with no leading zero;
84/// - every path segment is non-empty, is not "." or "..", and holds no "/",
85///   "?", "#", "\\", "%", control character or space, raw or percent-encoded.
86pub fn parse_did_web(did: &str) -> Result<DidWeb> {
87    let rest = did
88        .strip_prefix("did:web:")
89        .ok_or_else(|| bad("not a did:web identifier"))?;
90    let mut parts = rest.split(':');
91    let mut host_part = parts.next().unwrap_or("");
92    let segments: Vec<&str> = parts.collect();
93
94    let mut port = None;
95    if host_part.contains('%') {
96        let lower = host_part.to_ascii_lowercase();
97        let idx = lower
98            .find("%3a")
99            .ok_or_else(|| bad("a did:web host may only percent-encode the colon before a port"))?;
100        let (h, p) = (&host_part[..idx], &host_part[idx + 3..]);
101        if h.contains('%') || p.contains('%') {
102            return Err(bad(
103                "a did:web host may only percent-encode the colon before a port",
104            ));
105        }
106        let pb = p.as_bytes();
107        if pb.is_empty() || pb.len() > 5 || pb[0] == b'0' || !pb.iter().all(|c| c.is_ascii_digit())
108        {
109            return Err(bad("a did:web port must be 1 to 65535"));
110        }
111        let n: u32 = p
112            .parse()
113            .map_err(|_| bad("a did:web port must be 1 to 65535"))?;
114        if n > 65535 {
115            return Err(bad("a did:web port must be 1 to 65535"));
116        }
117        port = Some(n as u16);
118        host_part = h;
119    }
120    let host = host_part;
121    if host.is_empty() || host.len() > 253 {
122        return Err(bad("a did:web host must be 1 to 253 characters"));
123    }
124    let labels: Vec<&str> = host.split('.').collect();
125    if !labels.iter().all(|l| is_ldh_label(l)) {
126        return Err(bad(
127            "a did:web host must be letters, digits, hyphens and dots",
128        ));
129    }
130    if labels
131        .last()
132        .is_some_and(|l| l.bytes().all(|c| c.is_ascii_digit()))
133        || is_inet_aton_address(host)
134    {
135        return Err(bad(
136            "a did:web host must be a domain name, not an IP address",
137        ));
138    }
139
140    let mut out = Vec::with_capacity(segments.len());
141    for segment in segments {
142        let sb = segment.as_bytes();
143        let allowed = |c: u8| c.is_ascii_alphanumeric() || b"._~!$&'()*+,;=@%-".contains(&c);
144        if sb.is_empty() || !sb.iter().all(|c| allowed(*c)) {
145            return Err(bad(
146                "a did:web path segment is empty or holds a forbidden character",
147            ));
148        }
149        // Decode %XX escapes; a '%' that does not start one is refused.
150        let mut decoded: Vec<u32> = Vec::with_capacity(sb.len());
151        let mut i = 0;
152        while i < sb.len() {
153            if sb[i] == b'%' {
154                match (
155                    sb.get(i + 1).and_then(|c| hex_val(*c)),
156                    sb.get(i + 2).and_then(|c| hex_val(*c)),
157                ) {
158                    (Some(a), Some(b)) => {
159                        decoded.push(u32::from(a * 16 + b));
160                        i += 3;
161                    }
162                    _ => return Err(bad("a did:web path segment holds a broken percent-escape")),
163                }
164            } else {
165                decoded.push(u32::from(sb[i]));
166                i += 1;
167            }
168        }
169        let forbidden = |c: u32| c <= 0x20 || c == 0x7f || "/\\?#%".contains(char::from(c as u8));
170        let is_dots = decoded == [u32::from(b'.')] || decoded == [u32::from(b'.'), u32::from(b'.')];
171        if is_dots || decoded.iter().any(|c| *c < 0x80 && forbidden(*c)) {
172            return Err(bad("a did:web path segment holds a forbidden character"));
173        }
174        out.push(segment.to_string());
175    }
176    Ok(DidWeb {
177        host: host.to_string(),
178        port,
179        segments: out,
180    })
181}
182
183/// The DID a trusted root names, exactly as the Python reference reads it:
184/// a full DID is kept as it is (a did:web must parse); a bare domain
185/// ("yourcompany.com", or "yourcompany.com:8443" with a port) becomes its
186/// did:web identifier ("did:web:yourcompany.com%3A8443"). Anything else, such
187/// as an IP literal, a non-punycode international name, a trailing dot, a bad
188/// port, a URL or a path, is refused.
189pub fn normalize_root(value: &str) -> Result<String> {
190    if value.is_empty() || value.trim() != value {
191        return Err(bad("a trusted root is a DID or a domain name"));
192    }
193    if value.starts_with("did:") {
194        let mut parts = value.splitn(3, ':');
195        let (_, method, id) = (parts.next(), parts.next(), parts.next());
196        if method.is_none_or(|m| m.is_empty())
197            || id.is_none_or(|i| i.is_empty())
198            || value.chars().any(char::is_whitespace)
199        {
200            return Err(bad("not a DID"));
201        }
202        if value.starts_with("did:web:") {
203            parse_did_web(value)?;
204        }
205        return Ok(value.to_string());
206    }
207    let did = format!("did:web:{}", value.replace(':', "%3A"));
208    parse_did_web(&did)
209        .map_err(|_| bad("not a DID or a domain name (for example yourcompany.com)"))?;
210    Ok(did)
211}
212
213#[cfg(test)]
214mod tests {
215    use super::*;
216
217    #[test]
218    fn shorthand_matches_the_reference_rules() {
219        for (root, want) in [
220            ("example.com", Some("did:web:example.com")),
221            ("Example.com", Some("did:web:Example.com")),
222            ("example.com:8443", Some("did:web:example.com%3A8443")),
223            (
224                "xn--bcher-kva.example",
225                Some("did:web:xn--bcher-kva.example"),
226            ),
227            (
228                "did:web:example.com:users",
229                Some("did:web:example.com:users"),
230            ),
231            ("did:example:123", Some("did:example:123")),
232            ("example.com.", None),
233            ("bücher.example", None),
234            ("127.0.0.1", None),
235            ("localhost", Some("did:web:localhost")),
236            ("[::1]", None),
237            ("example.com/users", None),
238            ("https://example.com", None),
239            ("example.com:0", None),
240            ("example.com:65536", None),
241            ("example.com:08443", None),
242            ("example.com:users", None),
243            ("example.com:8443:users", None),
244            ("-example.com", None),
245            (" example.com", None),
246            ("", None),
247            ("did:web:", None),
248            ("did::x", None),
249            ("did:web:example.com:..", None),
250            ("did:web:example.com:%2e%2e", None),
251            ("did:web:example.com:us%20ers", None),
252            ("0x7f000001", None),
253            ("did:web:例え.jp", None),
254        ] {
255            assert_eq!(normalize_root(root).ok().as_deref(), want, "{root:?}");
256        }
257    }
258}