Skip to content

High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.

fix: seven URL spellings skip the SSRF guard entirely, and the protocol-relative one is a live regression (PIN-282)

Luigi Agosti1d906d661ae1
diff --git a/internal/handlers/navigation_host_forms_test.go b/internal/handlers/navigation_host_forms_test.go
index 91e28c37..4354f928 100644
--- a/internal/handlers/navigation_host_forms_test.go
+++ b/internal/handlers/navigation_host_forms_test.go
@@ -93,3 +93,41 @@ func TestAnUnlistedSingleLabelHostIsRefusedNamingTheAllowlist(t *testing.T) {
t.Errorf("remedy = %q; it does not name the host the caller must list", got)
}
}
+
+// Both navigate paths apply urls.EnsureScheme before the same validation, so a fix
+// landing on one and not the other leaves the bypass reachable. They are driven
+// against the same table here rather than trusted to share it.
+//
+// IDPI is OFF in this fixture, and deliberately: with IDPI enabled and NO allowlist
+// configured, ShieldGuard.DomainAllowed answers true for every URL (nothing scored,
+// so nothing blocked), that becomes allowExplicitInternal, and the private-IP block
+// is overridden before the spelling ever matters. That is a separate defect, recorded
+// on the card; turning IDPI off here is what lets this test measure the spelling
+// property it is about rather than that one.
+func TestBothNavigatePathsRefuseEverySpellingOfAPrivateHost(t *testing.T) {
+ cfg := hostFormConfig(nil)
+ cfg.IDPI = config.IDPIConfig{}
+ h := New(&policyMockBridge{}, cfg, nil, nil, nil)
+
+ for _, raw := range []string{
+ `https://10.0.0.5/x`,
+ `https:\\10.0.0.5\x`,
+ `https:/10.0.0.5/x`,
+ `https:\/10.0.0.5\x`,
+ `https:////10.0.0.5/x`,
+ `//10.0.0.5/x`,
+ `https:10.0.0.5/x`,
+ `/10.0.0.5/x`,
+ } {
+ t.Run(raw, func(t *testing.T) {
+ w := httptest.NewRecorder()
+ if _, ok := h.validateNavigateTargets(w, httptest.NewRequest("GET", "/navigate", nil), "", raw, h.Config); ok {
+ t.Errorf("navigate path ALLOWED a private address written as %q", raw)
+ }
+
+ if _, err := h.validateAuditTarget(raw, h.Config); err == nil {
+ t.Errorf("audit-page path ALLOWED a private address written as %q; the two share the normalization and must share the verdict", raw)
+ }
+ })
+ }
+}
diff --git a/internal/navguard/authority_browser_differential_test.go b/internal/navguard/authority_browser_differential_test.go
new file mode 100644
index 00000000..f9bfd677
--- /dev/null
+++ b/internal/navguard/authority_browser_differential_test.go
@@ -0,0 +1,131 @@
+package navguard
+
+import (
+ "context"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/chromedp/chromedp"
+ "github.com/pinchtab/pinchtab/internal/security"
+ "github.com/pinchtab/pinchtab/internal/testbrowser"
+ "github.com/pinchtab/pinchtab/internal/urls"
+)
+
+// The differential this card turns on: the guard's host and the BROWSER's host for
+// the same string. They disagreed for every slash-and-backslash spelling, and the
+// disagreement is the vulnerability — a guard that reads no host does not check, and
+// a browser that reads one navigates. This drives a real Chrome at each spelling and
+// asserts the request the browser actually made names the host the guard extracted,
+// so a future parser change on either side reds here instead of drifting unmeasured.
+//
+// CI has no browser, so this skips there; TestTheGuardAgreesWithTheRecordedBrowserAnswers
+// is its browserless twin over the same generated table.
+func TestTheBrowserResolvesTheHostTheGuardExtracts(t *testing.T) {
+ chromePath := testbrowser.Path(t)
+
+ var mu sync.Mutex
+ requested := map[string]bool{}
+ srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ mu.Lock()
+ requested[r.Host+r.URL.Path] = true
+ mu.Unlock()
+ w.Header().Set("Content-Type", "text/html")
+ _, _ = w.Write([]byte("<h1>ok</h1>"))
+ }))
+ defer srv.Close()
+
+ // A TLS server so every generated spelling can use one scheme: the scheme-less
+ // rows normalize to https://, and a plain-http server would fail those on TLS
+ // rather than on the parser question this test is about.
+ authority := strings.TrimPrefix(srv.URL, "https://")
+
+ alloc, cancelAlloc := chromedp.NewExecAllocator(context.Background(), append(
+ chromedp.DefaultExecAllocatorOptions[:],
+ chromedp.ExecPath(chromePath),
+ chromedp.UserDataDir(testbrowser.ProfileDir(t)),
+ chromedp.Flag("headless", true),
+ chromedp.Flag("no-sandbox", true),
+ chromedp.Flag("ignore-certificate-errors", true),
+ )...)
+ ctx, cancelBrowser := chromedp.NewContext(alloc)
+ ctx, cancelTimeout := context.WithTimeout(ctx, 120*time.Second)
+ t.Cleanup(func() {
+ cancelTimeout()
+ cancelBrowser()
+ cancelAlloc()
+ })
+
+ for _, spelling := range authoritySpellings(authority + "/probe") {
+ t.Run(spelling.raw, func(t *testing.T) {
+ mu.Lock()
+ requested = map[string]bool{}
+ mu.Unlock()
+
+ // The browser is handed what PinchTab hands it: validateNavigateTargets
+ // normalizes and navigates the normalized target, so that is the string
+ // whose browser answer has to match the guard's.
+ navigated := urls.EnsureScheme(spelling.raw)
+ if err := chromedp.Run(ctx, chromedp.Navigate(navigated)); err != nil {
+ t.Fatalf("navigate %q (from %q, %s): %v", navigated, spelling.raw, spelling.note, err)
+ }
+
+ mu.Lock()
+ reached := requested[authority+"/probe"]
+ mu.Unlock()
+
+ host := security.ExtractHost(spelling.raw)
+ if !reached {
+ t.Fatalf("the browser did not reach the probe for %q (from %q, %s)", navigated, spelling.raw, spelling.note)
+ }
+ if host != "127.0.0.1" {
+ t.Errorf("the browser resolved this and reached the server, but the guard extracted host %q (%s) — a host the guard cannot read is a check it does not run", host, spelling.note)
+ }
+ })
+ }
+}
+
+// The browserless twin, recording what the browser answered so the rule is checkable
+// where no browser runs: every generated spelling of a special-scheme authority names
+// the same host to the guard as the correctly-spelled form does.
+func TestTheGuardAgreesWithTheRecordedBrowserAnswers(t *testing.T) {
+ for _, spelling := range authoritySpellings("127.0.0.1:9999/probe") {
+ t.Run(spelling.raw, func(t *testing.T) {
+ if host := security.ExtractHost(spelling.raw); host != "127.0.0.1" {
+ t.Errorf("host = %q, want 127.0.0.1 (%s) — the browser reaches this authority, so the guard must read it too", host, spelling.note)
+ }
+ })
+ }
+}
+
+// Measured, not assumed: a raw protocol-relative string is not navigable through CDP
+// at all — Page.navigate needs an absolute URL and has no base to resolve one
+// against. So the protocol-relative bypass never ran through Chrome's parser; it ran
+// through PinchTab's own normalization, which turned "//10.0.0.5/x" into the
+// scheme-ful "https:////10.0.0.5/x" that Chrome does navigate and the guard read as
+// hostless. That is why the fix belongs in the normaliser.
+func TestARawProtocolRelativeTargetIsNotNavigableWithoutABase(t *testing.T) {
+ chromePath := testbrowser.Path(t)
+
+ alloc, cancelAlloc := chromedp.NewExecAllocator(context.Background(), append(
+ chromedp.DefaultExecAllocatorOptions[:],
+ chromedp.ExecPath(chromePath),
+ chromedp.UserDataDir(testbrowser.ProfileDir(t)),
+ chromedp.Flag("headless", true),
+ chromedp.Flag("no-sandbox", true),
+ )...)
+ ctx, cancelBrowser := chromedp.NewContext(alloc)
+ ctx, cancelTimeout := context.WithTimeout(ctx, 30*time.Second)
+ t.Cleanup(func() {
+ cancelTimeout()
+ cancelBrowser()
+ cancelAlloc()
+ })
+
+ if err := chromedp.Run(ctx, chromedp.Navigate("//127.0.0.1:9/probe")); err == nil {
+ t.Error("a raw protocol-relative target navigated; the note above about where the bypass came from is wrong and should be corrected")
+ }
+}
diff --git a/internal/navguard/authority_spellings_test.go b/internal/navguard/authority_spellings_test.go
new file mode 100644
index 00000000..cf259c06
--- /dev/null
+++ b/internal/navguard/authority_spellings_test.go
@@ -0,0 +1,155 @@
+package navguard
+
+import (
+ "context"
+ "fmt"
+ "net"
+ "strings"
+ "testing"
+
+ "github.com/pinchtab/pinchtab/internal/security"
+ "github.com/pinchtab/pinchtab/internal/urls"
+)
+
+// authoritySpelling is one way of writing the same destination. WHATWG's
+// special-authority-ignore-slashes state skips ANY run of "/" and "\" after a
+// special scheme's colon, so the set of spellings is a property of the state
+// machine rather than a list somebody remembered — which is why they are generated.
+type authoritySpelling struct {
+ raw string
+ note string
+}
+
+// authoritySpellings generates every run of "/" and "\" up to length three, after a
+// special scheme's colon and in the scheme-less (protocol-relative) position, plus
+// the backslash-in-path forms a browser reads as slashes.
+func authoritySpellings(hostAndPath string) []authoritySpelling {
+ var runs []string
+ for length := 0; length <= 3; length++ {
+ for mask := 0; mask < 1<<length; mask++ {
+ var run strings.Builder
+ for bit := 0; bit < length; bit++ {
+ if mask&(1<<bit) == 0 {
+ run.WriteByte('/')
+ } else {
+ run.WriteByte('\\')
+ }
+ }
+ runs = append(runs, run.String())
+ }
+ }
+
+ backslashPath := strings.ReplaceAll(hostAndPath, "/", `\`)
+ var out []authoritySpelling
+ for _, run := range runs {
+ out = append(out,
+ authoritySpelling{raw: "https:" + run + hostAndPath, note: fmt.Sprintf("scheme-ful, run %q", run)},
+ authoritySpelling{raw: "https:" + run + backslashPath, note: fmt.Sprintf("scheme-ful with backslash path, run %q", run)},
+ )
+ if run != "" {
+ out = append(out,
+ authoritySpelling{raw: run + hostAndPath, note: fmt.Sprintf("scheme-less, run %q", run)},
+ authoritySpelling{raw: run + backslashPath, note: fmt.Sprintf("scheme-less with backslash path, run %q", run)},
+ )
+ }
+ }
+ return out
+}
+
+// The whole defect: seven spellings of one private address reached it past the SSRF
+// guard the correctly-spelled one is refused by, because Go read them as hostless and
+// a hostless target skipped resolution entirely. Driven through the production
+// sequence — urls.EnsureScheme then ValidateTarget — not against the extractor alone.
+func TestEverySpellingOfAPrivateHostIsRefused(t *testing.T) {
+ stubHostResolution(t, func(context.Context, string, string) ([]net.IP, error) {
+ return []net.IP{net.ParseIP("10.0.0.5")}, nil
+ })
+
+ canonical := "https://10.0.0.5/x"
+ if _, err := ValidateTarget(context.Background(), urls.EnsureScheme(canonical), false, nil); err == nil {
+ t.Fatal("the correctly-spelled private address was allowed; this table compares against it")
+ }
+
+ for _, spelling := range authoritySpellings("10.0.0.5/x") {
+ t.Run(spelling.raw, func(t *testing.T) {
+ normalized := urls.EnsureScheme(spelling.raw)
+ if host := security.ExtractHost(spelling.raw); host != "10.0.0.5" {
+ t.Errorf("host = %q, want 10.0.0.5 (%s): normalized to %q — the guard reads a different host than the browser", host, spelling.note, normalized)
+ }
+ if _, err := ValidateTarget(context.Background(), normalized, false, nil); err == nil {
+ t.Errorf("ALLOWED (%s): normalized to %q — this names a private address the canonical spelling is refused for", spelling.note, normalized)
+ }
+ })
+ }
+}
+
+// The regression named in the card. Before urls.EnsureScheme existed, a
+// protocol-relative target was REFUSED; the normalization prepended a scheme in front
+// of the leading "//" and produced "https:////10.0.0.5/x", which net/url reads as
+// hostless — so the most ordinary spelling of the set became the bypass. It is
+// refused again, and stripping the leading run before prepending is what does it.
+func TestTheProtocolRelativeRegressionIsRefusedAgain(t *testing.T) {
+ stubHostResolution(t, func(context.Context, string, string) ([]net.IP, error) {
+ return []net.IP{net.ParseIP("10.0.0.5")}, nil
+ })
+
+ const raw = "//10.0.0.5/x"
+ if got, want := urls.EnsureScheme(raw), "https://10.0.0.5/x"; got != want {
+ t.Fatalf("EnsureScheme(%q) = %q, want %q; prepending a scheme destroyed the authority the input already had", raw, got, want)
+ }
+ if _, err := ValidateTarget(context.Background(), urls.EnsureScheme(raw), false, nil); err == nil {
+ t.Fatal("a protocol-relative private address was allowed")
+ }
+}
+
+// The other half, and the reason the fix normalises rather than blanket-rejects
+// unusual punctuation: a public host written in any of the same spellings still
+// navigates. A guard that refused all of them would be fail-closed and useless.
+func TestEverySpellingOfAPublicHostStillNavigates(t *testing.T) {
+ stubHostResolution(t, func(context.Context, string, string) ([]net.IP, error) {
+ return []net.IP{net.ParseIP("93.184.216.34")}, nil
+ })
+
+ for _, spelling := range authoritySpellings("example.com/x") {
+ t.Run(spelling.raw, func(t *testing.T) {
+ if _, err := ValidateTarget(context.Background(), urls.EnsureScheme(spelling.raw), false, nil); err != nil {
+ t.Errorf("REFUSED (%s): %v — a legitimate target stopped navigating", spelling.note, err)
+ }
+ })
+ }
+}
+
+// "Cannot check" and "checked and safe" must not share an outcome. This is what
+// keeps the class closed rather than resting on how exactly EnsureScheme mirrors the
+// WHATWG state machine: a target left with no readable host is refused whether or not
+// the normaliser anticipated its spelling.
+func TestATargetWithNoReadableHostIsRefusedRatherThanAllowedUnresolved(t *testing.T) {
+ stubHostResolution(t, func(context.Context, string, string) ([]net.IP, error) {
+ t.Error("a target with no readable host was resolved, which cannot happen")
+ return nil, nil
+ })
+
+ for _, raw := range []string{"https://", "https://?q=1", "https://#frag"} {
+ t.Run(raw, func(t *testing.T) {
+ if _, err := ValidateTarget(context.Background(), raw, false, nil); err == nil {
+ t.Error("a target the guard cannot read a host from was allowed unresolved")
+ }
+ })
+ }
+}
+
+// EnsureScheme must never destroy an authority the input already had: whenever a host
+// is readable from the input, one is readable from its output, and it is the same
+// host. That is the property the protocol-relative regression violated.
+func TestEnsureSchemeNeverDestroysAnAuthority(t *testing.T) {
+ for _, hostAndPath := range []string{"10.0.0.5/x", "example.com/x", "example.com:8443/x"} {
+ for _, spelling := range authoritySpellings(hostAndPath) {
+ t.Run(spelling.raw, func(t *testing.T) {
+ normalized := urls.EnsureScheme(spelling.raw)
+ if security.ExtractHost(normalized) == "" {
+ t.Errorf("EnsureScheme(%q) = %q, from which no host can be read (%s)", spelling.raw, normalized, spelling.note)
+ }
+ })
+ }
+ }
+}
diff --git a/internal/navguard/target.go b/internal/navguard/target.go
index 0ae41336..8086e6b1 100644
--- a/internal/navguard/target.go
+++ b/internal/navguard/target.go
@@ -36,15 +36,24 @@ func ValidateTarget(ctx context.Context, raw string, allowExplicitInternal bool,
// exactly the single-label intranet names it exists for.
host := security.ExtractHost(raw)
if host == "" {
- // No resolvable host means the IP/SSRF checks below can't run, so a
- // caller that relies on ValidateTarget alone would otherwise allow any
- // scheme. Enforce scheme safety here too (defense in depth) so opaque
- // targets like file:/data: are rejected regardless of caller ordering;
- // scheme-less/relative inputs and about:blank still pass ValidateURL.
+ // "Cannot check" must not share an outcome with "checked and safe". This
+ // branch used to return success: no resolution, no private-IP check. Go and
+ // the browser disagree about where an authority begins, so a target the
+ // browser resolves and this cannot read was permitted unchecked — which is
+ // how every slash-and-backslash spelling of a private address got past the
+ // SSRF guard the correctly-spelled one is refused by.
+ //
+ // urls.EnsureScheme now collapses those spellings, so the browser's host and
+ // this one agree and nothing reaches here that the browser would navigate.
+ // The refusal is what keeps that a closed class rather than a claim about
+ // how exactly this mirrors the WHATWG state machine: anything left with no
+ // readable host is refused whether or not the normaliser anticipated it.
+ //
+ // The scheme check runs first so an unsafe scheme is still named as one.
if err := ValidateURL(raw); err != nil {
return nil, err
}
- return &ValidatedTarget{}, nil
+ return nil, fmt.Errorf("navigation target has no readable host")
}
if netguard.IsLocalHost(host) {
return &ValidatedTarget{AllowInternal: true}, nil
diff --git a/internal/urls/urls.go b/internal/urls/urls.go
index 7793ce5d..107e57e3 100644
--- a/internal/urls/urls.go
+++ b/internal/urls/urls.go
@@ -7,12 +7,17 @@ import (
"strings"
)
-// Normalize adds https:// if no protocol specified. Existing http/https preserved.
+// Normalize adds https:// if no protocol is specified. It is EnsureScheme under
+// another name, kept because the CLI reads better for it.
+//
+// It used to recognise only the literal "http://" and "https://" prefixes, so a
+// target written with any other slash run — "https:/example.com/x",
+// "https:\\example.com\x", "https:example.com/x" — was not recognised as having a
+// scheme at all and got another one prepended in front of it, producing
+// "https://https:/example.com/x", whose host reads as "https". The CLI silently sent
+// the server a different destination than the user typed.
func Normalize(rawURL string) string {
- if strings.HasPrefix(rawURL, "http://") || strings.HasPrefix(rawURL, "https://") {
- return rawURL
- }
- return "https://" + rawURL
+ return EnsureScheme(rawURL)
}
// Sanitize normalizes a URL. Bare hostnames get https:// added.
@@ -46,11 +51,27 @@ func IsValid(rawURL string) bool {
}
// EnsureScheme is the ONE place a scheme-less target acquires one, so no consumer
-// has to hand-roll a bare-URL branch to find the host inside it. url.Parse reads a
-// scheme-less string's leading label as a scheme, which is right for the opaque
-// forms ("about:blank", "data:...", "javascript:...") and wrong for "intranet:8080",
-// where the label is a host and the opaque part is a port — that is the one case
-// this has to tell apart, and a port is what tells it.
+// has to hand-roll a bare-URL branch to find the host inside it.
+//
+// It also has to agree with the BROWSER about where the authority begins, because
+// the guard that decides whether a target is safe reads its answer and Chrome reads
+// its own. WHATWG's special-authority-ignore-slashes state skips any run of "/" and
+// "\" after a special scheme's colon, so "https:\\10.0.0.5\x", "https:/10.0.0.5/x",
+// "https:////10.0.0.5/x" and even "https:10.0.0.5/x" all name the host 10.0.0.5 to a
+// browser — and none of them did to net/url, which read them as hostless. A hostless
+// target skipped resolution and the private-IP check, so those spellings reached a
+// private address the correctly-spelled one is refused for. Collapsing the run is
+// what makes the two parsers agree.
+//
+// The protocol-relative form is the same defect one step earlier: "//10.0.0.5/x" has
+// no scheme, so this used to prepend one and produce "https:////10.0.0.5/x" — the
+// bypass manufactured out of the most ordinary input of the set. Stripping the
+// leading run before prepending is what stops a prepend destroying an authority the
+// input already had.
+//
+// "file" is deliberately not collapsed: its authority rules differ, and
+// "file:///tmp/x" means an empty authority and an absolute path rather than the host
+// "tmp".
//
// https:// is the default a bare host gets. It is the assumption Normalize already
// makes for the CLI and Sanitize for MCP, and it is the safer of the two: a target
@@ -60,6 +81,9 @@ func EnsureScheme(rawURL string) string {
if trimmed == "" {
return trimmed
}
+ if scheme, rest, ok := splitAuthorityScheme(trimmed); ok {
+ return scheme + "://" + browserAuthorityAndPath(rest)
+ }
if strings.Contains(trimmed, "://") {
return trimmed
}
@@ -67,7 +91,61 @@ func EnsureScheme(rawURL string) string {
if err == nil && parsed.Scheme != "" && !opaqueStartsWithPort(parsed.Opaque) {
return trimmed
}
- return "https://" + trimmed
+ return "https://" + browserAuthorityAndPath(trimmed)
+}
+
+// browserAuthorityAndPath rewrites the part of a special-scheme URL that a browser
+// reads with backslashes and slashes interchangeable: the leading run between the
+// colon and the authority is skipped, and every remaining backslash up to the query
+// or fragment is a slash. Query and fragment are left alone — the parser does not
+// remap them either, and rewriting them would change what the page receives.
+func browserAuthorityAndPath(rest string) string {
+ rest = strings.TrimLeft(rest, authoritySlashes)
+ cut := strings.IndexAny(rest, "?#")
+ if cut < 0 {
+ return strings.ReplaceAll(rest, `\`, "/")
+ }
+ return strings.ReplaceAll(rest[:cut], `\`, "/") + rest[cut:]
+}
+
+// authoritySlashes are the two characters WHATWG skips between a special scheme's
+// colon and the authority. A backslash is not a typo the parser rejects — it is a
+// slash for this purpose, which is exactly why the backslash spellings reached a
+// private host past a guard that read them as hostless.
+const authoritySlashes = `/\`
+
+// authorityCollapsingSchemes are WHATWG's special schemes minus "file". Every one of
+// them takes an authority, so anything between its colon and the host is punctuation
+// the browser ignores.
+var authorityCollapsingSchemes = map[string]bool{
+ "http": true, "https": true, "ws": true, "wss": true, "ftp": true,
+}
+
+// splitAuthorityScheme recognises a leading special scheme and returns it with the
+// remainder. The scheme must be a real scheme token, so "./rel://x" is not mistaken
+// for one and left alone rather than rewritten.
+func splitAuthorityScheme(raw string) (scheme, rest string, ok bool) {
+ colon := strings.Index(raw, ":")
+ if colon <= 0 {
+ return "", "", false
+ }
+ candidate := raw[:colon]
+ if !isSchemeToken(candidate) || !authorityCollapsingSchemes[strings.ToLower(candidate)] {
+ return "", "", false
+ }
+ return candidate, raw[colon+1:], true
+}
+
+func isSchemeToken(candidate string) bool {
+ for i, r := range candidate {
+ switch {
+ case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z':
+ case i > 0 && (r >= '0' && r <= '9' || r == '+' || r == '-' || r == '.'):
+ default:
+ return false
+ }
+ }
+ return candidate != ""
}
// opaqueStartsWithPort reports whether an opaque remainder begins with a port —
diff --git a/internal/urls/urls_test.go b/internal/urls/urls_test.go
index 736ad38a..1a1df194 100644
--- a/internal/urls/urls_test.go
+++ b/internal/urls/urls_test.go
@@ -2,6 +2,7 @@ package urls
import (
"fmt"
+ "net/url"
"strings"
"testing"
"unicode/utf8"
@@ -241,3 +242,54 @@ func TestRedactForLogTruncationBoundaries(t *testing.T) {
})
}
}
+
+// The card asks for the CLI and MCP normalizers to be PROBED against the same
+// table rather than assumed safe, and for the verdicts to be recorded. They are
+// recorded here as assertions:
+//
+// - Sanitize (MCP) delegates to EnsureScheme, so it collapses the authority and
+// hands the server a string whose host is readable.
+// - Normalize (CLI) did NOT, and that was worse than a bypass: recognising only
+// the literal "http://" and "https://" prefixes, it prepended a second scheme
+// in front of these spellings and produced "https://https:/10.0.0.5/x", whose
+// host reads as "https" — so the CLI sent the server a destination the user
+// never typed. It now delegates to EnsureScheme, and this pins that.
+func TestTheCLIAndMCPNormalizersAgainstTheAuthorityTable(t *testing.T) {
+ for _, raw := range []string{
+ `https://10.0.0.5/x`,
+ `https:\\10.0.0.5\x`,
+ `https:/10.0.0.5/x`,
+ `https:\/10.0.0.5\x`,
+ `https:////10.0.0.5/x`,
+ `//10.0.0.5/x`,
+ `https:10.0.0.5/x`,
+ `/10.0.0.5/x`,
+ } {
+ t.Run(raw, func(t *testing.T) {
+ if got := EnsureScheme(raw); got != "https://10.0.0.5/x" {
+ t.Errorf("EnsureScheme(%q) = %q, want the collapsed authority", raw, got)
+ }
+
+ sanitized, err := Sanitize(raw)
+ if err != nil {
+ t.Fatalf("Sanitize(%q) error = %v", raw, err)
+ }
+ if host := hostOf(t, sanitized); host != "10.0.0.5" {
+ t.Errorf("Sanitize(%q) = %q, whose host reads as %q — MCP would hand the server a target the guard cannot check", raw, sanitized, host)
+ }
+
+ if host := hostOf(t, Normalize(raw)); host != "10.0.0.5" {
+ t.Errorf("Normalize(%q) = %q, whose host reads as %q — the CLI would send the server a destination the user never typed", raw, Normalize(raw), host)
+ }
+ })
+ }
+}
+
+func hostOf(t *testing.T, rawURL string) string {
+ t.Helper()
+ parsed, err := url.Parse(rawURL)
+ if err != nil {
+ return ""
+ }
+ return parsed.Hostname()
+}