did-hosting-common 0.10.1

DID Hosting Common, Common methods and structs related to WebVH Content
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
//! Domain-name normalisation.
//!
//! Per `docs/multi-domain-spec.md` §3 row "Domain name normalization":
//! every domain name reaching the system gets lowercase + IDNA-
//! normalised before storage / comparison. Inputs that aren't already
//! in canonical form are **rejected with 400**, with the canonical form
//! quoted in the error message so the caller can retry cleanly.
//!
//! Path-prefix domains (`example.com/webvh-a`) are first-class per
//! §3 — the host part is IDNA-normalised, the path part is lowercase-
//! validated.
//!
//! ## Why reject rather than silently rewrite
//!
//! Silently rewriting `Example.com` to `example.com` lets two
//! ostensibly-different stored names collide and creates spooky-action-
//! at-a-distance for audit logs. Rejecting with the canonical form in
//! the error keeps the input → storage mapping bijective: what the
//! caller sent is what got stored.

use crate::server::error::AppError;

/// Maximum sensible domain-name length for storage keys / error
/// messages. Stops a 1MB upload from being echoed back in a 400.
const MAX_LEN: usize = 253;

/// Normalise a domain identifier.
///
/// Behaviour:
/// - If `input` is **already** in canonical form, returns `Ok(canonical)`
///   (which equals `input`).
/// - If `input` parses cleanly but isn't canonical (uppercase, IDN
///   pre-punycode, trailing slash, etc.), returns
///   `Err(AppError::Validation(...))` with the canonical form in the
///   message so the caller can retry.
/// - If `input` is unparseable (control chars, garbage), returns
///   `Err(AppError::Validation(...))` with a generic "malformed" reason.
///
/// IP-literal hosts (`127.0.0.1`, `[::1]`) are rejected — a domain
/// must be a DNS name. Loopback IPs are honoured at the request-host
/// level by the trusted-proxy logic in T19, not here.
pub fn normalize_domain_name(input: &str) -> Result<String, AppError> {
    if input.is_empty() {
        return Err(AppError::Validation("domain name must not be empty".into()));
    }
    if input.len() > MAX_LEN {
        return Err(AppError::Validation(format!(
            "domain name exceeds {MAX_LEN} chars"
        )));
    }
    // No leading/trailing whitespace (operators paste from chat / docs
    // and these slip in). Reject before any further processing so the
    // error names the issue clearly.
    if input.trim() != input {
        return Err(AppError::Validation(
            "domain name must not have leading or trailing whitespace".into(),
        ));
    }
    if input.starts_with('/') || input.ends_with('/') {
        return Err(AppError::Validation(
            "domain name must not start or end with '/'".into(),
        ));
    }

    let (host_in, path_in) = match input.split_once('/') {
        Some((h, p)) => (h, Some(p)),
        None => (input, None),
    };

    let host = normalize_host(host_in)?;
    let canonical = match path_in {
        None => host,
        Some(p) => {
            let path = normalize_path(p)?;
            format!("{host}/{path}")
        }
    };

    if canonical != input {
        return Err(AppError::Validation(format!(
            "domain name not in canonical form — use '{canonical}'"
        )));
    }
    Ok(canonical)
}

/// Normalise the host portion of a domain identifier.
///
/// Uses [`url::Host::parse`] which applies IDNA-strict + lowercase
/// conversion. Rejects IP literals and any host containing characters
/// outside the LDH (letters, digits, hyphens) + `.` + IDN-punycode set.
///
/// An optional `:port` suffix is accepted and preserved in the
/// canonical form. The port is validated as a `1..=65535` integer
/// and re-emitted numerically so non-canonical inputs like
/// `example.com:08080` round-trip to `example.com:8080`. This is
/// what makes dev / single-host daemon deployments at
/// `http://localhost:8534` work: the embedded DID host is
/// `localhost%3A8534`, the HTTP `Host:` header is `localhost:8534`,
/// and the stored domain entry must be `localhost:8534` for both
/// sides to agree.
fn normalize_host(host: &str) -> Result<String, AppError> {
    let (host_part, port) = split_host_port(host)?;
    let parsed = url::Host::parse(host_part)
        .map_err(|e| AppError::Validation(format!("malformed host '{host_part}': {e}")))?;
    let canonical_host = match parsed {
        url::Host::Domain(s) => {
            // url::Host::parse lowercases and IDNA-encodes; double-check
            // there's no character we don't want to accept.
            if !s
                .chars()
                .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-' || c == '.')
            {
                return Err(AppError::Validation(format!(
                    "host '{s}' contains characters outside LDH + '.'"
                )));
            }
            s
        }
        url::Host::Ipv4(_) | url::Host::Ipv6(_) => {
            return Err(AppError::Validation(format!(
                "host '{host_part}' is an IP literal — domain names must be DNS hostnames"
            )));
        }
    };
    Ok(match port {
        Some(p) => format!("{canonical_host}:{p}"),
        None => canonical_host,
    })
}

/// Split an optional `:port` suffix from a host, validating the port
/// as a `1..=65535` integer. Returns the bare host plus the parsed
/// port. A bracketed IPv6 literal (`[::1]:8080`) falls through with
/// `Some` port and the literal `[::1]` host — which `url::Host::parse`
/// will accept as IPv6 and `normalize_host` then rejects with the
/// usual IP-literal error.
fn split_host_port(host: &str) -> Result<(&str, Option<u16>), AppError> {
    let Some((h, p)) = host.rsplit_once(':') else {
        return Ok((host, None));
    };
    if h.is_empty() || p.is_empty() {
        return Err(AppError::Validation(format!(
            "malformed host '{host}': empty host or port around ':'"
        )));
    }
    let n: u16 = p.parse().map_err(|_| {
        AppError::Validation(format!(
            "host port '{p}' must be a number between 1 and 65535"
        ))
    })?;
    if n == 0 {
        return Err(AppError::Validation("host port must not be 0".into()));
    }
    Ok((h, Some(n)))
}

/// Normalise the path-prefix portion (after `/`).
///
/// Accepts: lowercase alphanumeric + `-` + `_` + `.` + `/` (for multi-
/// segment paths like `tenant-a/instance-1`). Rejects uppercase,
/// percent-encoding, leading/trailing slashes, empty segments.
fn normalize_path(path: &str) -> Result<String, AppError> {
    if path.is_empty() {
        return Err(AppError::Validation(
            "path-prefix after '/' must not be empty".into(),
        ));
    }
    if path.starts_with('/') || path.ends_with('/') {
        return Err(AppError::Validation(
            "path-prefix must not have leading or trailing '/'".into(),
        ));
    }
    if path.contains("//") {
        return Err(AppError::Validation(
            "path-prefix must not contain empty segments ('//')".into(),
        ));
    }
    for c in path.chars() {
        let ok = c.is_ascii_lowercase()
            || c.is_ascii_digit()
            || c == '-'
            || c == '_'
            || c == '.'
            || c == '/';
        if !ok {
            return Err(AppError::Validation(format!(
                "path-prefix contains invalid character {c:?} — \
                 allowed: lowercase alphanumeric, '-', '_', '.', '/'"
            )));
        }
    }
    Ok(path.to_string())
}

#[cfg(test)]
mod tests {
    use super::*;

    fn assert_canonical_msg(err: &AppError, expected_form: &str) {
        let s = format!("{err}");
        assert!(
            s.contains(&format!("use '{expected_form}'")),
            "error message should quote canonical form '{expected_form}'; got: {s}"
        );
    }

    #[test]
    fn accepts_canonical_lowercase() {
        let out = normalize_domain_name("example.com").unwrap();
        assert_eq!(out, "example.com");
    }

    #[test]
    fn accepts_subdomain() {
        let out = normalize_domain_name("tenant-a.example.com").unwrap();
        assert_eq!(out, "tenant-a.example.com");
    }

    #[test]
    fn rejects_uppercase_with_canonical_in_error() {
        let err = normalize_domain_name("Example.com").expect_err("must reject");
        assert_canonical_msg(&err, "example.com");
    }

    #[test]
    fn rejects_all_caps_with_canonical_in_error() {
        let err = normalize_domain_name("EXAMPLE.COM").expect_err("must reject");
        assert_canonical_msg(&err, "example.com");
    }

    #[test]
    fn rejects_leading_or_trailing_whitespace() {
        assert!(normalize_domain_name(" example.com").is_err());
        assert!(normalize_domain_name("example.com ").is_err());
        assert!(normalize_domain_name("\texample.com").is_err());
    }

    #[test]
    fn rejects_empty() {
        assert!(normalize_domain_name("").is_err());
    }

    #[test]
    fn rejects_overlong() {
        let huge = "a".repeat(MAX_LEN + 1);
        assert!(normalize_domain_name(&huge).is_err());
    }

    #[test]
    fn rejects_ipv4_literal() {
        let err = normalize_domain_name("127.0.0.1").expect_err("must reject");
        assert!(err.to_string().contains("IP literal"));
    }

    #[test]
    fn rejects_ipv6_literal() {
        let err = normalize_domain_name("[::1]").expect_err("must reject");
        // url::Host::parse rejects bracketed without scheme — that
        // surfaces via the malformed-host path, which is fine.
        let _ = err.to_string();
    }

    #[test]
    fn idna_normalises_internationalised() {
        // IDN: müller.example → xn--mller-kva.example. The non-canonical
        // input must reject with the canonical form in the error.
        let err = normalize_domain_name("müller.example").expect_err("must reject pre-punycode");
        assert_canonical_msg(&err, "xn--mller-kva.example");
        // The canonical punycode form must be accepted.
        assert_eq!(
            normalize_domain_name("xn--mller-kva.example").unwrap(),
            "xn--mller-kva.example"
        );
    }

    // ---- path-prefix ----

    #[test]
    fn accepts_path_prefix_canonical() {
        let out = normalize_domain_name("example.com/webvh-a").unwrap();
        assert_eq!(out, "example.com/webvh-a");
    }

    #[test]
    fn accepts_path_prefix_with_segments() {
        let out = normalize_domain_name("example.com/tenant-a/instance-1").unwrap();
        assert_eq!(out, "example.com/tenant-a/instance-1");
    }

    #[test]
    fn rejects_uppercase_path_with_canonical_in_error() {
        // The path portion is uppercase but the host is fine — the
        // canonical form keeps the host as-is and reports the path
        // capitalisation. url::Host::parse on the host returns lowercase,
        // but here host is already lowercase, so the mismatch is purely
        // on the path side.
        let err =
            normalize_domain_name("example.com/Tenant-A").expect_err("uppercase path rejects");
        // path itself is invalid (uppercase), surfaces in the error
        // via normalize_path before the canonical check.
        let s = err.to_string();
        assert!(s.contains("invalid character"), "unexpected error: {s}");
    }

    #[test]
    fn rejects_leading_slash_in_input() {
        assert!(normalize_domain_name("/example.com").is_err());
    }

    #[test]
    fn rejects_trailing_slash_in_input() {
        assert!(normalize_domain_name("example.com/").is_err());
    }

    #[test]
    fn rejects_double_slash_in_path() {
        assert!(normalize_domain_name("example.com/a//b").is_err());
    }

    #[test]
    fn rejects_special_chars_in_path() {
        for bad in [
            "example.com/foo bar",
            "example.com/foo?bar",
            "example.com/foo#bar",
            "example.com/foo%20bar",
        ] {
            let err = normalize_domain_name(bad).expect_err(&format!("{bad} must reject"));
            let s = err.to_string();
            // For inputs that reach normalize_path the error mentions
            // "invalid character"; for inputs that get caught earlier
            // (url::Host::parse) the host-malformed path may trigger.
            // Either is acceptable; just confirm rejection.
            let _ = s;
            assert!(matches!(err, AppError::Validation(_)));
        }
    }

    #[test]
    fn rejects_path_with_uppercase_host() {
        // Uppercase host + valid path → canonical is fully lowercased.
        let err = normalize_domain_name("Example.com/webvh-a").expect_err("uppercase host rejects");
        assert_canonical_msg(&err, "example.com/webvh-a");
    }

    #[test]
    fn round_trips_under_re_normalisation() {
        // The result of `normalize_domain_name` must itself be canonical
        // (i.e. a second pass returns the same string). Drift between
        // these two would mean the system stores values it can't
        // re-validate.
        for input in [
            "example.com",
            "tenant-a.example.com",
            "example.com/webvh-a",
            "example.com/tenant-a/instance-1",
            "xn--mller-kva.example",
            "localhost:8534",
            "example.com:8443/webvh-a",
        ] {
            let canonical = normalize_domain_name(input).expect(input);
            assert_eq!(
                canonical,
                normalize_domain_name(&canonical).unwrap(),
                "non-idempotent on {input}"
            );
        }
    }

    // ---- host:port ----

    #[test]
    fn accepts_host_with_port() {
        assert_eq!(
            normalize_domain_name("localhost:8534").unwrap(),
            "localhost:8534"
        );
        assert_eq!(
            normalize_domain_name("example.com:8443").unwrap(),
            "example.com:8443"
        );
    }

    #[test]
    fn accepts_host_with_port_and_path() {
        assert_eq!(
            normalize_domain_name("example.com:8443/webvh-a").unwrap(),
            "example.com:8443/webvh-a"
        );
    }

    #[test]
    fn host_with_port_normalises_case_and_leading_zero() {
        // Uppercase host with port → canonical lowercases and re-emits
        // port numerically. Both deviations surface in one error.
        let err =
            normalize_domain_name("Example.com:08443").expect_err("non-canonical must reject");
        assert_canonical_msg(&err, "example.com:8443");
    }

    #[test]
    fn rejects_zero_port() {
        let err = normalize_domain_name("example.com:0").expect_err("port 0 must reject");
        assert!(matches!(err, AppError::Validation(_)));
    }

    #[test]
    fn rejects_overflow_port() {
        // 65536 doesn't fit in u16.
        let err = normalize_domain_name("example.com:65536").expect_err("overflow must reject");
        assert!(matches!(err, AppError::Validation(_)));
    }

    #[test]
    fn rejects_non_numeric_port() {
        let err = normalize_domain_name("example.com:http").expect_err("non-numeric must reject");
        assert!(matches!(err, AppError::Validation(_)));
    }

    #[test]
    fn rejects_empty_port_after_colon() {
        let err = normalize_domain_name("example.com:").expect_err("empty port must reject");
        assert!(matches!(err, AppError::Validation(_)));
    }
}