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