validation

package
v1.7.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 24, 2026 License: MIT Imports: 13 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package validation provides input sanitization and validation utilities for credentials, headers, cookies, URLs, and network addresses.

Index

Constants

View Source
const (
	// MaxCredLen is the maximum allowed length for credentials (username/password).
	MaxCredLen = 255
	// MaxTokenLen is the maximum allowed length for bearer tokens.
	MaxTokenLen = 2048
	// MaxKeyLen is the maximum allowed length for query parameter keys.
	MaxKeyLen = 256
	// MaxValueLen is the maximum allowed length for query parameter values.
	MaxValueLen = 8192
	// MaxFilenameLen is the maximum allowed filename length for file uploads.
	MaxFilenameLen = 256

	// MaxCookieNameLen is the maximum allowed length for cookie names.
	MaxCookieNameLen = 256
	// MaxCookieValueLen is the maximum allowed length for cookie values.
	MaxCookieValueLen = 4096
	// MaxCookieDomainLen is the maximum allowed length for cookie domains.
	MaxCookieDomainLen = 255
	// MaxCookiePathLen is the maximum allowed length for cookie paths.
	MaxCookiePathLen = 1024

	// MaxHeaderKeyLen is the maximum allowed length for HTTP header keys.
	MaxHeaderKeyLen = 256
	// MaxHeaderValueLen is the maximum allowed length for HTTP header values.
	MaxHeaderValueLen = 8192
)

Validation length limits for credentials, query parameters, cookies, headers, and filenames used across the validation package.

Variables

This section is empty.

Functions

func ASCIILower added in v1.7.0

func ASCIILower(s string) string

ASCIILower converts ASCII uppercase letters to lowercase in-place using a stack-allocated buffer, avoiding the heap allocation strings.ToLower incurs for typical short parameter names. Exported so the security package's domain whitelist can reuse it instead of carrying its own identical copy.

func CanonicalProxyAddr added in v1.6.3

func CanonicalProxyAddr(u *url.URL) string

CanonicalProxyAddr returns the host:port form of a proxy URL as net/http will actually DIAL it. net/http's transport dials canonicalAddr(proxyURL) — the URL hostname with the scheme's default port appended when the URL omits one — so any comparison against the dial address (proxy SSRF exemptions, proxypool health-report keys) must use this canonical form, not url.Host. Before this existed, a portless entry like "socks5://internal-proxy" was keyed as "internal-proxy" while the dialer saw "internal-proxy:1080": the proxy SSRF exemption silently never applied and circuit-breaking failure counts never incremented.

Non-ASCII (IDN) hostnames are punycoded exactly as net/http does at dial time (idna.Lookup.ToASCII, left unchanged on conversion failure), so an IDN proxy URL matches the dialed form with or without an explicit port.

func ContainsFold added in v1.4.4

func ContainsFold(s, substr string) bool

ContainsFold reports whether substr is contained within s, ASCII case-insensitively. Zero-allocation alternative to strings.Contains(strings.ToLower(s), substr).

func EffectivePort added in v1.7.1

func EffectivePort(u *url.URL) string

EffectivePort returns u's explicit port, or the scheme's default when the URL omits one. Schemes are matched case-insensitively (url.Parse already lowercases the scheme; the fold is belt-and-braces for hand-built URLs). A URL with neither port nor a recognized scheme has no effective port and matches only the same degenerate form — engines only route http/https (ws/wss included for the transports that speak them), so the "" default is unreachable through validated requests and exists to fail closed on the exotic forms rather than lump them onto port 80.

func EqualFold added in v1.4.4

func EqualFold(s, t string) bool

EqualFold checks if s equals t case-insensitively (ASCII only). Avoids allocation from strings.ToLower.

func FilterAllowedIPs added in v1.4.1

func FilterAllowedIPs(ips []net.IP, exemptNets []*net.IPNet) []net.IP

FilterAllowedIPs filters a list of IPs to only those allowed under SSRF rules. Private/reserved IPs are excluded unless they match an exempt CIDR range. Returns nil slice when no IPs are allowed. This supports Split-Horizon DNS environments where a domain may resolve to both public and private IPs — only public (or exempted) IPs are used for dialing.

func HasSensitiveQueryParams added in v1.5.0

func HasSensitiveQueryParams(query string) bool

HasSensitiveQueryParams checks if any key-value pair in the query string has a sensitive parameter name. Uses byte-level ASCII lowercase to avoid allocations from strings.ToLower. HasSensitiveQueryParams reports whether any parameter key in the raw query string looks sensitive. Parsing is segment-based (&-split, then strip the value after '=') so it matches redactSensitiveParams exactly: a bare key without '=' is still treated as a key. ';' splits segments alongside '&' (see redactSensitiveParams for why legacy separators must count).

func IsASCII added in v1.7.1

func IsASCII(s string) bool

IsASCII reports whether s consists solely of ASCII bytes. Exported next to ASCIILower so the security package's IDNA pre-checks can share this predicate instead of carrying an identical private copy: the two gate the same normalization family (proxy addresses, redirect-whitelist domains) and must never diverge.

func IsValidHeaderString added in v1.3.8

func IsValidHeaderString(s string) bool

IsValidHeaderString checks if a string contains only valid characters for HTTP headers. It returns true if the string contains no control characters (except tab), DEL, or CR/LF. Optimized to use byte-level checks instead of rune iteration.

func ParseSystemProxyURL added in v1.7.1

func ParseSystemProxyURL(raw string) (*url.URL, error)

ParseSystemProxyURL parses a proxy address obtained from system sources — environment variables (HTTP_PROXY/HTTPS_PROXY) and platform settings (Windows registry, macOS networksetup). It is the system-detection counterpart of ValidateProxyURL and the single normalization point for those sources: the environment and registry paths previously carried two hand-maintained variants of these rules, and their drift made an uppercase-scheme registry value silently disable the system proxy.

Normalization applied before validation:

  • "" (or whitespace) returns (nil, nil): "no value configured" is not an error at the system-detection layer.
  • A bare "socks" scheme is mapped to "socks5" — net/http recognizes socks5/socks5h but not "socks://".
  • A bare host:port ("proxy:3128", the dominant registry/env spelling, which parses with the hostname in the scheme position) gets an "http://" prefix.

Everything else — including uppercase schemes, which url.Parse lowercases — is validated by ValidateProxyURL unchanged, inheriting its scheme allow-list, host requirement, and credential redaction.

func RedactURLInMessage added in v1.7.2

func RedactURLInMessage(msg, rawURL string) (string, bool)

RedactURLInMessage replaces every occurrence of rawURL in msg with its sanitized form, matching BOTH the raw spelling and the strconv.Quote-escaped one. The quote form matters because net/url renders *url.Error (and parse errors) with %q — a URL containing a character %q escapes (", \, control characters) reaches the message in ESCAPED form, so a plain substring match misses it and the credential or sensitive query value the redaction exists to scrub leaks through verbatim (escaped, but readable). Reports whether anything was redacted; msg is returned unchanged when the URL has nothing to sanitize or does not appear in either form.

Single implementation shared by validation.redactErrorURL and the engine's redactURLInError so the two cannot drift apart again.

func ResolveFilteredIPs added in v1.7.1

func ResolveFilteredIPs(ctx context.Context, host string, exemptNets []*net.IPNet, dialTimeout time.Duration, lookup func(context.Context, string) ([]net.IPAddr, error)) ([]net.IP, error)

ResolveFilteredIPs is the single implementation of the SSRF resolve-and-filter rule, shared by every enforcement layer: the standard dial path and the proxied-target pre-check (internal/connection/pool.go), the fingerprint pre-flight (internal/fingerprint/ssrf.go), and the fingerprint validating dialer (internal/fingerprint/directdial.go). The four hand-maintained copies it replaced had already drifted in timeout derivation and error text; a filter-rule change now applies everywhere at once.

It resolves host via lookup (nil means net.DefaultResolver; tests substitute a seam) under the shared DNS timeout policy — capped at 10s, tightened to dialTimeout when dialTimeout is positive and smaller — and returns the resolved IPs that survive FilterAllowedIPs. Resolution errors are returned unwrapped so each layer keeps its own error prefix; an empty allowed set is NOT an error here (each layer reports it with its own message, some after further processing the IPs).

func SameOrigin added in v1.7.1

func SameOrigin(a, b *url.URL) bool

SameOrigin reports whether two URLs share an origin per RFC 6454: scheme, host, and effective port, with scheme-default ports normalized ("example.com" and "example.com:80" under http are one origin; "example.com:8080" is not). It is the single canonical implementation shared by the engine's redirect credential-stripping and the fingerprint path's sec-fetch-site computation — the two previously carried private copies whose semantics had drifted apart.

func SanitizeURL added in v1.3.9

func SanitizeURL(urlStr string) string

SanitizeURL removes credentials and redacts sensitive query parameters from a URL for safe logging. URLs with credentials are transformed from user:pass@host to ***:***@host. Sensitive query parameters (token, api_key, password, etc.) have their values replaced with [REDACTED].

SECURITY: this function must FAIL CLOSED. It exists to keep credentials out of logs and error messages, so an input that url.Parse rejects — or parses into an opaque form that hides userinfo — is best-effort redacted by redactUnparseableURL instead of being returned verbatim (returning the raw string would leak user:pass@... precisely on the malformed inputs most likely to come from untrusted sources).

This function is used to prevent credential leakage in:

  • Log messages
  • Error messages
  • Audit events
  • Debug output

Example:

SanitizeURL("https://user:pass@example.com/path?token=secret")
// Returns "https://***:***@example.com/path?token=[REDACTED]"

func ValidateAndParseURL added in v1.4.1

func ValidateAndParseURL(urlStr string) (*url.URL, error)

ValidateAndParseURL validates a URL and returns the parsed result. This avoids callers needing to parse the URL again after validation.

func ValidateCookie added in v1.3.7

func ValidateCookie(cookie *http.Cookie) error

ValidateCookie performs comprehensive validation of an HTTP cookie including name, value, domain, and path attributes.

func ValidateCookieSecurity added in v1.3.8

func ValidateCookieSecurity(cookie *http.Cookie, config *CookieSecurityConfig) error

ValidateCookieSecurity validates a cookie against the security configuration. Returns an error if the cookie does not meet the security requirements. This is the standard validation for general use.

SECURITY: a nil config is a caller error, not "no requirements" — a security gate must not silently pass open. Callers that want optional enforcement nil-check the config themselves before calling (as every in-repo caller does: SessionManager.validateCookieSecurity, httpc.WithSecureCookie). The zero-value CookieSecurityConfig (non-nil, all flags false) is the legitimate "no requirements" policy.

func ValidateCredential

func ValidateCredential(cred string, maxLen int, checkColon bool, credType string) error

ValidateCredential validates credentials for Basic Auth.

func ValidateFieldName

func ValidateFieldName(name string, fieldType string) error

ValidateFieldName validates form field names and filenames. It checks for dangerous characters and path traversal patterns to prevent directory traversal attacks and injection vulnerabilities.

func ValidateHeaderKeyValue

func ValidateHeaderKeyValue(key, value string) error

ValidateHeaderKeyValue validates HTTP header keys and values.

Byte-level fast path: the generic validateInputString walks the key as runes and calls a per-character closure, which costs ~35% of this function's time (measured: 220ns → 138ns for a six-header request) on a path that runs for every header of every validated request. The loop and the value check below produce byte-identical results and error messages to that generic form:

  • the empty/too-long checks mirror validateInputString's guards;
  • a byte >= 0x80 fails the ASCII-only header-key table, so any non-ASCII rune (whose UTF-8 lead byte is >= 0x80) is rejected, exactly like the generic per-rune form would;
  • bytes < 0x20 or == 0x7F are rejected first, so the table lookup only runs for printable ASCII (the table itself marks them invalid, so the ordering only affects which message is produced, not the outcome).

func ValidateIPWithExemptions added in v1.4.0

func ValidateIPWithExemptions(ip net.IP, exemptNets []*net.IPNet) error

ValidateIPWithExemptions checks if an IP is allowed, considering exempt CIDR ranges. IPs that are private/reserved but match an exempt CIDR are allowed.

func ValidateMultipartToken added in v1.6.3

func ValidateMultipartToken(s, what string) error

ValidateMultipartToken validates a token (form field name or filename) that will be embedded in a Content-Disposition quoted-string at the multipart encoding sink (engine request building). It rejects control characters — the bytes that can break out of the quoted string and inject additional MIME headers (CR/LF) or corrupt the part stream — plus excessive length.

Unlike ValidateFieldName (the stricter option-layer policy applied by WithFile), characters such as '/', '&', or non-ASCII remain legal here: they cannot escape a quoted-string parameter value because the encoder backslash-escapes '"' and '\', and the multipart writer quotes every value. Every path that encodes a *FormData must call this so the validation cannot be bypassed by constructing FormData directly instead of via WithFile.

func ValidateProxyURL added in v1.5.3

func ValidateProxyURL(rawURL string) (*url.URL, error)

ValidateProxyURL parses and validates a proxy URL string, returning the parsed URL so callers do not need to re-parse.

Accepted schemes: http, https, socks5, socks5h. The socks5 schemes are supported natively by net/http.Transport when set via transport.Proxy = http.ProxyURL(u), so they must not be rejected here.

This is the single source of truth for proxy URL validation, shared by the public Config validator (ValidateConfig) and the internal connection pool (NewPoolManager). Centralizing it prevents the two layers from drifting — which is what previously let the public layer accept socks5 while the pool rejected it with a different error.

func ValidateQueryKey

func ValidateQueryKey(key string) error

ValidateQueryKey validates query parameter keys.

func ValidateSSRFHost added in v1.4.1

func ValidateSSRFHost(host string, exemptNets []*net.IPNet) error

ValidateSSRFHost checks whether a hostname (which may include a port) should be blocked under SSRF protection rules. It checks localhost, direct IP addresses, and legacy IP-literal notation. Returns nil if the host is allowed, or an error describing why it was blocked.

DNS resolution of hostnames is deliberately NOT performed here: the connection pool dialer (internal/connection) resolves once, validates every IP, and dials the validated IP directly, which also prevents DNS-rebinding TOCTOU attacks a pre-check could not.

func ValidateToken

func ValidateToken(token string) error

ValidateToken validates bearer tokens according to RFC 6750.

func ValidatedCandidates added in v1.7.3

func ValidatedCandidates(ctx context.Context, addr string, exemptNets []*net.IPNet, dialTimeout time.Duration, lookup func(context.Context, string) ([]net.IPAddr, error)) ([]string, error)

ValidatedCandidates turns "host:port" into SSRF-validated "ip:port" dial candidates: an IP literal validates directly (no DNS, no rebinding window); a hostname resolves once through the shared resolve-and-filter rule (ResolveFilteredIPs) and every allowed address becomes a candidate so callers can fail over IPv6→IPv4. Single owner of the split → validate → candidate-join sequence the standard dialer, its DoH variant, and the fingerprint validating dialer previously maintained as three hand-synced copies — copies that had already drifted (the pool assumed port 443 for addresses without a port; the fingerprint path failed closed).

Fail-closed: an address without a port is an error. Guessing a port would dial the wrong service; both httpc dial paths receive host:port from the transport, so a portless address is a caller bug worth an error, not a silent 443 that dials the wrong port for any non-TLS target.

Error shapes (callers add their own prefixes): a policy-rejected IP returns ValidateIPWithExemptions's error verbatim; a DNS failure is wrapped as "DNS resolution failed for <host>"; an empty allowed set reports the shared "resolves only to blocked addresses" message.

Types

type CookieSecurityConfig added in v1.3.8

type CookieSecurityConfig struct {
	// RequireSecure requires the Secure attribute to be set.
	// Secure cookies are only sent over HTTPS connections.
	// Recommended: true for production environments.
	RequireSecure bool

	// RequireHttpOnly requires the HttpOnly attribute to be set.
	// HttpOnly cookies cannot be accessed via JavaScript, preventing XSS attacks.
	// Recommended: true for session cookies.
	RequireHttpOnly bool

	// RequireSameSite requires a specific SameSite attribute.
	// Valid values: "Strict", "Lax", "None", "" (empty means no requirement).
	// - Strict: Cookie only sent in first-party context (most secure)
	// - Lax: Cookie sent in first-party context and top-level navigations
	// - None: Cookie sent in all contexts (requires Secure)
	RequireSameSite string

	// AllowSameSiteNone allows SameSite=None attribute.
	// This is useful for cross-site cookies but reduces security.
	// If false and RequireSameSite is empty, cookies with SameSite=None are rejected.
	// Recommended: false for high-security applications.
	AllowSameSiteNone bool

	// RequireSecureForSameSiteNone requires the Secure attribute when
	// SameSite=None. Modern browsers reject SameSite=None without Secure,
	// so this catches misconfigured cookies early. Default: true.
	RequireSecureForSameSiteNone bool
}

CookieSecurityConfig defines the security requirements for cookies. This is used to enforce security attributes like Secure, HttpOnly, and SameSite to protect against CSRF, XSS, and session hijacking attacks.

func DefaultCookieSecurityConfig added in v1.3.8

func DefaultCookieSecurityConfig() *CookieSecurityConfig

DefaultCookieSecurityConfig returns a recommended security configuration. This provides a good balance between security and compatibility.

func StrictCookieSecurityConfig added in v1.3.8

func StrictCookieSecurityConfig() *CookieSecurityConfig

StrictCookieSecurityConfig returns a strict security configuration. Use this for high-security applications (financial, medical, government).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL