validation

package
v1.4.4 Latest Latest
Warning

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

Go to latest
Published: May 17, 2026 License: MIT Imports: 6 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     = 255  // Maximum credential length (username/password)
	MaxTokenLen    = 2048 // Maximum bearer token length
	MaxKeyLen      = 256  // Maximum query parameter key length
	MaxValueLen    = 8192 // Maximum query parameter value length
	MaxFilenameLen = 256  // Maximum filename length for uploads

	MaxCookieNameLen   = 256
	MaxCookieValueLen  = 4096
	MaxCookieDomainLen = 255
	MaxCookiePathLen   = 1024

	MaxHeaderKeyLen   = 256
	MaxHeaderValueLen = 8192
)

Common validation constants

Variables

This section is empty.

Functions

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 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 IsIPExempted added in v1.4.0

func IsIPExempted(ip net.IP, nets []*net.IPNet) bool

IsIPExempted checks if an IP address matches any of the exempt CIDR ranges.

func IsLocalhost added in v1.3.8

func IsLocalhost(hostname string) bool

IsLocalhost detects localhost variations including: - "localhost" (case-insensitive) - 127.0.0.1 - ::1 - 0.0.0.0 - :: - 127.x.x.x range - localhost.* subdomains (case-insensitive)

Optimized to avoid repeated string allocations from strings.ToLower.

func IsPrivateOrReservedIP added in v1.3.8

func IsPrivateOrReservedIP(ip net.IP) bool

IsPrivateOrReservedIP checks if an IP address is private, reserved, or otherwise not suitable for public internet communication. This is used for SSRF (Server-Side Request Forgery) protection.

SECURITY: This function handles IPv4-mapped IPv6 addresses (::ffff:x.x.x.x) to prevent bypass attempts using mixed notation.

func IsSensitiveQueryParam added in v1.4.0

func IsSensitiveQueryParam(name string) bool

IsSensitiveQueryParam reports whether the given query parameter name is considered sensitive and should be redacted from logs and cache keys.

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 ParseExemptCIDRs added in v1.4.0

func ParseExemptCIDRs(cidrs []string) ([]*net.IPNet, error)

ParseExemptCIDRs parses a list of CIDR strings into net.IPNet slices. Returns nil, nil for empty input.

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].

Returns the original string if the URL cannot be parsed.

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 SensitiveQueryParamNames added in v1.4.2

func SensitiveQueryParamNames() map[string]bool

SensitiveQueryParamNames returns the set of sensitive query parameter names. Used internally to check URLs for sensitive content without importing the map directly.

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 ValidateCookieName

func ValidateCookieName(name string) error

ValidateCookieName validates HTTP cookie names.

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.

func ValidateCookieValue

func ValidateCookieValue(value string) error

ValidateCookieValue validates HTTP cookie values.

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.

func ValidateIP added in v1.3.8

func ValidateIP(ip net.IP) error

ValidateIP checks if an IP is allowed for outbound requests. Returns an error if the IP is blocked by security policy.

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 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, resolveDNS bool) 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 optionally resolves DNS for domain names. Returns nil if the host is allowed, or an error describing why it was blocked.

func ValidateToken

func ValidateToken(token string) error

ValidateToken validates bearer tokens according to RFC 6750.

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