rama-net 0.3.0

rama network types and utilities
Documentation
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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
//! `Uri::parse_authority_form` — the HTTP CONNECT request-target shape
//! `[userinfo@]host[:port]` (RFC 9112 §3.2.3).
//!
//! Distinct entry point because the grammar is ambiguous with
//! `scheme:opaque-path` (`example.com:443` parses validly as both, and
//! RFC 3986 prefers the scheme reading). HTTP proxies handling CONNECT
//! must route through this entry; `Uri::parse` retains the RFC 3986
//! tie-break.

use crate::uri::{ParseError, Uri};

#[test]
fn host_port_pair() {
    let u = Uri::parse_authority_form("example.com:443").unwrap();
    assert!(u.scheme().is_none(), "authority-form has no scheme");
    assert_eq!(u.host().unwrap().to_str(), "example.com");
    assert_eq!(u.port_u16(), Some(443));
    assert_eq!(u.path().map(|p| p.as_encoded_str()).as_deref(), Some(""));
}

#[test]
fn host_port_with_userinfo() {
    let u = Uri::parse_authority_form("user:pass@example.com:443").unwrap();
    assert_eq!(u.host().unwrap().to_str(), "example.com");
    assert_eq!(u.port_u16(), Some(443));
    assert!(u.userinfo().is_some());
}

#[test]
fn ipv4_literal() {
    let u = Uri::parse_authority_form("127.0.0.1:8080").unwrap();
    assert_eq!(u.host().unwrap().to_str(), "127.0.0.1");
    assert_eq!(u.port_u16(), Some(8080));
}

#[test]
fn ipv6_bracketed_literal() {
    let u = Uri::parse_authority_form("[::1]:443").unwrap();
    assert_eq!(u.host().unwrap().to_str(), "::1");
    assert_eq!(u.port_u16(), Some(443));

    let u = Uri::parse_authority_form("[2001:db8::1]:80").unwrap();
    assert_eq!(u.host().unwrap().to_str(), "2001:db8::1");
    assert_eq!(u.port_u16(), Some(80));
}

#[test]
fn bare_host_without_port_accepted() {
    // RFC 9112 §3.2.3 says CONNECT *requires* a port; lower-level URI
    // parsing is more permissive — HTTP-aware callers can enforce the
    // port requirement at their layer.
    let u = Uri::parse_authority_form("example.com").unwrap();
    assert_eq!(u.host().unwrap().to_str(), "example.com");
    assert_eq!(u.port_u16(), None);
}

#[test]
fn path_query_fragment_delimiters_rejected() {
    // Any of `/`, `?`, `#` means the caller has the wrong shape.
    Uri::parse_authority_form("example.com:443/foo").unwrap_err();
    Uri::parse_authority_form("example.com:443?x=1").unwrap_err();
    Uri::parse_authority_form("example.com:443#frag").unwrap_err();
    Uri::parse_authority_form("https://example.com:443").unwrap_err();
}

#[test]
fn empty_input_rejected() {
    assert!(matches!(
        Uri::parse_authority_form(""),
        Err(ParseError::Empty)
    ));
}

#[test]
fn invalid_port_rejected() {
    Uri::parse_authority_form("example.com:99999").unwrap_err();
    Uri::parse_authority_form("example.com:abc").unwrap_err();
}

#[test]
fn empty_port_accepted_in_graceful_as_bare_host() {
    // RFC 3986 §3.2.3 allows empty port; graceful authority-form
    // accepts bare-host shapes, so `example.com:` parses with `None`.
    let u = Uri::parse_authority_form("example.com:").unwrap();
    assert_eq!(u.host().unwrap().to_str(), "example.com");
    assert_eq!(u.port_u16(), None);
}

#[test]
fn empty_port_rejected_in_strict_authority_form() {
    // RFC 9112 §3.2.3 requires `host ":" port` — strict mode rejects
    // the bare-host form an empty port produces.
    let r = Uri::parse_authority_form_strict("example.com:");
    assert!(matches!(r, Err(crate::uri::ParseError::StrictViolation)));
}

#[cfg(feature = "idna")]
#[test]
fn graceful_preserves_non_ascii_host_in_authority_form() {
    // Wire-fidelity preservation (M7 reversed): parser stores the bytes
    // verbatim. IDN conversion to ACE happens on demand via
    // `Domain::try_from(uri.host().as_uninterpreted())`.
    let u = Uri::parse_authority_form("münchen.de:443").unwrap();
    assert_eq!(u.host().unwrap().to_str(), "münchen.de");
}

#[cfg(feature = "idna")]
#[test]
fn strict_rejects_non_ascii_host() {
    // Strict authority-form must reject non-ASCII identically to strict
    // `Uri::parse` — RFC 3986 host grammar is ASCII only.
    let r = Uri::parse_authority_form_strict("münchen.de:443");
    assert!(r.is_err(), "strict authority-form must reject non-ASCII");
}

#[test]
fn renders_without_scheme_or_path() {
    // Round-trip: parsed authority-form must render as `host:port` only.
    // If a scheme or path slips in, HTTP CONNECT proxies route wrong.
    let u = Uri::parse_authority_form("example.com:443").unwrap();
    let s = u.to_string();
    assert!(!s.contains("://"), "rendered has scheme prefix: {s}");
    assert!(s.contains("example.com"));
    assert!(s.contains("443"));
}

#[test]
fn plain_parse_treats_host_port_as_scheme_path() {
    // Pin RFC 3986 tie-break: `Uri::parse` on a bare `host:port` reads
    // it as `scheme:opaque-path`. Callers handling CONNECT must call
    // `parse_authority_form` instead.
    let u = Uri::parse("example.com:443").unwrap();
    assert_eq!(u.scheme().map(|s| s.as_str()), Some("example.com"));
    assert!(u.host().is_none());
}

// ---- Strict RFC 9112 §3.2.3 enforcement -----------------------------------

#[test]
fn strict_accepts_host_port() {
    // The canonical CONNECT shape passes through cleanly.
    let u = Uri::parse_authority_form_strict("example.com:443").unwrap();
    assert_eq!(u.host().unwrap().to_str(), "example.com");
    assert_eq!(u.port_u16(), Some(443));
}

#[test]
fn strict_accepts_bracketed_ipv6_host_port() {
    let u = Uri::parse_authority_form_strict("[2001:db8::1]:443").unwrap();
    assert_eq!(u.host().unwrap().to_str(), "2001:db8::1");
    assert_eq!(u.port_u16(), Some(443));
}

#[test]
fn strict_rejects_userinfo() {
    // RFC 9112 §3.2.3: "The request-target consists of the host and port
    // number of the tunnel destination" — no userinfo permitted.
    let err = Uri::parse_authority_form_strict("user:pass@example.com:443").unwrap_err();
    assert!(
        matches!(err, ParseError::StrictViolation),
        "expected StrictViolation, got {err:?}"
    );
    // Userinfo on its own (no password) is also out.
    Uri::parse_authority_form_strict("user@example.com:443").unwrap_err();
}

#[test]
fn strict_rejects_bare_host_without_port() {
    // §3.2.3 mandates a port. Graceful accepts; strict does not.
    let err = Uri::parse_authority_form_strict("example.com").unwrap_err();
    assert!(
        matches!(err, ParseError::StrictViolation),
        "expected StrictViolation, got {err:?}"
    );
    // IPv6 bracketed without port also rejected.
    Uri::parse_authority_form_strict("[2001:db8::1]").unwrap_err();
}

#[test]
fn strict_keeps_path_query_fragment_rejection() {
    // Pre-port-check guard fires before the strict-mode shape check.
    // The error kind (InvalidComponent vs StrictViolation) doesn't matter
    // — both modes reject — but pin both still error so we don't accept
    // a CONNECT target with a path under any setting.
    Uri::parse_authority_form_strict("example.com:443/p").unwrap_err();
    Uri::parse_authority_form_strict("example.com:443?q").unwrap_err();
    Uri::parse_authority_form_strict("example.com:443#f").unwrap_err();
}

#[test]
fn as_authority_form_projects_full_uri() {
    // Drops scheme/path/query/fragment, keeps host[:port].
    let u = Uri::parse("https://example.com:8443/some/path?q=1#frag").unwrap();
    let auth = u.as_authority_form().unwrap();
    assert!(auth.scheme().is_none());
    assert_eq!(auth.host().unwrap().to_str(), "example.com");
    assert_eq!(auth.port_u16(), Some(8443));
    assert_eq!(auth.path().map(|p| p.as_encoded_str()).as_deref(), Some(""));
    assert_eq!(auth.as_str(), "example.com:8443");

    // No explicit port → bare host.
    let u = Uri::parse("http://example.com/a").unwrap();
    assert_eq!(u.as_authority_form().unwrap().as_str(), "example.com");

    // Already authority-form → idempotent.
    let u = Uri::parse_authority_form("example.com:443").unwrap();
    assert_eq!(u.as_authority_form().unwrap().as_str(), "example.com:443");

    // No authority (origin-form / asterisk) → None.
    assert!(
        Uri::parse("/just/a/path")
            .unwrap()
            .as_authority_form()
            .is_none()
    );
    assert!(Uri::parse("*").unwrap().as_authority_form().is_none());
}

#[test]
fn ergonomic_accessors() {
    let u = Uri::parse("https://example.com:8443/api/v2/users?q=1").unwrap();
    assert_eq!(u.path_or_root(), "/api/v2/users");
    assert_eq!(u.query_or_empty(), "q=1");
    assert_eq!(u.scheme_str(), Some("https"));
    assert_eq!(u.host_str().as_deref(), Some("example.com"));
    assert_eq!(u.request_target(), "/api/v2/users?q=1");
    assert!(u.has_path_prefix("/api"));
    assert!(u.has_path_suffix("/users"));
    assert_eq!(
        u.first_path_segment()
            .map(|s| s.as_encoded_str())
            .as_deref(),
        Some("api")
    );
    assert_eq!(
        u.path_segment(2).map(|s| s.as_encoded_str()).as_deref(),
        Some("users")
    );
    assert!(u.path_segment(3).is_none());

    // empty / absent path defaults
    let u = Uri::parse("http://example.com").unwrap();
    assert!(u.is_path_empty());
    assert_eq!(u.path_or_root(), "/");
    assert_eq!(u.query_or_empty(), "");
    assert_eq!(u.request_target(), "/");
    assert!(!u.has_path_suffix("/x"));

    // origin-form
    let u = Uri::parse("/foo/bar").unwrap();
    assert!(!u.is_path_empty());
    assert_eq!(u.request_target(), "/foo/bar");
    assert_eq!(u.scheme_str(), None);
    assert_eq!(u.host_str(), None);
}

#[test]
fn ensure_path_or_root_only_roots_empty_non_asterisk_path() {
    let mut u = Uri::parse("http://example.com?x=1").unwrap();
    assert!(u.is_path_empty());
    u.ensure_path_or_root();
    assert!(!u.is_path_empty());
    assert_eq!(u.request_target(), "/?x=1");

    let mut u = Uri::parse("*").unwrap();
    assert!(u.is_path_empty());
    u.ensure_path_or_root();
    assert!(u.is_asterisk());
    assert_eq!(u.request_target(), "*");
}

#[test]
fn ensure_path_trailing_slash_works() {
    let mut u = Uri::parse("http://example.com/dir").unwrap();
    u.ensure_path_trailing_slash();
    assert_eq!(u.path_or_root(), "/dir/");
    // idempotent
    u.ensure_path_trailing_slash();
    assert_eq!(u.path_or_root(), "/dir/");
    // query preserved
    let mut u = Uri::parse("http://example.com/dir?x=1").unwrap();
    u.ensure_path_trailing_slash();
    assert_eq!(u.request_target(), "/dir/?x=1");
}

#[test]
fn ensure_path_trailing_slash_leaves_asterisk_untouched() {
    // Same guard as `ensure_path_or_root` — the asterisk-form has no
    // path to normalize and must not silently degrade to `/`.
    let mut u = Uri::parse("*").unwrap();
    u.ensure_path_trailing_slash();
    assert!(u.is_asterisk());
    assert_eq!(u.request_target(), "*");
}

#[test]
fn trim_path_trailing_slash_works() {
    let mut u = Uri::parse("http://example.com/dir/").unwrap();
    assert!(u.trim_path_trailing_slash());
    assert_eq!(u.path_or_root(), "/dir");
    // idempotent
    assert!(!u.trim_path_trailing_slash());
    assert_eq!(u.path_or_root(), "/dir");

    // root stays root
    let mut u = Uri::parse("http://example.com/").unwrap();
    assert!(!u.trim_path_trailing_slash());
    assert_eq!(u.path_or_root(), "/");

    // duplicate slashes collapse, query preserved
    let mut u = Uri::parse("http://example.com/dir///?x=1").unwrap();
    assert!(u.trim_path_trailing_slash());
    assert_eq!(u.request_target(), "/dir?x=1");
}

#[test]
fn trim_path_trailing_slash_leaves_asterisk_untouched() {
    let mut u = Uri::parse("*").unwrap();
    assert!(!u.trim_path_trailing_slash());
    assert!(u.is_asterisk());
    assert_eq!(u.request_target(), "*");
}

#[cfg(test)]
mod path_match {
    use crate::uri::{PathMatchOptions, Uri};

    fn uri(s: &str) -> Uri {
        Uri::parse(s).unwrap()
    }

    #[test]
    fn has_prefix_boundary_default() {
        let u = uri("https://example.com/api/v2/users");
        assert!(u.has_path_prefix("/api"));
        assert!(u.has_path_prefix("api")); // leading slash optional
        assert!(u.has_path_prefix("/api/v2"));
        assert!(u.has_path_prefix("")); // empty matches
        assert!(u.has_path_prefix("/api/v2/users")); // whole path
        // mid-segment rejected at boundary
        assert!(!u.has_path_prefix("/ap"));
        assert!(!u.has_path_prefix("/api/v")); // partial last segment
        assert!(!uri("https://example.com/apixyz").has_path_prefix("/api"));
    }

    #[test]
    fn has_prefix_partial() {
        let opts = PathMatchOptions {
            partial: true,
            ..Default::default()
        };
        let u = uri("https://example.com/apixyz/v2");
        assert!(u.has_path_prefix_with_opts("/api", opts));
        assert!(u.has_path_prefix_with_opts("/apixyz/v", opts));
        assert!(!u.has_path_prefix_with_opts("/xyz", opts));
    }

    #[test]
    fn has_suffix_boundary_and_partial() {
        let u = uri("https://example.com/api/style.css");
        // boundary: whole last segment
        assert!(u.has_path_suffix("style.css"));
        assert!(u.has_path_suffix("api/style.css"));
        assert!(!u.has_path_suffix(".css")); // mid-segment rejected
        assert!(!u.has_path_suffix("le.css"));
        // partial: byte suffix
        let partial = PathMatchOptions {
            partial: true,
            ..Default::default()
        };
        assert!(u.has_path_suffix_with_opts(".css", partial));
        assert!(u.has_path_suffix_with_opts("le.css", partial));
        assert!(!u.has_path_suffix_with_opts(".png", partial));
    }

    #[test]
    fn percent_decode_default_on() {
        let u = uri("https://example.com/foo%20bar/baz");
        // normalized: decoded "foo bar" matches both decoded and encoded patterns
        assert!(u.has_path_prefix("/foo bar"));
        assert!(u.has_path_prefix("/foo%20bar"));
        // opt out of decoding → only the raw byte form matches
        let raw = PathMatchOptions {
            percent_decode: false,
            ..Default::default()
        };
        assert!(!u.has_path_prefix_with_opts("/foo bar", raw));
        assert!(u.has_path_prefix_with_opts("/foo%20bar", raw));
        // encoded slash stays in-segment (no phantom separator)
        assert!(!uri("https://example.com/a%2Fb/c").has_path_prefix("/a/b"));
    }

    #[test]
    fn ignore_ascii_case_opt() {
        let u = uri("https://example.com/API/v2");
        assert!(!u.has_path_prefix("/api"));
        let ci = PathMatchOptions {
            ignore_ascii_case: true,
            ..Default::default()
        };
        assert!(u.has_path_prefix_with_opts("/api", ci));
        assert!(u.has_path_prefix_with_opts("/API", ci));
    }

    #[test]
    fn strip_prefix_boundary_and_partial() {
        let mut u = uri("https://example.com/api/v2/x");
        assert!(u.path_mut().strip_prefix("/api"));
        assert_eq!(u.as_str(), "https://example.com/v2/x");

        // boundary rejects mid-segment
        let mut u = uri("https://example.com/api/v2");
        assert!(!u.path_mut().strip_prefix("/ap"));
        assert_eq!(u.as_str(), "https://example.com/api/v2"); // unchanged

        // partial allows mid-segment
        let mut u = uri("https://example.com/api/v2");
        let partial = PathMatchOptions {
            partial: true,
            ..Default::default()
        };
        assert!(u.path_mut().strip_prefix_with_opts("/ap", partial));
        assert_eq!(u.as_str(), "https://example.com/i/v2");
    }

    #[test]
    fn strip_suffix_works() {
        let mut u = uri("https://example.com/a/b/c");
        assert!(u.path_mut().strip_suffix("c"));
        assert_eq!(u.as_str(), "https://example.com/a/b");

        let mut u = uri("https://example.com/a/b/c");
        assert!(u.path_mut().strip_suffix("b/c"));
        assert_eq!(u.as_str(), "https://example.com/a");

        // boundary rejects mid-segment suffix
        let mut u = uri("https://example.com/a/bc");
        assert!(!u.path_mut().strip_suffix("c"));
        assert_eq!(u.as_str(), "https://example.com/a/bc");

        // partial allows it
        let mut u = uri("https://example.com/a/bc");
        let partial = PathMatchOptions {
            partial: true,
            ..Default::default()
        };
        assert!(u.path_mut().strip_suffix_with_opts("c", partial));
        assert_eq!(u.as_str(), "https://example.com/a/b");
    }

    #[test]
    fn has_and_strip_agree() {
        // The check and the strip must use identical matching.
        let cases = ["/api/v2", "/apixyz", "/a/b/c", "/", "/foo%20bar/x"];
        let patterns = ["/api", "api", "/a/b", "ap", "/foo bar"];
        for opts in [
            PathMatchOptions::default(),
            PathMatchOptions {
                partial: true,
                ..Default::default()
            },
            PathMatchOptions {
                ignore_ascii_case: true,
                ..Default::default()
            },
            PathMatchOptions {
                percent_decode: false,
                ..Default::default()
            },
        ] {
            for path in cases {
                for pat in patterns {
                    let u = uri(&format!("http://h{path}"));
                    let has = u.has_path_prefix_with_opts(pat, opts);
                    let mut s = u.clone();
                    let stripped = s.path_mut().strip_prefix_with_opts(pat, opts);
                    assert_eq!(
                        has, stripped,
                        "disagree for path={path:?} pat={pat:?} opts={opts:?}"
                    );
                }
            }
        }
    }
}