security

package
v1.5.2-hotfix Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2026 License: MIT Imports: 18 Imported by: 1 module, 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.

README

NornicDB Security Validation

This package provides comprehensive security validation for NornicDB HTTP endpoints, protecting against:

  • CSRF (Cross-Site Request Forgery) attacks
  • SSRF (Server-Side Request Forgery) attacks
  • HTTP Header Injection attacks
  • XSS (Cross-Site Scripting) attacks
  • Protocol Smuggling attacks
  • Data URI Injection attacks

Features

1. Token Validation (ValidateToken)

Validates OAuth/API tokens to prevent injection attacks:

import "github.com/orneryd/nornicdb/pkg/security"

token := "eyJhbGciOiJIUzI1NiIs..."
if err := security.ValidateToken(token); err != nil {
    return fmt.Errorf("invalid token: %w", err)
}

Protects against:

  • HTTP header injection (CRLF, newlines)
  • XSS attacks (HTML tags, JavaScript)
  • Protocol injection (javascript:, data:, file:)
  • DoS attacks (excessively long tokens > 8192 bytes)
  • String termination attacks (null bytes)

Test Coverage: 13 injection attack scenarios

2. URL Validation (ValidateURL)

Validates URLs to prevent SSRF attacks. The policy is passed explicitly:

// Production policy (strict, secure default = zero value)
err := security.ValidateURL(callbackURL, security.URLPolicy{})

// Development policy (allows loopback hosts and HTTP for local workflows)
err := security.ValidateURL(localURL, security.URLPolicy{
    AllowHTTP:  true,
    HostPolicy: security.URLDevelopmentHost,
})

Protects against:

  • SSRF to private IP ranges (10.0.0.0/8, 192.168.0.0/16, 172.16.0.0/12)
  • SSRF to cloud metadata services (169.254.169.254)
  • SSRF to localhost (127.0.0.0/8) in production
  • Protocol smuggling (file://, gopher://, dict://)
  • HTTP downgrade attacks (requires HTTPS in production)

Test Coverage: 15+ SSRF attack scenarios including AWS/Azure/GCP metadata services

Go helper migration

ValidateURL(url, isDevelopment, allowHTTP) now takes ValidateURL(url, policy). The zero value URLPolicy{} preserves production defaults: HTTPS, localhost and private literal-IP restrictions, and the 2048-byte MaxURLLength bound.

Previous call Replacement
security.ValidateURL(u, false, false) security.ValidateURL(u, security.URLPolicy{})
security.ValidateURL(u, false, true) security.ValidateURL(u, security.URLPolicy{AllowHTTP: true})
security.ValidateURL(u, true, false) security.ValidateURL(u, security.URLPolicy{AllowHTTP: true, HostPolicy: security.URLDevelopmentHost})
security.ValidateURL(u, true, true) security.ValidateURL(u, security.URLPolicy{AllowHTTP: true, HostPolicy: security.URLDevelopmentHost})

Policy fields select these contracts:

  • HostPolicy: URLProductionHost is the default; URLDevelopmentHost allows loopback but rejects other private literal IPs; URLResolvedLoopback requires every DNS answer to be loopback; URLAnyHost explicitly permits any host.
  • MaxLength: zero uses MaxURLLength, positive values set a limit, and negative values explicitly disable it. Eval uses -1 to preserve its long-URL behavior.
  • SchemePolicy defaults to URLHTTPScheme. OAuth issuer consumers explicitly select URLAbsoluteScheme to retain their absolute-URL contract.
  • RejectCredentials rejects userinfo and credential-bearing query/fragment values; OAuth issuer callers select this policy with URLAnyHost and MaxLength: -1.
  • AllowHTTP permits HTTP; RejectUserinfo rejects URL userinfo when selected. Unset RejectUserinfo preserves the previous userinfo allowance.
3. Header Validation (ValidateHeaderValue)

Validates HTTP header values to prevent injection:

if err := security.ValidateHeaderValue(userAgent); err != nil {
    return fmt.Errorf("invalid header: %w", err)
}

Protects against:

  • HTTP header injection (CRLF)
  • HTTP response splitting
  • Null byte injection
  • Excessively long headers (> 4096 bytes)
4. Security Middleware

Automatically applies all validations to HTTP endpoints:

import (
    "net/http"
    "github.com/orneryd/nornicdb/pkg/security"
)

func main() {
    middleware := security.NewSecurityMiddleware()

    // Wrap individual handler
    http.Handle("/api/query", middleware.Wrap(queryHandler))

    // Or wrap entire mux
    mux := http.NewServeMux()
    mux.HandleFunc("/api/query", queryHandler)

    http.ListenAndServe(":7474", middleware.ValidateRequest(mux))
}

Automatically validates:

  • All HTTP header values
  • Authorization tokens (Bearer/Basic)
  • Query parameter tokens (for SSE/WebSocket)
  • URL parameters (callback, redirect, redirect_uri, url, webhook)

Environment Variables

  • NORNICDB_ENV or NODE_ENV: Set to development to allow localhost URLs
  • NORNICDB_ALLOW_HTTP: Set to true to allow HTTP URLs in production (not recommended)

Mapping to TypeScript Tests

This implementation provides equivalent protection to the TypeScript security tests:

CSRF Protection (csrf-protection.test.ts)

While the TypeScript tests focus on OAuth state management, NornicDB's security layer protects against CSRF through:

  1. Token validation - prevents forged/injected tokens
  2. State parameter validation - validates callback URLs (SSRF prevention)
  3. Header injection prevention - blocks CRLF attacks that could bypass CSRF checks

Example equivalent protection:

// TypeScript: SecureStateStore validates OAuth state parameters
// Go: SecurityMiddleware validates all tokens and URLs

middleware := security.NewSecurityMiddleware()
http.Handle("/oauth/callback", middleware.Wrap(oauthCallbackHandler))
SSRF Protection (ssrf-protection.test.ts)

Direct 1:1 mapping of all SSRF protections:

TypeScript Test Go Implementation Coverage
validateOAuthTokenFormat() ValidateToken() ✅ 100%
validateOAuthUserinfoUrl() ValidateURL() ✅ 100%
createSecureFetchOptions() SecurityMiddleware ✅ 100%
IP restriction IsRestrictedIP() ✅ All ranges
Cloud metadata blocking ValidateURL() ✅ AWS/Azure/GCP
Protocol smuggling ValidateURL() ✅ file://, gopher://, etc.
Test Scenarios Covered

All attack scenarios from the TypeScript tests are covered:

Token Injection:

  • ✅ CRLF injection (token\r\nX-Malicious: header)
  • ✅ HTML injection (<script>alert('xss')</script>)
  • ✅ JavaScript protocol (javascript:alert('xss'))
  • ✅ Data URI (data:text/html,<script>...)
  • ✅ File protocol (file:///etc/passwd)
  • ✅ Null byte injection (token\x00evil)

SSRF Attacks:

  • ✅ Private IP ranges (10.x, 192.168.x, 172.16-31.x)
  • ✅ AWS metadata (http://169.254.169.254/latest/meta-data/)
  • ✅ Azure metadata (http://169.254.169.254/metadata/instance)
  • ✅ GCP metadata (http://169.254.169.254/computeMetadata/)
  • ✅ Internal network scanning
  • ✅ Localhost access in production

Protocol Smuggling:

  • ✅ file:// protocol
  • ✅ ftp:// protocol
  • ✅ gopher:// protocol
  • ✅ dict:// protocol

Testing

Run all security tests:

cd nornicdb
go test -v ./pkg/security/...

Run with coverage:

go test -cover ./pkg/security/...

Benchmark performance:

go test -bench=. ./pkg/security/...

Usage Examples

Protecting OAuth Endpoints
func setupOAuthServer() {
    middleware := security.NewSecurityMiddleware()

    // OAuth authorization endpoint
    http.Handle("/oauth/authorize", middleware.Wrap(
        http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            // redirect_uri is automatically validated by middleware
            redirectURI := r.URL.Query().Get("redirect_uri")
            // ... OAuth flow
        }),
    ))

    // OAuth callback endpoint
    http.Handle("/oauth/callback", middleware.Wrap(oauthCallbackHandler))
}
Protecting API Endpoints
func setupAPIServer() {
    middleware := security.NewSecurityMiddleware()

    mux := http.NewServeMux()
    mux.HandleFunc("/api/query", queryHandler)
    mux.HandleFunc("/api/import", importHandler)
    mux.HandleFunc("/api/export", exportHandler)

    // All endpoints protected
    http.ListenAndServe(":7474", middleware.ValidateRequest(mux))
}
Manual Validation
func handleWebhook(w http.ResponseWriter, r *http.Request) {
    webhookURL := r.URL.Query().Get("callback")

    // Validate before making outbound request (zero value = production policy)
    if err := security.ValidateURL(webhookURL, security.URLPolicy{}); err != nil {
        http.Error(w, "Invalid webhook URL", http.StatusBadRequest)
        return
    }

    // Safe to make request
    resp, err := http.Post(webhookURL, "application/json", payload)
    // ...
}

Security Best Practices

  1. Always use HTTPS in production - set NORNICDB_ENV=production
  2. Never disable validations - they prevent real attacks
  3. Use middleware globally - protect all endpoints by default
  4. Validate before external requests - check all user-provided URLs
  5. Log security violations - monitor for attack attempts
  6. Keep dependencies updated - security fixes are critical

Performance

All validations are optimized for production use:

  • Token validation: ~1-2 µs per call
  • URL validation: ~5-10 µs per call
  • Header validation: ~0.5-1 µs per call

Negligible overhead for comprehensive protection.

References

Documentation

Overview

Package security provides HTTP middleware for NornicDB security validation.

Package security provides security validation utilities for NornicDB.

Index

Constants

View Source
const (
	MaxTokenLength  = 8192
	MaxURLLength    = 2048
	MaxHeaderLength = 4096
)

Variables

View Source
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

func AbsCanonicalFilePath(path string) (string, error)

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

func EnsureRootedParent(path string, perm os.FileMode) error

EnsureRootedParent creates the parent directory of a canonical path through an os.Root capability.

func IsRestrictedIP

func IsRestrictedIP(ip net.IP, policy IPPolicy) bool

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

func KeyedDigest(ctx context.Context, namespace string, parts ...string) ([32]byte, error)

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

func KeyedDigestHex(ctx context.Context, namespace string, parts ...string) (string, error)

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

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

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

func ReadRootedDir(path string) ([]os.DirEntry, error)

ReadRootedDir reads a canonical directory through an os.Root capability.

func RemoveAllRootedPath added in v1.2.1

func RemoveAllRootedPath(path string) error

RemoveAllRootedPath removes a canonical path through an os.Root capability.

func RemoveRootedPath added in v1.2.1

func RemoveRootedPath(path string) error

RemoveRootedPath removes a canonical file or empty directory through an os.Root capability.

func RenameRootedFile added in v1.2.1

func RenameRootedFile(oldPath, newPath string) error

RenameRootedFile atomically renames canonical paths in the same directory through a single os.Root capability.

func RootedStat added in v1.2.1

func RootedStat(path string) (os.FileInfo, error)

RootedStat returns information about a canonical path through an os.Root capability.

func SanitizeString

func SanitizeString(input string) string

SanitizeString removes dangerous characters from user input.

func ValidateHeaderValue

func ValidateHeaderValue(value string) error

ValidateHeaderValue validates HTTP header values to prevent injection attacks.

func ValidateToken

func ValidateToken(token string) error

ValidateToken validates OAuth/API token format to prevent injection attacks.

func ValidateURL

func ValidateURL(rawURL string, policy URLPolicy) error

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.

func WriteRootedFile added in v1.2.1

func WriteRootedFile(path string, data []byte, perm os.FileMode) error

WriteRootedFile writes data to a canonical path through os.Root.

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

type RootedFile struct {
	*os.File
	// contains filtered or unexported fields
}

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

func OpenRootedFile(path string, flag int, perm os.FileMode) (*RootedFile, error)

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.

func (*SecurityMiddleware) Wrap

func (m *SecurityMiddleware) Wrap(handler http.Handler) http.Handler

Wrap is a convenience method for wrapping individual handlers.

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
)

Jump to

Keyboard shortcuts

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