Validate Redirects With URL.ResolveReference

Resolve relative, protocol-relative, and external redirect strings against a base net/url.URL, then enforce same-scheme and same-host checks.

GoSecurity Boundaries

Code

snippet
package main

import (
	"fmt"
	"net/url"
)

func safeRedirect(base *url.URL, rawTarget string) (string, bool) {
	ref, err := url.Parse(rawTarget)
	if err != nil {
		return "", false
	}
	resolved := base.ResolveReference(ref)
	sameOrigin := resolved.Scheme == base.Scheme && resolved.Host == base.Host
	return resolved.String(), sameOrigin
}

func main() {
	base, err := url.Parse("https://app.example.org/account/profile")
	if err != nil {
		fmt.Println("invalid base:", err)
		return
	}

	targets := []string{
		"settings",
		"/billing?plan=pro",
		"//evil.example.net/steal",
		"https://other.example.org/login",
	}
	for _, target := range targets {
		dest, ok := safeRedirect(base, target)
		fmt.Printf("%-32s allowed=%-5t resolved=%s\n", target, ok, dest)
	}
}

Code mechanics — Validate Redirects With URL.ResolveReference

Inspect the flow starting from routines safeRedirect and main, doing all the work.

The cycling part of this snippet is for _, target := range targets. Error handling is inline: 2 places test err != nil and branch immediately.

What to watch for

  • Only the core language runtime is required — zero third-party installs.

Applying it

The entry-point signature is func safeRedirect(base *url.URL, rawTarget string) (string, bool)

The run prints invalid base: — each prefix names the step that produced it.

Launch the file; main takes over and steps through safeRedirect.

Statements that matter

func safeRedirect(base *url.URL, rawTarget string) (string, bool) {
	ref, err := url.Parse(rawTarget)
	if err != nil {
		return "", false
	}
	resolved := base.ResolveReference(ref)
	sameOrigin := resolved.Scheme == base.Scheme && resolved.Host == base.Host
	return resolved.String(), sameOrigin
}
for _, target := range targets {
	dest, ok := safeRedirect(base, target)
	fmt.Printf("%-32s allowed=%-5t resolved=%s\n", target, ok, dest)
}
if err != nil {
	fmt.Println("invalid base:", err)
	return
}

Interactive Tools for This Topic

FAQ

What does Validate Redirects With URL.ResolveReference print when run?
Invoke the file as-is — the `invalid base:` prefixes identify which step printed each line.