Documentation
¶
Overview ¶
Package security provides HTTP middleware for NornicDB security validation.
Package security provides security validation utilities for NornicDB.
Index ¶
- Constants
- Variables
- func AbsCanonicalFilePath(path string) (string, error)
- func EnsureRootedParent(path string, perm os.FileMode) error
- func IsRestrictedIP(ip net.IP, policy IPPolicy) bool
- func KeyedDigest(ctx context.Context, namespace string, parts ...string) ([32]byte, error)
- func KeyedDigestHex(ctx context.Context, namespace string, parts ...string) (string, error)
- func ParseURL(rawURL string) (*url.URL, error)
- func ReadRootedDir(path string) ([]os.DirEntry, error)
- func RemoveAllRootedPath(path string) error
- func RemoveRootedPath(path string) error
- func RenameRootedFile(oldPath, newPath string) error
- func RootedStat(path string) (os.FileInfo, error)
- func SanitizeString(input string) string
- func ValidateHeaderValue(value string) error
- func ValidateToken(token string) error
- func ValidateURL(rawURL string, policy URLPolicy) error
- func WriteRootedFile(path string, data []byte, perm os.FileMode) error
- type IPPolicy
- type RootedFile
- type SecurityConfig
- type SecurityMiddleware
- type URLHostPolicy
- type URLPolicy
- type URLSchemePolicy
Constants ¶
const ( MaxTokenLength = 8192 MaxURLLength = 2048 MaxHeaderLength = 4096 )
Variables ¶
var ( ErrTokenInvalidChars = fmt.Errorf("token contains invalid characters (possible injection attack)") ErrTokenTooLong = fmt.Errorf("token exceeds maximum length of %d characters", MaxTokenLength) ErrTokenEmpty = fmt.Errorf("token must be a non-empty string") ErrURLInvalidProtocol = fmt.Errorf("only HTTP/HTTPS protocols are allowed") ErrURLPrivateIP = fmt.Errorf("private IP addresses are not allowed") ErrURLLocalhost = fmt.Errorf("localhost is not allowed in production") ErrURLHTTPNotAllowed = fmt.Errorf("only HTTPS URLs are allowed in production") ErrURLTooLong = fmt.Errorf("URL exceeds maximum length of %d characters", MaxURLLength) ErrURLInvalid = fmt.Errorf("invalid URL format") )
Functions ¶
func AbsCanonicalFilePath ¶
AbsCanonicalFilePath applies the rooted-file path validation before resolving a path against the working directory. Validating the supplied spelling first prevents filepath.Abs from cleaning away rejected traversal components.
func EnsureRootedParent ¶ added in v1.2.1
EnsureRootedParent creates the parent directory of a canonical path through an os.Root capability.
func IsRestrictedIP ¶
IsRestrictedIP is the one owner of IP address restriction. ValidateURL asks it about a URL's literal host with the zero policy; APOC asks it about every resolved and every dialled address with RejectMulticast and RejectUnspecified enabled.
The zero policy refuses loopback, private and link-local addresses: IPv4 10/8, 172.16/12, 192.168/16 and 169.254/16, and IPv6 fc00::/7 and fe80::/10. An IPv4-mapped IPv6 address is judged by its IPv4 address. A nil or malformed address is not restricted here; a consumer that must not use an unjudgeable address rejects it before asking this question.
func KeyedDigest ¶ added in v1.2.1
KeyedDigest returns a deterministic process-local HMAC-SHA256 digest for the supplied namespace and parts. The namespace provides domain separation so the same value used in different contexts does not yield the same digest. Every namespace and part is length-prefixed with its 8-byte big-endian length, so different part boundaries never produce the same digest.
Parts are hashed in bounded chunks. ctx is checked before the digest starts, before each part's length prefix, and before each chunk is converted to bytes and hashed. When ctx is cancelled or its deadline passes, KeyedDigest stops and returns ctx.Err() with the zero digest.
A digest reuses one bounded chunk buffer for all of its chunks and parts, and allocates it only when a part is long enough to need chunking, so a large input is never converted to bytes in one piece and a small one never allocates the buffer.
The digest is only meaningful within the current process: the key is random per process. KeyedDigest requires a non-nil ctx, as usual for Go APIs that accept a context.
Example:
digest, err := security.KeyedDigest(ctx, "auth.basic.header", r.Header.Get("Authorization"))
if err != nil {
return err
}
if digest == deniedDigest {
return ErrDenied
}
func KeyedDigestHex ¶ added in v1.2.1
KeyedDigestHex is the hex-encoded form of KeyedDigest. It returns an empty string and ctx.Err() when the context is cancelled or its deadline passes.
func ParseURL ¶
ParseURL parses URL syntax and safely renders parse failures. It imposes no protocol, hostname or network policy; ValidateURL applies the selected consumer contract in its required order.
func ReadRootedDir ¶ added in v1.2.1
ReadRootedDir reads a canonical directory through an os.Root capability.
func RemoveAllRootedPath ¶ added in v1.2.1
RemoveAllRootedPath removes a canonical path through an os.Root capability.
func RemoveRootedPath ¶ added in v1.2.1
RemoveRootedPath removes a canonical file or empty directory through an os.Root capability.
func RenameRootedFile ¶ added in v1.2.1
RenameRootedFile atomically renames canonical paths in the same directory through a single os.Root capability.
func RootedStat ¶ added in v1.2.1
RootedStat returns information about a canonical path through an os.Root capability.
func SanitizeString ¶
SanitizeString removes dangerous characters from user input.
func ValidateHeaderValue ¶
ValidateHeaderValue validates HTTP header values to prevent injection attacks.
func ValidateToken ¶
ValidateToken validates OAuth/API token format to prevent injection attacks.
func ValidateURL ¶
ValidateURL is the shared ordered URL validation owner. Security configuration rejects private literal addresses; eval separately requires all DNS answers to be loopback unless remote evaluation is enabled. The zero policy retains production defaults; callers explicitly select other contracts rather than relying on mode booleans or compatibility wrappers.
Types ¶
type IPPolicy ¶
type IPPolicy struct {
// RejectMulticast refuses multicast destination addresses.
RejectMulticast bool
// RejectUnspecified refuses unspecified addresses such as 0.0.0.0 and ::.
RejectUnspecified bool
}
IPPolicy selects the additional address classes a consumer refuses. The zero policy is the literal-address rule ValidateURL applies. Multicast and unspecified addresses are separate flags because they stay permitted for a consumer that never rejected them; enabling a flag only adds its class.
type RootedFile ¶ added in v1.2.1
RootedFile retains the root capability for the lifetime of an open file.
func CreateRootedFile ¶ added in v1.2.1
func CreateRootedFile(path string, perm os.FileMode) (*RootedFile, error)
CreateRootedFile creates or truncates a canonical path through os.Root.
func OpenRootedFile ¶ added in v1.2.1
OpenRootedFile opens a canonical file path through an os.Root rooted at its parent directory. Traversal components and paths whose cleaned form differs from the supplied path are rejected before any filesystem operation.
func (*RootedFile) Close ¶ added in v1.2.1
func (f *RootedFile) Close() error
Close closes both the file and its root capability.
type SecurityConfig ¶
type SecurityConfig struct {
Environment string // "development", "production"
AllowHTTP bool // Allow non-TLS connections
}
SecurityConfig holds security middleware configuration. This is passed from the main config to avoid direct env var access.
type SecurityMiddleware ¶
type SecurityMiddleware struct {
// contains filtered or unexported fields
}
SecurityMiddleware wraps HTTP handlers with security validations.
func NewSecurityMiddleware ¶
func NewSecurityMiddleware() *SecurityMiddleware
NewSecurityMiddleware creates a new security middleware instance. Use NewSecurityMiddlewareWithConfig for production code.
func NewSecurityMiddlewareWithConfig ¶
func NewSecurityMiddlewareWithConfig(cfg SecurityConfig) *SecurityMiddleware
NewSecurityMiddlewareWithConfig creates a security middleware with explicit config.
func (*SecurityMiddleware) SetLocalizer ¶ added in v1.3.1
func (m *SecurityMiddleware) SetLocalizer(manager *localization.Manager)
SetLocalizer sets the immutable message catalog used for HTTP errors.
func (*SecurityMiddleware) ValidateRequest ¶
func (m *SecurityMiddleware) ValidateRequest(next http.Handler) http.Handler
ValidateRequest performs comprehensive security validation on incoming requests.
type URLHostPolicy ¶
type URLHostPolicy uint8
URLHostPolicy identifies an existing consumer's host access contract.
const ( URLProductionHost URLHostPolicy = iota URLDevelopmentHost URLResolvedLoopback URLAnyHost )
type URLPolicy ¶
type URLPolicy struct {
SchemePolicy URLSchemePolicy
RejectCredentials bool
MaxLength int
AllowHTTP bool
RejectUserinfo bool
HostPolicy URLHostPolicy
HostRejected func(string) error
}
URLPolicy selects a consumer's URL access contract. Its zero value applies production host restrictions, HTTPS, and MaxURLLength. A negative MaxLength explicitly disables the length bound; HostRejected preserves consumer errors.
type URLSchemePolicy ¶
type URLSchemePolicy uint8
URLSchemePolicy selects the existing consumer's URL syntax contract.
const ( URLHTTPScheme URLSchemePolicy = iota // URLAbsoluteScheme accepts any absolute scheme with an authority, as OAuth issuer configuration requires. URLAbsoluteScheme )