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).
24pub(crate) fn 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", ...).
53pub(crate) fn 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/// Python's `str.isspace`: Unicode White_Space plus the four information
184/// separators U+001C to U+001F (which Python counts as space and Rust does
185/// not).
186pub fn py_space(c: char) -> bool {
187    c.is_whitespace() || ('\u{1c}'..='\u{1f}').contains(&c)
188}
189
190/// The DID a trusted root names, exactly as the Python reference reads it:
191/// a full DID is kept as it is (a did:web must parse); a bare domain
192/// ("yourcompany.com", or "yourcompany.com:8443" with a port) becomes its
193/// did:web identifier ("did:web:yourcompany.com%3A8443"). Anything else, such
194/// as an IP literal, a non-punycode international name, a trailing dot, a bad
195/// port, a URL or a path, is refused.
196pub fn normalize_root(value: &str) -> Result<String> {
197    if value.is_empty() || value.trim_matches(py_space) != value {
198        return Err(bad("a trusted root is a DID or a domain name"));
199    }
200    if value.starts_with("did:") {
201        let mut parts = value.splitn(3, ':');
202        let (_, method, id) = (parts.next(), parts.next(), parts.next());
203        if method.is_none_or(|m| m.is_empty())
204            || id.is_none_or(|i| i.is_empty())
205            || value.chars().any(py_space)
206        {
207            return Err(bad("not a DID"));
208        }
209        if value.starts_with("did:web:") {
210            parse_did_web(value)?;
211        }
212        if value.starts_with(crate::did_webvh::PREFIX) {
213            // A did:webvh root is that exact DID: its SCID pins one log, so
214            // it is never widened to the domain or to the did:web DID there.
215            crate::did_webvh::parse(value).map_err(|e| bad(e.text))?;
216        }
217        return Ok(value.to_string());
218    }
219    let did = format!("did:web:{}", value.replace(':', "%3A"));
220    parse_did_web(&did)
221        .map_err(|_| bad("not a DID or a domain name (for example yourcompany.com)"))?;
222    Ok(did)
223}
224
225#[cfg(test)]
226mod tests {
227    use super::*;
228
229    #[test]
230    fn shorthand_matches_the_reference_rules() {
231        for (root, want) in [
232            ("example.com", Some("did:web:example.com")),
233            ("Example.com", Some("did:web:Example.com")),
234            ("example.com:8443", Some("did:web:example.com%3A8443")),
235            (
236                "xn--bcher-kva.example",
237                Some("did:web:xn--bcher-kva.example"),
238            ),
239            (
240                "did:web:example.com:users",
241                Some("did:web:example.com:users"),
242            ),
243            ("did:example:123", Some("did:example:123")),
244            ("example.com.", None),
245            ("bücher.example", None),
246            ("127.0.0.1", None),
247            ("localhost", Some("did:web:localhost")),
248            ("[::1]", None),
249            ("example.com/users", None),
250            ("https://example.com", None),
251            ("example.com:0", None),
252            ("example.com:65536", None),
253            ("example.com:08443", None),
254            ("example.com:users", None),
255            ("example.com:8443:users", None),
256            ("-example.com", None),
257            (" example.com", None),
258            ("", None),
259            ("did:web:", None),
260            ("did::x", None),
261            ("did:web:example.com:..", None),
262            ("did:web:example.com:%2e%2e", None),
263            ("did:web:example.com:us%20ers", None),
264            ("0x7f000001", None),
265            ("did:web:例え.jp", None),
266            (
267                "did:webvh:QmUy89VrfryQ254CeHZzQfmcKqByPoKNGqYykP3SeXuegQ:example.com",
268                Some("did:webvh:QmUy89VrfryQ254CeHZzQfmcKqByPoKNGqYykP3SeXuegQ:example.com"),
269            ),
270            ("did:webvh:{SCID}:example.com", None),
271            (
272                "did:webvh:QmUy89VrfryQ254CeHZzQfmcKqByPoKNGqYykP3SeXuegQ:127.0.0.1",
273                None,
274            ),
275            (
276                "did:webvh:QmUy89VrfryQ254CeHZzQfmcKqByPoKNGqYykP3SeXuegQ:example.com#key-1",
277                None,
278            ),
279        ] {
280            assert_eq!(normalize_root(root).ok().as_deref(), want, "{root:?}");
281        }
282    }
283}