// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT const std = @import("std"); const uri = @import("root.zig"); const Host = uri.Host; const QueryParam = uri.QueryParam; const Uri = uri.Uri; const expect = std.testing.expect; const expectEqual = std.testing.expectEqual; const expectEqualDeep = std.testing.expectEqualDeep; const expectEqualStrings = std.testing.expectEqualStrings; const expectError = std.testing.expectError; // -- parsing --------------------------------------------------------------- const Case = struct { uri: []const u8, /// Expected serialization. Defaults to `uri`; set it where canonical /// re-encoding differs from the input. text: ?[]const u8 = null, scheme: ?[]const u8 = null, username: ?[]const u8 = null, password: ?[]const u8 = null, host: ?Host = null, port: ?u16 = null, rooted: bool = false, path: []const []const u8 = &.{}, query: []const QueryParam = &.{}, fragment: ?[]const u8 = null, }; const cases = [_]Case{ .{ .uri = "http://localhost", .scheme = "http", .host = .{ .hostname = "localhost" }, }, .{ .uri = "http://localhost/", .scheme = "http", .host = .{ .hostname = "localhost" }, .rooted = true, .path = &.{""}, }, .{ .uri = "http://127.0.0.1/", .scheme = "http", .host = .{ .ipv4 = "127.0.0.1" }, .rooted = true, .path = &.{""}, }, .{ .uri = "http://[::127.0.0.1]/", .scheme = "http", .host = .{ .ipv6 = "::127.0.0.1" }, .rooted = true, .path = &.{""}, }, .{ .uri = "http://[::1]/", .scheme = "http", .host = .{ .ipv6 = "::1" }, .rooted = true, .path = &.{""}, }, .{ .uri = "http://localhost/foo", .scheme = "http", .host = .{ .hostname = "localhost" }, .rooted = true, .path = &.{"foo"}, }, .{ .uri = "http://localhost/foo/", .scheme = "http", .host = .{ .hostname = "localhost" }, .rooted = true, .path = &.{ "foo", "" }, }, .{ .uri = "http://localhost/foo!!bar/", .scheme = "http", .host = .{ .hostname = "localhost" }, .rooted = true, .path = &.{ "foo!!bar", "" }, }, .{ .uri = "http://localhost/foo%20bar/", .scheme = "http", .host = .{ .hostname = "localhost" }, .rooted = true, .path = &.{ "foo bar", "" }, }, .{ .uri = "http://localhost/foo%2Fbar/", .scheme = "http", .host = .{ .hostname = "localhost" }, .rooted = true, .path = &.{ "foo/bar", "" }, }, .{ .uri = "http://localhost/foo?n", .scheme = "http", .host = .{ .hostname = "localhost" }, .rooted = true, .path = &.{"foo"}, .query = &.{.{ .key = "n" }}, }, .{ .uri = "http://localhost/foo?n=v", .scheme = "http", .host = .{ .hostname = "localhost" }, .rooted = true, .path = &.{"foo"}, .query = &.{.{ .key = "n", .value = "v" }}, }, .{ .uri = "http://localhost/foo?n=/a/b", .scheme = "http", .host = .{ .hostname = "localhost" }, .rooted = true, .path = &.{"foo"}, .query = &.{.{ .key = "n", .value = "/a/b" }}, }, .{ .uri = "http://example.com/foo!@$bar?b!@z=123", .scheme = "http", .host = .{ .hostname = "example.com" }, .rooted = true, .path = &.{"foo!@$bar"}, .query = &.{.{ .key = "b!@z", .value = "123" }}, }, .{ .uri = "http://localhost/asd?a=asd%20sdf/345", .scheme = "http", .host = .{ .hostname = "localhost" }, .rooted = true, .path = &.{"asd"}, .query = &.{.{ .key = "a", .value = "asd sdf/345" }}, }, // A doubly-encoded percent sign in every percent-encodable position. Each // component decodes exactly one layer and re-encodes back to the original. .{ .uri = "http://(%2525)/(%2525)?(%2525)&(%2525)=(%2525)#(%2525)", .scheme = "http", .host = .{ .hostname = "(%25)" }, .rooted = true, .path = &.{"(%25)"}, .query = &.{ .{ .key = "(%25)" }, .{ .key = "(%25)", .value = "(%25)" }, }, .fragment = "(%25)", }, .{ .uri = "http://(%C3%A9)/(%C3%A9)?(%C3%A9)&(%C3%A9)=(%C3%A9)#(%C3%A9)", .scheme = "http", .host = .{ .hostname = "(é)" }, .rooted = true, .path = &.{"(é)"}, .query = &.{ .{ .key = "(é)" }, .{ .key = "(é)", .value = "(é)" }, }, .fragment = "(é)", }, .{ .uri = "?sslrootcert=/Users/glyph/Downloads/rds-ca-2015-root.pem&sslmode=verify", .query = &.{ .{ .key = "sslrootcert", .value = "/Users/glyph/Downloads/rds-ca-2015-root.pem" }, .{ .key = "sslmode", .value = "verify" }, }, }, // from boltons.urlutils' tests .{ .uri = "http://googlewebsite.com/e-shops.aspx", .scheme = "http", .host = .{ .hostname = "googlewebsite.com" }, .rooted = true, .path = &.{"e-shops.aspx"}, }, .{ .uri = "http://example.com:8080/search?q=123&business=Nothing%20Special", .scheme = "http", .host = .{ .hostname = "example.com" }, .port = 8080, .rooted = true, .path = &.{"search"}, .query = &.{ .{ .key = "q", .value = "123" }, .{ .key = "business", .value = "Nothing Special" }, }, }, .{ .uri = "http://hatnote.com:9000/?arg=1&arg=2&arg=3", .scheme = "http", .host = .{ .hostname = "hatnote.com" }, .port = 9000, .rooted = true, .path = &.{""}, .query = &.{ .{ .key = "arg", .value = "1" }, .{ .key = "arg", .value = "2" }, .{ .key = "arg", .value = "3" }, }, }, .{ .uri = "https://xn--bcher-kva.ch", .scheme = "https", .host = .{ .hostname = "xn--bcher-kva.ch" }, }, .{ .uri = "http://xn--ggbla1c4e.xn--ngbc5azd/", .scheme = "http", .host = .{ .hostname = "xn--ggbla1c4e.xn--ngbc5azd" }, .rooted = true, .path = &.{""}, }, .{ .uri = "http://tools.ietf.org/html/rfc3986#section-3.4", .scheme = "http", .host = .{ .hostname = "tools.ietf.org" }, .rooted = true, .path = &.{ "html", "rfc3986" }, .fragment = "section-3.4", }, .{ .uri = "http://wiki:pedia@hatnote.com", .scheme = "http", .username = "wiki", .password = "pedia", .host = .{ .hostname = "hatnote.com" }, }, .{ .uri = "ftp://ftp.rfc-editor.org/in-notes/tar/RFCs0001-0500.tar.gz", .scheme = "ftp", .host = .{ .hostname = "ftp.rfc-editor.org" }, .rooted = true, .path = &.{ "in-notes", "tar", "RFCs0001-0500.tar.gz" }, }, .{ .uri = "http://[1080:0:0:0:8:800:200C:417A]/index.html", .scheme = "http", .host = .{ .ipv6 = "1080:0:0:0:8:800:200C:417A" }, .rooted = true, .path = &.{"index.html"}, }, .{ .uri = "ssh://192.0.2.16:2222/", .scheme = "ssh", .host = .{ .ipv4 = "192.0.2.16" }, .port = 2222, .rooted = true, .path = &.{""}, }, .{ .uri = "https://[::101.45.75.219]:80/?hi=bye", .scheme = "https", .host = .{ .ipv6 = "::101.45.75.219" }, .port = 80, .rooted = true, .path = &.{""}, .query = &.{.{ .key = "hi", .value = "bye" }}, }, .{ .uri = "ldap://[::192.9.5.5]/dc=example,dc=com??sub?(sn=Jensen)", .scheme = "ldap", .host = .{ .ipv6 = "::192.9.5.5" }, .rooted = true, .path = &.{"dc=example,dc=com"}, .query = &.{.{ .key = "?sub?(sn", .value = "Jensen)" }}, }, .{ .uri = "mailto:me@example.com?to=me@example.com&body=hi%20http://wikipedia.org", .scheme = "mailto", .path = &.{"me@example.com"}, .query = &.{ .{ .key = "to", .value = "me@example.com" }, .{ .key = "body", .value = "hi http://wikipedia.org" }, }, }, .{ .uri = "news:alt.rec.motorcycle", .scheme = "news", .path = &.{"alt.rec.motorcycle"}, }, .{ .uri = "tel:+1-800-867-5309", .scheme = "tel", .path = &.{"+1-800-867-5309"}, }, .{ .uri = "urn:oasis:member:A00024:x", .scheme = "urn", .path = &.{"oasis:member:A00024:x"}, }, .{ .uri = "magnet:?xt=urn:btih:1a42b9e04e122b97a5254e3df77ab3c4b7da725f&dn=Puppy%20Linux%20precise-5.7.1.iso&tr=udp://tracker.openbittorrent.com:80&tr=udp://tracker.publicbt.com:80", .scheme = "magnet", .query = &.{ .{ .key = "xt", .value = "urn:btih:1a42b9e04e122b97a5254e3df77ab3c4b7da725f" }, .{ .key = "dn", .value = "Puppy Linux precise-5.7.1.iso" }, .{ .key = "tr", .value = "udp://tracker.openbittorrent.com:80" }, .{ .key = "tr", .value = "udp://tracker.publicbt.com:80" }, }, }, // Percent-encoded delimiters must not split the component they appear in. .{ .uri = "https://%3A@example.com/", // colon in username .scheme = "https", .username = ":", .host = .{ .hostname = "example.com" }, .rooted = true, .path = &.{""}, }, .{ .uri = "https://%40@example.com/", // at sign in username .scheme = "https", .username = "@", .host = .{ .hostname = "example.com" }, .rooted = true, .path = &.{""}, }, .{ .uri = "https://%2f@example.com/", // slash in username .text = "https://%2F@example.com/", .scheme = "https", .username = "/", .host = .{ .hostname = "example.com" }, .rooted = true, .path = &.{""}, }, .{ // A colon needs no escape in a password: the split is on the *first* // colon, so everything after it is unambiguous. .uri = "https://a:%3a@example.com/", .text = "https://a::@example.com/", .scheme = "https", .username = "a", .password = ":", .host = .{ .hostname = "example.com" }, .rooted = true, .path = &.{""}, }, .{ .uri = "https://a:%40@example.com/", // at sign in password .scheme = "https", .username = "a", .password = "@", .host = .{ .hostname = "example.com" }, .rooted = true, .path = &.{""}, }, .{ .uri = "https://a:%2f@example.com/", // slash in password .text = "https://a:%2F@example.com/", .scheme = "https", .username = "a", .password = "/", .host = .{ .hostname = "example.com" }, .rooted = true, .path = &.{""}, }, .{ .uri = "https://a:%3f@example.com/", // question mark in password .text = "https://a:%3F@example.com/", .scheme = "https", .username = "a", .password = "?", .host = .{ .hostname = "example.com" }, .rooted = true, .path = &.{""}, }, .{ .uri = "https://example.com/%2F/", // slash in path .scheme = "https", .host = .{ .hostname = "example.com" }, .rooted = true, .path = &.{ "/", "" }, }, .{ .uri = "https://example.com/%3F/", // question mark in path .scheme = "https", .host = .{ .hostname = "example.com" }, .rooted = true, .path = &.{ "?", "" }, }, .{ .uri = "https://example.com/%23/", // hash in path .scheme = "https", .host = .{ .hostname = "example.com" }, .rooted = true, .path = &.{ "#", "" }, }, .{ .uri = "https://example.com/?%23=b", // hash in query param name .scheme = "https", .host = .{ .hostname = "example.com" }, .rooted = true, .path = &.{""}, .query = &.{.{ .key = "#", .value = "b" }}, }, .{ .uri = "https://example.com/?%3D=b", // equals in query param name .scheme = "https", .host = .{ .hostname = "example.com" }, .rooted = true, .path = &.{""}, .query = &.{.{ .key = "=", .value = "b" }}, }, .{ .uri = "https://example.com/?%26=b", // ampersand in query param name .scheme = "https", .host = .{ .hostname = "example.com" }, .rooted = true, .path = &.{""}, .query = &.{.{ .key = "&", .value = "b" }}, }, .{ .uri = "https://example.com/?a=%23", // hash in query param value .scheme = "https", .host = .{ .hostname = "example.com" }, .rooted = true, .path = &.{""}, .query = &.{.{ .key = "a", .value = "#" }}, }, .{ .uri = "https://example.com/?a=%26", // ampersand in query param value .scheme = "https", .host = .{ .hostname = "example.com" }, .rooted = true, .path = &.{""}, .query = &.{.{ .key = "a", .value = "&" }}, }, .{ // Only the first `=` splits a pair, so a later one needs no escape. .uri = "https://example.com/?a=%3D", .text = "https://example.com/?a==", .scheme = "https", .host = .{ .hostname = "example.com" }, .rooted = true, .path = &.{""}, .query = &.{.{ .key = "a", .value = "=" }}, }, .{ // `+` is a literal plus: reading it as a space is a form-encoding // convention, not part of URI syntax. .uri = "https://example.com/?foo+bar=baz", .scheme = "https", .host = .{ .hostname = "example.com" }, .rooted = true, .path = &.{""}, .query = &.{.{ .key = "foo+bar", .value = "baz" }}, }, .{ .uri = "https://example.com/?foo=bar+baz", .scheme = "https", .host = .{ .hostname = "example.com" }, .rooted = true, .path = &.{""}, .query = &.{.{ .key = "foo", .value = "bar+baz" }}, }, .{ .uri = "http://(%2525):(%2525)@example.com/(%2525)/?(%2525)=(%2525)#(%2525)", .scheme = "http", .username = "(%25)", .password = "(%25)", .host = .{ .hostname = "example.com" }, .rooted = true, .path = &.{ "(%25)", "" }, .query = &.{.{ .key = "(%25)", .value = "(%25)" }}, .fragment = "(%25)", }, .{ // A colon in the *first* segment of a rootless relative reference would // be read as a scheme, so it stays escaped there and only there. .uri = "first_seg_rel_path__colon%3Anotok/second_seg__colon%3Aok", .text = "first_seg_rel_path__colon%3Anotok/second_seg__colon:ok", .path = &.{ "first_seg_rel_path__colon:notok", "second_seg__colon:ok" }, }, .{ .uri = "file:///etc/passwd", .scheme = "file", .host = .{ .hostname = "" }, .rooted = true, .path = &.{ "etc", "passwd" }, }, .{ // An empty fragment is preserved, and stays distinct from no fragment. .uri = "http://example.com/#", .scheme = "http", .host = .{ .hostname = "example.com" }, .rooted = true, .path = &.{""}, .fragment = "", }, .{ // A bare `:` with no digits is an absent port, not a zero one. .uri = "http://example.com:/", .text = "http://example.com/", .scheme = "http", .host = .{ .hostname = "example.com" }, .rooted = true, .path = &.{""}, }, .{ // An empty query string carries no parameters, so the `?` is dropped. .uri = "http://example.com/?", .text = "http://example.com/", .scheme = "http", .host = .{ .hostname = "example.com" }, .rooted = true, .path = &.{""}, }, }; test "parse: components" { const alloc = std.testing.allocator; for (cases) |c| { const u = Uri.parse(alloc, c.uri) catch |err| { std.debug.print("\nfailed to parse: {s}\n", .{c.uri}); return err; }; defer u.deinit(); inline for (@typeInfo(Case).@"struct".fields) |f| { comptime if (std.mem.eql(u8, f.name, "uri") or std.mem.eql(u8, f.name, "text")) continue; expectEqualDeep(@field(c, f.name), @field(u, f.name)) catch |err| { std.debug.print("\nfield '{s}' of: {s}\n", .{ f.name, c.uri }); return err; }; } } } test "parse: round-trips through text" { const alloc = std.testing.allocator; for (cases) |c| { const u = try Uri.parse(alloc, c.uri); defer u.deinit(); const text = try u.toText(alloc, .{ .with_password = true }); defer alloc.free(text); expectEqualStrings(c.text orelse c.uri, text) catch |err| { std.debug.print("\nre-encoding: {s}\n", .{c.uri}); return err; }; // Whatever the text looks like, parsing it again must land on exactly // the same components — that is the property that actually matters. const again = try Uri.parse(alloc, text); defer again.deinit(); try expect(u.eql(again)); try expectEqual(u.hash(), again.hash()); } } test "parse: errors" { const alloc = std.testing.allocator; try expectError(error.InvalidScheme, Uri.parse(alloc, "not a scheme:/x")); try expectError(error.InvalidScheme, Uri.parse(alloc, "1http://example.com")); try expectError(error.InvalidScheme, Uri.parse(alloc, ":no-scheme")); try expectError(error.InvalidPort, Uri.parse(alloc, "http://example.com:99999/")); try expectError(error.InvalidPort, Uri.parse(alloc, "http://example.com:80x/")); try expectError(error.UnterminatedIPv6Literal, Uri.parse(alloc, "http://[::1/")); try expectError(error.InvalidAuthority, Uri.parse(alloc, "http://[::1]x/")); } test "parse: address literals are validated" { const alloc = std.testing.allocator; // Well-formed literals are kept exactly as written, not canonicalised. for ([_][]const u8{ "http://[::1]/", "http://[1080:0:0:0:8:800:200C:417A]/", "http://[::ffff:192.0.2.1]/", // RFC 6874 zone identifier: the `%` is written `%25` in a URI. "http://[fe80::1%25eth0]/", // IPvFuture is a shape with no defined meaning, so only its shape is // checked. "http://[v7.future-address]/", }) |text| { const u = try Uri.parse(alloc, text); defer u.deinit(); const out = try u.toText(alloc, .{}); defer alloc.free(out); expectEqualStrings(text, out) catch |err| { std.debug.print("\nround-tripping {s}\n", .{text}); return err; }; } // Nonsense in brackets used to be accepted verbatim. for ([_][]const u8{ "http://[::gg]/", // not hex "http://[1:2:3]/", // too few groups, no :: "http://[]/", // empty "http://[1::2::3]/", // two compressions "http://[fe80::1%eth0]/", // zone not percent-encoded "http://[fe80::1%25]/", // empty zone "http://[v.x]/", // IPvFuture with no version digits }) |text| { expectError(error.InvalidIPv6Literal, Uri.parse(alloc, text)) catch |err| { std.debug.print("\nexpected {s} to be rejected\n", .{text}); return err; }; } } test "parse: a dotted name that is not an IPv4 address is a host name" { const alloc = std.testing.allocator; // RFC 3986 §3.2.2 tries IPv4address first and falls back to reg-name. const addr = try Uri.parse(alloc, "http://192.0.2.16/"); defer addr.deinit(); try expectEqualStrings("192.0.2.16", addr.host.?.ipv4); for ([_][]const u8{ "192.168.01.1", // a leading zero is not a dec-octet "999.1.1.1", // out of range "1.2.3", // too few octets "1.2.3.4.5", // too many "0x7f.0.0.1", // an inet_aton shorthand, not a URI IPv4address }) |name| { const text = try std.fmt.allocPrint(alloc, "http://{s}/", .{name}); defer alloc.free(text); const u = try Uri.parse(alloc, text); defer u.deinit(); expectEqualStrings(name, u.host.?.hostname) catch |err| { std.debug.print("\nexpected {s} to parse as a host name\n", .{name}); return err; }; } } test "parse: malformed percent escapes are literal by default" { const alloc = std.testing.allocator; const u = try Uri.parse(alloc, "http://example.com/100%/%zz/%"); defer u.deinit(); try expectEqualDeep(@as([]const []const u8, &.{ "100%", "%zz", "%" }), u.path); const text = try u.toText(alloc, .{}); defer alloc.free(text); try expectEqualStrings("http://example.com/100%25/%25zz/%25", text); try expectError( error.InvalidPercentEncoding, Uri.parseOpts(alloc, "http://example.com/100%", .{ .strict_percent = true }), ); } // -- reference resolution -------------------------------------------------- // RFC 3986 §5.4, verbatim. The base is §5.4's "http://a/b/c/d;p?q". const rfc3986_base = "http://a/b/c/d;p?q"; const resolution_cases = [_][2][]const u8{ // §5.4.1 normal examples .{ "g:h", "g:h" }, .{ "g", "http://a/b/c/g" }, .{ "./g", "http://a/b/c/g" }, .{ "g/", "http://a/b/c/g/" }, .{ "/g", "http://a/g" }, .{ "//g", "http://g" }, .{ "?y", "http://a/b/c/d;p?y" }, .{ "g?y", "http://a/b/c/g?y" }, .{ "#s", "http://a/b/c/d;p?q#s" }, .{ "g#s", "http://a/b/c/g#s" }, .{ "g?y#s", "http://a/b/c/g?y#s" }, .{ ";x", "http://a/b/c/;x" }, .{ "g;x", "http://a/b/c/g;x" }, .{ "g;x?y#s", "http://a/b/c/g;x?y#s" }, .{ "", "http://a/b/c/d;p?q" }, .{ ".", "http://a/b/c/" }, .{ "./", "http://a/b/c/" }, .{ "..", "http://a/b/" }, .{ "../", "http://a/b/" }, .{ "../g", "http://a/b/g" }, .{ "../..", "http://a/" }, .{ "../../", "http://a/" }, .{ "../../g", "http://a/g" }, // §5.4.2 abnormal examples .{ "../../../g", "http://a/g" }, .{ "../../../../g", "http://a/g" }, .{ "/./g", "http://a/g" }, .{ "/../g", "http://a/g" }, .{ "g.", "http://a/b/c/g." }, .{ ".g", "http://a/b/c/.g" }, .{ "g..", "http://a/b/c/g.." }, .{ "..g", "http://a/b/c/..g" }, .{ "./../g", "http://a/b/g" }, .{ "./g/.", "http://a/b/c/g/" }, .{ "g/./h", "http://a/b/c/g/h" }, .{ "g/../h", "http://a/b/c/h" }, .{ "g;x=1/./y", "http://a/b/c/g;x=1/y" }, .{ "g;x=1/../y", "http://a/b/c/y" }, .{ "g?y/./x", "http://a/b/c/g?y/./x" }, .{ "g?y/../x", "http://a/b/c/g?y/../x" }, .{ "g#s/./x", "http://a/b/c/g#s/./x" }, .{ "g#s/../x", "http://a/b/c/g#s/../x" }, // §5.4.2 also lists "http:g" -> "http://a/b/c/g" for non-strict parsers; // a strict parser keeps the reference as-is, which is what we do. .{ "http:g", "http:g" }, }; test "click: RFC 3986 §5.4 reference resolution" { const alloc = std.testing.allocator; const base = try Uri.parse(alloc, rfc3986_base); defer base.deinit(); for (resolution_cases) |c| { const got = try base.click(alloc, c[0]); defer got.deinit(); const text = try got.toText(alloc, .{}); defer alloc.free(text); expectEqualStrings(c[1], text) catch |err| { std.debug.print("\nclick({s}) against {s}\n", .{ c[0], rfc3986_base }); return err; }; } } test "click: a network-path reference replaces the whole authority" { const alloc = std.testing.allocator; const base = try Uri.parse(alloc, "https://user:pw@a.example/x/y"); defer base.deinit(); const got = try base.click(alloc, "//b.example/z"); defer got.deinit(); try expect(got.username == null); try expect(got.password == null); try expectEqualStrings("b.example", got.host.?.hostname); try expectEqualStrings("https", got.scheme.?); } test "click: relative reference against a host with no path" { const alloc = std.testing.allocator; const base = try Uri.parse(alloc, "http://example.com"); defer base.deinit(); const got = try base.click(alloc, "g"); defer got.deinit(); const text = try got.toText(alloc, .{}); defer alloc.free(text); try expectEqualStrings("http://example.com/g", text); } test "click: a reference that resolves away the whole path" { const alloc = std.testing.allocator; const base = try Uri.parse(alloc, "a?q"); defer base.deinit(); // Removing the dot segments of `..` leaves the trailing empty segment that // makes a result name a directory, and here there is nothing in front of // it. An unrooted path of one empty segment is written as no path at all, // so it has to be stored as no path at all -- otherwise the result would // not compare equal to the same reference parsed back from its own text. const got = try base.click(alloc, ".."); defer got.deinit(); try expect(!got.rooted); try expectEqual(@as(usize, 0), got.path.len); const text = try got.toText(alloc, .{}); defer alloc.free(text); try expectEqualStrings("", text); const again = try Uri.parse(alloc, text); defer again.deinit(); try expect(got.eql(again)); try expectEqual(got.hash(), again.hash()); } test "click: a resolved path that begins with an empty segment" { const alloc = std.testing.allocator; // `.//` leaves an empty segment in front of the path, and with no // authority for it to follow there is nowhere for it to go but into // `rooted`: `//a` with no authority reads back as a host, not a path. // RFC 3986 §5.2.4 arrives at the same text. for ([_][3][]const u8{ .{ "x", ".//", "/" }, .{ "x", ".//a", "/a" }, .{ "x", ".///a", "/a" }, .{ "/x", ".//a", "/a" }, // With an authority the empty segment is written out and read back // unchanged, so it stays. .{ "http://h/x", ".//", "http://h//" }, .{ "http://h/x", ".//a", "http://h//a" }, }) |c| { const base = try Uri.parse(alloc, c[0]); defer base.deinit(); const got = try base.click(alloc, c[1]); defer got.deinit(); const text = try got.toText(alloc, .{}); defer alloc.free(text); expectEqualStrings(c[2], text) catch |err| { std.debug.print("\nclick({s}) against {s}\n", .{ c[1], c[0] }); return err; }; // The components have to say the same thing the text does. const again = try Uri.parse(alloc, text); defer again.deinit(); try expect(got.eql(again)); } } test "clickUri: takes an already-parsed reference" { const alloc = std.testing.allocator; const base = try Uri.parse(alloc, rfc3986_base); defer base.deinit(); const ref = try Uri.parse(alloc, "../g"); defer ref.deinit(); const got = try base.clickUri(alloc, ref); defer got.deinit(); const text = try got.toText(alloc, .{}); defer alloc.free(text); try expectEqualStrings("http://a/b/g", text); } // -- derivation ------------------------------------------------------------ /// Parse `text`, apply `op`, and assert the result renders as `want`. fn expectDerived( text: []const u8, want: []const u8, comptime op: fn (std.mem.Allocator, Uri) anyerror!Uri, ) !void { const alloc = std.testing.allocator; const u = try Uri.parse(alloc, text); defer u.deinit(); const got = try op(alloc, u); defer got.deinit(); const rendered = try got.toText(alloc, .{ .with_password = true }); defer alloc.free(rendered); try expectEqualStrings(want, rendered); } test "child: appends segments" { try expectDerived("http://example.com/a/b", "http://example.com/a/b/c", struct { fn f(a: std.mem.Allocator, u: Uri) !Uri { return u.child(a, &.{"c"}); } }.f); // A trailing empty segment is the `/` at the end, so it gets replaced // rather than producing an empty segment in the middle. try expectDerived("http://example.com/a/", "http://example.com/a/b/c", struct { fn f(a: std.mem.Allocator, u: Uri) !Uri { return u.child(a, &.{ "b", "c" }); } }.f); try expectDerived("http://example.com", "http://example.com/a", struct { fn f(a: std.mem.Allocator, u: Uri) !Uri { return u.child(a, &.{"a"}); } }.f); // Segments are data, not syntax: a `/` inside one stays inside it. try expectDerived("http://example.com/", "http://example.com/a%2Fb", struct { fn f(a: std.mem.Allocator, u: Uri) !Uri { return u.child(a, &.{"a/b"}); } }.f); } test "sibling: replaces the last segment" { try expectDerived("http://example.com/a/b", "http://example.com/a/c", struct { fn f(a: std.mem.Allocator, u: Uri) !Uri { return u.sibling(a, "c"); } }.f); try expectDerived("http://example.com/a/", "http://example.com/a/c", struct { fn f(a: std.mem.Allocator, u: Uri) !Uri { return u.sibling(a, "c"); } }.f); } test "replace: keeps, sets and clears fields" { const alloc = std.testing.allocator; const u = try Uri.parse(alloc, "http://user:pw@example.com:8080/a?x=1#f"); defer u.deinit(); // Setting one field leaves the rest alone. { const got = try u.replace(alloc, .{ .scheme = "https" }); defer got.deinit(); const text = try got.toText(alloc, .{ .with_password = true }); defer alloc.free(text); try expectEqualStrings("https://user:pw@example.com:8080/a?x=1#f", text); } // An explicit `?T` null clears. { const got = try u.replace(alloc, .{ .port = @as(?u16, null), .fragment = @as(?[]const u8, null), .password = @as(?[]const u8, null), }); defer got.deinit(); const text = try got.toText(alloc, .{ .with_password = true }); defer alloc.free(text); try expectEqualStrings("http://user@example.com/a?x=1", text); } // The result owns its own arena, so it outlives the original. { const original = try Uri.parse(alloc, "http://example.com/a"); const derived = try original.replace(alloc, .{ .host = Host{ .hostname = "elsewhere.test" } }); defer derived.deinit(); original.deinit(); const text = try derived.toText(alloc, .{}); defer alloc.free(text); try expectEqualStrings("http://elsewhere.test/a", text); } } test "normalize: case and dot segments" { const alloc = std.testing.allocator; const u = try Uri.parse(alloc, "HTTP://User@Example.COM:80/a/./b/../c/"); defer u.deinit(); const n = try u.normalize(alloc, .{}); defer n.deinit(); try expectEqualStrings("http", n.scheme.?); try expectEqualStrings("example.com", n.host.?.hostname); // Userinfo is case-sensitive and must survive untouched. try expectEqualStrings("User", n.username.?); try expectEqualDeep(@as([]const []const u8, &.{ "a", "c", "" }), n.path); try expectEqual(@as(?u16, 80), n.port); const dropped = try u.normalize(alloc, .{ .drop_default_port = true }); defer dropped.deinit(); try expectEqual(@as(?u16, null), dropped.port); } test "normalize: a path that resolves away to nothing" { const alloc = std.testing.allocator; const relative = try Uri.parse(alloc, "a/..?q"); defer relative.deinit(); const n = try relative.normalize(alloc, .{}); defer n.deinit(); try expectEqual(@as(usize, 0), n.path.len); const text = try n.toText(alloc, .{}); defer alloc.free(text); try expectEqualStrings("?q", text); // A rooted path keeps the empty segment: it is the `/`. const rooted = try Uri.parse(alloc, "/a/.."); defer rooted.deinit(); const rn = try rooted.normalize(alloc, .{}); defer rn.deinit(); try expectEqualDeep(@as([]const []const u8, &.{""}), rn.path); const rooted_text = try rn.toText(alloc, .{}); defer alloc.free(rooted_text); try expectEqualStrings("/", rooted_text); } test "normalize: a resolved path that begins with an empty segment" { const alloc = std.testing.allocator; // Writing this used to be an assertion failure: dot-segment removal left // `//x`, which no reference without an authority can be written as. const u = try Uri.parse(alloc, ".///x"); defer u.deinit(); const n = try u.normalize(alloc, .{}); defer n.deinit(); try expect(n.rooted); try expectEqualDeep(@as([]const []const u8, &.{"x"}), n.path); const text = try n.toText(alloc, .{}); defer alloc.free(text); try expectEqualStrings("/x", text); } test "normalize: rooting an empty path" { const alloc = std.testing.allocator; // RFC 3986 §6.2.3: with an authority, an empty path is equivalent to `/`. for ([_][2][]const u8{ .{ "http://example.io", "http://example.io/" }, .{ "http://example.io?q", "http://example.io/?q" }, .{ "http://example.io#f", "http://example.io/#f" }, .{ "//example.io", "//example.io/" }, // Already rooted, so there is nothing to do. .{ "http://example.io/", "http://example.io/" }, .{ "http://example.io/a", "http://example.io/a" }, // No authority for the `/` to follow. .{ "mailto:me@example.com", "mailto:me@example.com" }, .{ "urn:oasis:member:A00024:x", "urn:oasis:member:A00024:x" }, }) |c| { const u = try Uri.parse(alloc, c[0]); defer u.deinit(); const n = try u.normalize(alloc, .{ .root_empty_path = true }); defer n.deinit(); const text = try n.toText(alloc, .{}); defer alloc.free(text); expectEqualStrings(c[1], text) catch |err| { std.debug.print("\nnormalizing {s}\n", .{c[0]}); return err; }; } // Off by default: it is scheme-based normalization, not syntax-based. const u = try Uri.parse(alloc, "http://example.io"); defer u.deinit(); const n = try u.normalize(alloc, .{}); defer n.deinit(); const text = try n.toText(alloc, .{}); defer alloc.free(text); try expectEqualStrings("http://example.io", text); // With it on, the two spellings compare equal, which is the point. const rooted = try Uri.parse(alloc, "http://example.io/"); defer rooted.deinit(); const a = try u.normalize(alloc, .{ .root_empty_path = true }); defer a.deinit(); const b = try rooted.normalize(alloc, .{ .root_empty_path = true }); defer b.deinit(); try expect(a.eql(b)); try expectEqual(a.hash(), b.hash()); } test "normalize: an address literal keeps its case" { const alloc = std.testing.allocator; const u = try Uri.parse(alloc, "http://[1080:0:0:0:8:800:200C:417A]/"); defer u.deinit(); const n = try u.normalize(alloc, .{}); defer n.deinit(); try expectEqualStrings("1080:0:0:0:8:800:200C:417A", n.host.?.ipv6); } // -- query ----------------------------------------------------------------- test "query: get, first and has" { const alloc = std.testing.allocator; const u = try Uri.parse(alloc, "http://x/?a=1&b&a=2&a"); defer u.deinit(); const all = try u.get(alloc, "a"); defer alloc.free(all); try expectEqualDeep(@as([]const ?[]const u8, &.{ "1", "2", null }), all); try expectEqualDeep(@as(?QueryParam, .{ .key = "a", .value = "1" }), u.first("a")); // `last` is the other end of the same list: "a" appears three times, and // the final one is the bare `?a`. try expectEqualDeep(@as(?QueryParam, .{ .key = "a", .value = null }), u.last("a")); // A bare key is not the same as an empty value. try expectEqualDeep(@as(?QueryParam, .{ .key = "b", .value = null }), u.first("b")); // With a single occurrence, first and last agree. try expectEqualDeep(u.first("b"), u.last("b")); try expect(u.has("b")); try expect(!u.has("c")); try expectEqual(@as(?QueryParam, null), u.first("c")); try expectEqual(@as(?QueryParam, null), u.last("c")); const none = try u.get(alloc, "zzz"); defer alloc.free(none); try expectEqual(@as(usize, 0), none.len); } test "query: first and last pick opposite ends" { const alloc = std.testing.allocator; const u = try Uri.parse(alloc, "http://x/?a=1&b=2&a=3&a=4"); defer u.deinit(); try expectEqualStrings("1", u.first("a").?.value.?); try expectEqualStrings("4", u.last("a").?.value.?); // Both agree with the corresponding end of `get`. const all = try u.get(alloc, "a"); defer alloc.free(all); try expectEqual(@as(usize, 3), all.len); try expectEqualStrings(all[0].?, u.first("a").?.value.?); try expectEqualStrings(all[all.len - 1].?, u.last("a").?.value.?); // An empty query has neither. const bare = try Uri.parse(alloc, "http://x/"); defer bare.deinit(); try expectEqual(@as(?QueryParam, null), bare.first("a")); try expectEqual(@as(?QueryParam, null), bare.last("a")); } test "query: add, set and remove" { const alloc = std.testing.allocator; const u = try Uri.parse(alloc, "http://x/?a=1&b=2&a=3"); defer u.deinit(); { const got = try u.add(alloc, "a", "4"); defer got.deinit(); const text = try got.toText(alloc, .{}); defer alloc.free(text); try expectEqualStrings("http://x/?a=1&b=2&a=3&a=4", text); } { // `set` collapses duplicates but keeps the original position. const got = try u.set(alloc, "a", "9"); defer got.deinit(); const text = try got.toText(alloc, .{}); defer alloc.free(text); try expectEqualStrings("http://x/?a=9&b=2", text); } { const got = try u.set(alloc, "c", "3"); defer got.deinit(); const text = try got.toText(alloc, .{}); defer alloc.free(text); try expectEqualStrings("http://x/?a=1&b=2&a=3&c=3", text); } { const got = try u.set(alloc, "b", null); defer got.deinit(); const text = try got.toText(alloc, .{}); defer alloc.free(text); try expectEqualStrings("http://x/?a=1&b&a=3", text); } { const got = try u.remove(alloc, "a"); defer got.deinit(); const text = try got.toText(alloc, .{}); defer alloc.free(text); try expectEqualStrings("http://x/?b=2", text); } { const got = try u.removeWhere(alloc, "a", null, 1); defer got.deinit(); const text = try got.toText(alloc, .{}); defer alloc.free(text); try expectEqualStrings("http://x/?b=2&a=3", text); } { const got = try u.removeWhere(alloc, "a", @as(?[]const u8, "3"), null); defer got.deinit(); const text = try got.toText(alloc, .{}); defer alloc.free(text); try expectEqualStrings("http://x/?a=1&b=2", text); } { // Removing every parameter drops the `?` too. const one = try Uri.parse(alloc, "http://x/?a=1"); defer one.deinit(); const got = try one.remove(alloc, "a"); defer got.deinit(); const text = try got.toText(alloc, .{}); defer alloc.free(text); try expectEqualStrings("http://x/", text); } } // -- text output ----------------------------------------------------------- test "toText: the password is withheld unless asked for" { const alloc = std.testing.allocator; const u = try Uri.parse(alloc, "https://user:hunter2@example.com/"); defer u.deinit(); const hidden = try u.toText(alloc, .{}); defer alloc.free(hidden); try expectEqualStrings("https://user:@example.com/", hidden); const shown = try u.toText(alloc, .{ .with_password = true }); defer alloc.free(shown); try expectEqualStrings("https://user:hunter2@example.com/", shown); // `{f}` formatting withholds it too, so a stray log line cannot leak it. const formatted = try std.fmt.allocPrint(alloc, "{f}", .{u}); defer alloc.free(formatted); try expectEqualStrings("https://user:@example.com/", formatted); } test "authority" { const alloc = std.testing.allocator; const u = try Uri.parse(alloc, "https://user:pw@example.com:8443/x"); defer u.deinit(); const hidden = try u.authority(alloc, .{}); defer alloc.free(hidden); try expectEqualStrings("user:@example.com:8443", hidden); const shown = try u.authority(alloc, .{ .with_password = true }); defer alloc.free(shown); try expectEqualStrings("user:pw@example.com:8443", shown); const relative = try Uri.parse(alloc, "a/b"); defer relative.deinit(); const empty = try relative.authority(alloc, .{}); defer alloc.free(empty); try expectEqualStrings("", empty); } test "toText: `//` is written only for a real authority" { const alloc = std.testing.allocator; const Pair = struct { []const u8, []const u8 }; for ([_]Pair{ // No authority, so no `//` is invented — writing `http:///foo` here // would come back with an empty host instead of no host at all. .{ "http:/foo", "http:/foo" }, .{ "http:", "http:" }, .{ "unknownscheme:foo", "unknownscheme:foo" }, .{ "mailto:a@b.example", "mailto:a@b.example" }, .{ "urn:x:y", "urn:x:y" }, // An empty authority is preserved when it was actually there. .{ "file:///etc/passwd", "file:///etc/passwd" }, .{ "http://", "http://" }, }) |c| { const u = try Uri.parse(alloc, c[0]); defer u.deinit(); const text = try u.toText(alloc, .{}); defer alloc.free(text); try expectEqualStrings(c[1], text); } } // -- construction from components ----------------------------------------- test "init: builds from loose components" { const alloc = std.testing.allocator; const u = try Uri.init(alloc, .{ .scheme = "https", .host = .{ .hostname = "example.com" }, .rooted = true, .path = &.{ "a b", "c" }, .query = &.{.{ .key = "k", .value = "v" }}, .fragment = "top", }); defer u.deinit(); const text = try u.toText(alloc, .{}); defer alloc.free(text); try expectEqualStrings("https://example.com/a%20b/c?k=v#top", text); } test "init and clone deep-copy their input" { const alloc = std.testing.allocator; var scheme_buf = [_]u8{ 'h', 't', 't', 'p' }; const u = try Uri.init(alloc, .{ .scheme = &scheme_buf, .host = .{ .hostname = "example.com" }, }); defer u.deinit(); @memset(&scheme_buf, 'x'); try expectEqualStrings("http", u.scheme.?); const copy = try u.clone(alloc); defer copy.deinit(); try expect(u.eql(copy)); try expectEqual(u.hash(), copy.hash()); } // -- scheme metadata ------------------------------------------------------- test "default ports match IANA and the defining RFCs" { // Spot-checks of the entries where the scheme name and the IANA service // name diverge, or where the value was wrong before being verified. // See the provenance notes at the top of schemes.zig. const Port = struct { []const u8, u16 }; for ([_]Port{ // Corrected: 111 is the sunrpc portmapper, not NFS (RFC 2224 §3). .{ "nfs", 2049 }, // Corrected: rtspu shares rtsp's port and differs only in transport // (RFC 2326 §3.2); 5005 is IANA's avt-profile-2. .{ "rtspu", 554 }, .{ "rtsp", 554 }, .{ "rtsps", 322 }, // Right despite an IANA service of the same name sitting elsewhere. .{ "sftp", 22 }, // IANA sftp is 115, a different protocol .{ "prospero", 1525 }, // IANA prospero is 191; 1525 is prospero-np .{ "ventrilo", 3784 }, // convention; IANA 3784 is bfd-control // Right, but filed by IANA under another service name. .{ "afp", 548 }, // afpovertcp .{ "dns", 53 }, // domain .{ "ircs", 6697 }, // ircs-u .{ "mms", 1755 }, // ms-streaming .{ "pop", 110 }, // pop3 .{ "smb", 445 }, // microsoft-ds .{ "vnc", 5900 }, // rfb .{ "wais", 210 }, // z39.50 .{ "ws", 80 }, // http (RFC 6455 §3) .{ "wss", 443 }, // https (RFC 6455 §3) }) |c| { expectEqual(@as(?u16, c[1]), uri.defaultPort(c[0])) catch |err| { std.debug.print("\ndefault port for scheme '{s}'\n", .{c[0]}); return err; }; } } test "scheme metadata" { const alloc = std.testing.allocator; // Scheme names are case-insensitive (RFC 3986 §3.1). try expectEqual(@as(?u16, 443), uri.defaultPort("https")); try expectEqual(@as(?u16, 443), uri.defaultPort("HTTPS")); try expectEqual(@as(?u16, 443), uri.defaultPort("HtTpS")); try expect(!uri.usesNetloc("mailto")); try expect(!uri.usesNetloc("MAILTO")); try expect(!uri.usesNetloc("MaIlTo")); // An unknown scheme misses whatever its length, and a shorter string must // not match a longer entry by prefix. try expectEqual(@as(?u16, null), uri.defaultPort("nonesuch")); try expectEqual(@as(?u16, null), uri.defaultPort("a" ** 64)); try expectEqual(@as(?u16, null), uri.defaultPort("")); try expectEqual(@as(?u16, null), uri.defaultPort("htt")); try expectEqual(@as(?u16, null), uri.defaultPort("https2")); try expect(uri.usesNetloc("http")); try expect(uri.usesNetloc("nonesuch")); try expect(uri.usesNetloc("mail")); const u = try Uri.parse(alloc, "http://example.com/"); defer u.deinit(); try expectEqual(@as(?u16, null), u.port); try expectEqual(@as(?u16, 80), u.defaultPort()); try expectEqual(@as(?u16, 80), u.effectivePort()); try expect(u.usesNetloc()); try expect(u.isAbsolute()); const explicit = try Uri.parse(alloc, "http://example.com:8080/"); defer explicit.deinit(); try expectEqual(@as(?u16, 8080), explicit.effectivePort()); const relative = try Uri.parse(alloc, "/a/b"); defer relative.deinit(); try expect(!relative.isAbsolute()); try expect(!relative.usesNetloc()); try expectEqual(@as(?u16, null), relative.effectivePort()); } // -- percent-encoding primitives ------------------------------------------ test "percent: encode and decode" { const alloc = std.testing.allocator; const decoded = try uri.percentDecode(alloc, "a%2Fb%20c%c3%a9", false); defer alloc.free(decoded); try expectEqualStrings("a/b cé", decoded); const encoded = try uri.percent.encodeAlloc(alloc, "a/b cé", &uri.percent.segment); defer alloc.free(encoded); try expectEqualStrings("a%2Fb%20c%C3%A9", encoded); // No escapes at all is the common case and must be exact. const plain = try uri.percentDecode(alloc, "abc", false); defer alloc.free(plain); try expectEqualStrings("abc", plain); // Decoding produces bytes, not text: a lone %FF is legal and not UTF-8. const raw = try uri.percentDecode(alloc, "%FF", false); defer alloc.free(raw); try expectEqualDeep(@as([]const u8, &.{0xFF}), raw); } test "eql: distinguishes what the syntax distinguishes" { const alloc = std.testing.allocator; const Pair = struct { []const u8, []const u8, bool }; for ([_]Pair{ // Different spellings of the same components compare equal. .{ "http://x/%41", "http://x/A", true }, .{ "http://x/a%2fb", "http://x/a%2Fb", true }, // These genuinely differ. .{ "http://x/a%2Fb", "http://x/a/b", false }, .{ "http://x/?a", "http://x/?a=", false }, .{ "http://x/", "http://x", false }, .{ "http://x/#", "http://x/", false }, .{ "http://x:80/", "http://x/", false }, }) |c| { const a = try Uri.parse(alloc, c[0]); defer a.deinit(); const b = try Uri.parse(alloc, c[1]); defer b.deinit(); expectEqual(c[2], a.eql(b)) catch |err| { std.debug.print("\ncomparing {s} and {s}\n", .{ c[0], c[1] }); return err; }; if (c[2]) try expectEqual(a.hash(), b.hash()); } } // -- round-trip stability -------------------------------------------------- test "round-trip is stable for delimiter-heavy input" { const alloc = std.testing.allocator; // A deliberately hostile alphabet: every structural delimiter, the // characters that are sub-delims, percent signs, and some non-ASCII. const alphabet = "aZ0:/?#[]@!$&'()*+,;=%.-_~ \x7f\xc3\xa9\xff"; var prng = std.Random.DefaultPrng.init(0x5eed); const rand = prng.random(); var buf: [40]u8 = undefined; var parsed: usize = 0; for (0..20_000) |_| { const len = rand.uintLessThan(usize, buf.len); for (buf[0..len]) |*c| c.* = alphabet[rand.uintLessThan(usize, alphabet.len)]; const text = buf[0..len]; const a = Uri.parse(alloc, text) catch continue; defer a.deinit(); parsed += 1; const once = try a.toText(alloc, .{ .with_password = true }); defer alloc.free(once); const b = Uri.parse(alloc, once) catch |err| { std.debug.print("\nre-parsing {s} (from {s}) failed\n", .{ once, text }); return err; }; defer b.deinit(); // Writing must not lose or invent anything... expect(a.eql(b)) catch |err| { std.debug.print("\ncomponents changed: {s} -> {s}\n", .{ text, once }); return err; }; try expectEqual(a.hash(), b.hash()); // ...and must be a fixed point, not merely convergent. const twice = try b.toText(alloc, .{ .with_password = true }); defer alloc.free(twice); expectEqualStrings(once, twice) catch |err| { std.debug.print("\nunstable output from: {s}\n", .{text}); return err; }; } // Guard against the alphabet drifting into something that never parses. try expect(parsed > 10_000); }