security

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Mar 7, 2026 License: MIT Imports: 8 Imported by: 0

Documentation

Overview

Package security provides path safety checks and HTTP security middleware for the static web server.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNullByte indicates the URL path contained a null byte.
	ErrNullByte = errors.New("path contains null byte")
	// ErrPathTraversal indicates the resolved path escapes the root directory.
	ErrPathTraversal = errors.New("path traversal detected")
	// ErrDotfile indicates a path component starts with '.' and dotfiles are blocked.
	ErrDotfile = errors.New("dotfile access denied")
)

Sentinel errors returned by PathSafe.

Functions

func Middleware

func Middleware(cfg *config.SecurityConfig, root string, next http.Handler) http.Handler

Middleware returns an http.Handler that validates the request path and sets security response headers before delegating to next. It returns 400 for null bytes, 403 for path traversal and dotfile attempts, and 405 for disallowed HTTP methods.

absRoot is computed once at construction time (via filepath.Abs + filepath.EvalSymlinks) and reused for every request, eliminating the per-request syscall overhead. The resolved safe path is stored in the request context so downstream handlers can retrieve it with SafePathFromContext instead of calling PathSafe a second time.

func PathSafe

func PathSafe(urlPath, absRoot string, blockDotfiles bool) (string, error)

PathSafe validates and resolves urlPath relative to absRoot. absRoot must already be an absolute, cleaned path (use filepath.Abs once at startup). The function performs the following checks in order:

  1. Rejects paths containing null bytes.
  2. Cleans the URL path with path.Clean.
  3. Verifies the resolved path is inside absRoot.
  4. Resolves symlinks via filepath.EvalSymlinks and re-verifies the target is still inside absRoot (prevents symlink escape attacks). For paths that do not exist yet (e.g. not-found pages), the unresolved candidate is returned — it has already passed the prefix check.
  5. Blocks any path component starting with "." when blockDotfiles is true.

On success it returns the absolute filesystem path. On failure it returns one of the sentinel errors (ErrNullByte, ErrPathTraversal, ErrDotfile).

func SafePathFromContext

func SafePathFromContext(ctx context.Context) (string, bool)

SafePathFromContext retrieves the pre-validated absolute filesystem path that security.Middleware stored in the request context. Returns ("", false) when the value is absent (e.g. in unit tests that bypass the security middleware).

Types

This section is empty.

Jump to

Keyboard shortcuts

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