safeinput

package module
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Apr 6, 2026 License: MIT Imports: 5 Imported by: 0

README ¶

go-safeinput

CI Go Report Card codecov Go Reference


🔴 Vulnerability Impact Analysis

MITRE CWE Top 25 coverage — Real-time ecosystem scan (updated weekly)

CWE Vulnerability Instances Severity
CWE-502 Deserialization of Untrusted Data 166240 🔴 CRITICAL
CWE-79 Cross-site Scripting (XSS) 46156 🟠 HIGH
CWE-89 SQL Injection 54904 🔴 CRITICAL
CWE-22 Path Traversal 46156 🟠 HIGH
CWE-78 OS Command Injection 69164 🔴 CRITICAL

Total Impact: Total Vulnerable Stars Affected


Universal input sanitization library for Go with MITRE CWE Top 25 coverage. Zero external dependencies, production-ready, easy to integrate.

Table of Contents

Features

  • CWE-79: XSS prevention for HTML contexts
  • CWE-89: SQL Injection prevention for identifiers and values
  • CWE-22: Path Traversal prevention
  • CWE-78: OS Command Injection prevention
  • CWE-502: Safe deserialization with size, depth, and type limits
  • Agentic AI: AST-based static analysis, HTTP middleware, and safe JSON decoder
  • Zero dependencies: Standard library only (plus gopkg.in/yaml.v3 for YAML)
  • 90%+ test coverage, race-detector clean

Installation

go get github.com/ravisastryk/go-safeinput

Quick Start

s := safeinput.Default()

safe, err := s.Sanitize("<script>alert('xss')</script>Hello", safeinput.HTMLBody)
// safe == "Hello", script tag stripped

Usage

s := safeinput.Default()

// XSS — strip tags from HTML body or attribute
s.Sanitize(input, safeinput.HTMLBody)
s.Sanitize(input, safeinput.HTMLAttr)

// SQL — validate identifiers; reject injection attempts
s.Sanitize(tableName, safeinput.SQLIdentifier)
s.Sanitize(value,     safeinput.SQLValue)       // escapes single quotes

// Path traversal — reject ".." and absolute paths
s.Sanitize(path, safeinput.FilePath)

// Shell injection — reject dangerous shell characters
s.Sanitize(arg, safeinput.ShellArg)

Safe Deserialization (CWE-502)

safedecode — bounded JSON decoding (new)
import "github.com/ravisastryk/go-safeinput/safedecode"

dec := safedecode.NewDecoder(r.Body, safedecode.Config{
    MaxBytes:     64 << 10, // 64 KB
    MaxDepth:     10,
    MaxKeys:      200,
    AllowedTypes: []reflect.Type{reflect.TypeOf(MyRequest{})},
})
var req MyRequest
if err := dec.Decode(&req); err != nil {
    http.Error(w, "invalid payload", http.StatusBadRequest)
    return
}
safedeserialize — multi-format (JSON / YAML / XML / Gob)
import "github.com/ravisastryk/go-safeinput/safedeserialize"

var user User
err := safedeserialize.JSON(data, &user,
    safedeserialize.WithMaxSize(1<<16),   // 64 KB
    safedeserialize.WithMaxDepth(16),
    safedeserialize.WithStrictMode(true), // reject unknown fields
)

Dangerous targets (interface{}, map[string]interface{}, []interface{}) are blocked automatically.

Agentic AI Support

Three packages for detection, prevention, and safe decoding in CI pipelines and production services.

Analyzer — Static Detection

github.com/ravisastryk/go-safeinput/analyzer

AST-based scanner that finds HTTP handlers reading user input without sanitization. Each finding includes a CWE identifier, severity, confidence score, and a ready-to-paste fix snippet.

findings, err := analyzer.Default().AnalyzeFile("handler.go", src)
for _, f := range findings {
    fmt.Printf("%s line %d — %s\n%s\n", f.CWE, f.Line, f.Suggestion, f.FixCode)
}

Run across a source tree from CI or the command line:

go run ./cmd/analyzer -dir . -fmt json > findings.json

GitHub Actions emits inline ::warning annotations on PR diffs automatically.

Middleware — Auto-Sanitization

github.com/ravisastryk/go-safeinput/middleware

Drop-in http.Handler wrapper that sanitizes every query parameter and form field before the wrapped handler runs. Per-parameter context routing selects the right sanitization strategy.

sanitize := func(v string, ctx middleware.Context) (string, error) {
    return safeinput.Default().Sanitize(v, safeinput.Context(ctx))
}

http.ListenAndServe(":8080", middleware.New(mux, sanitize,
    middleware.WithContext("file", middleware.FilePath),
    middleware.WithContext("q",    middleware.SQLIdentifier),
))
CI Integration

The agentic-fix job runs automatically on every PR:

  1. Tests analyzer, middleware, and safedecode
  2. Runs the analyzer and posts findings as inline PR annotations
  3. Uploads agentic-findings.json as a downloadable artifact

Remove -exit-zero from the Run Agentic Analyzer step in ci.yml to make the job a hard gate that blocks merges when unsanitized input is found.

Supported Contexts

Context CWE Use Case
HTMLBody CWE-79 User-generated HTML content
HTMLAttr CWE-79 HTML attribute values
SQLIdentifier CWE-89 Table/column names
SQLValue CWE-89 User input in SQL queries
FilePath CWE-22 File uploads, file operations
ShellArg CWE-78 Shell command arguments

Requirements

  • Go 1.23+
  • Core package: no external dependencies
  • YAML support: gopkg.in/yaml.v3

Development

make test          # run tests (90% coverage threshold)
make lint          # golangci-lint
make security      # gosec + govulncheck
make fmt           # gofmt + goimports
make all           # lint + test
make coverage-html # HTML coverage report
make tools         # install dev tools

Contributing

  • Maintain 90%+ test coverage
  • Pass all linter checks
  • No external dependencies in the core package
  • Follow Go best practices and include tests for new features

See CONTRIBUTING.md and CODE_OF_CONDUCT.md.

License

MIT License — see LICENSE for details.

Documentation ¶

Overview ¶

Package safeinput provides context-aware input sanitization for Go applications. It addresses MITRE CWE Top 25 injection vulnerabilities including:

  • CWE-79: Cross-site Scripting (XSS)
  • CWE-89: SQL Injection
  • CWE-22: Path Traversal
  • CWE-78: OS Command Injection

Index ¶

Constants ¶

This section is empty.

Variables ¶

View Source
var (
	// ErrInputTooLong is returned when input exceeds maximum length.
	ErrInputTooLong = errors.New("input exceeds maximum length")
	// ErrUnknownContext is returned when an unknown sanitization context is provided.
	ErrUnknownContext = errors.New("unknown sanitization context")
	// ErrNullByte is returned when a null byte is detected in input.
	ErrNullByte = errors.New("null byte detected in input")
)

Functions ¶

func SanitizeShellArg ¶

func SanitizeShellArg(input string) string

SanitizeShellArg sanitizes shell command arguments (CWE-78). Only allows alphanumeric characters, dash, underscore, period, and forward slash.

func StripNullBytes ¶

func StripNullBytes(s string) string

StripNullBytes removes null bytes from a string.

Types ¶

type Config ¶

type Config struct {
	MaxInputLength  int
	AllowedHTMLTags []string
	BasePath        string
	StrictMode      bool
	StripNullBytes  bool
}

Config holds sanitizer configuration options.

type Context ¶

type Context int

Context defines the output context for sanitization.

const (
	// HTMLBody sanitizes for HTML body content (CWE-79).
	HTMLBody Context = iota
	// HTMLAttribute sanitizes for HTML attribute values (CWE-79).
	HTMLAttribute
	// SQLIdentifier sanitizes SQL identifiers (CWE-89).
	SQLIdentifier
	// SQLValue validates values before queries (CWE-89).
	SQLValue
	// FilePath sanitizes filesystem paths (CWE-22).
	FilePath
	// URLPath sanitizes URL path components.
	URLPath
	// URLQuery sanitizes URL query parameters.
	URLQuery
	// ShellArg sanitizes shell command arguments (CWE-78).
	ShellArg
)

func (Context) String ¶

func (c Context) String() string

String returns a human-readable name for the context.

type Sanitizer ¶

type Sanitizer struct {
	// contains filtered or unexported fields
}

Sanitizer provides the main sanitization interface.

func Default ¶

func Default() *Sanitizer

Default returns a Sanitizer with secure default settings.

func New ¶

func New(cfg Config) *Sanitizer

New creates a new Sanitizer with the given configuration.

func (*Sanitizer) GetConfig ¶

func (s *Sanitizer) GetConfig() Config

GetConfig returns a copy of the configuration.

func (*Sanitizer) IsValid ¶

func (s *Sanitizer) IsValid(input string, ctx Context) bool

IsValid checks if input is valid for the given context.

func (*Sanitizer) MustSanitize ¶

func (s *Sanitizer) MustSanitize(input string, ctx Context) string

MustSanitize panics on error.

func (*Sanitizer) Sanitize ¶

func (s *Sanitizer) Sanitize(input string, ctx Context) (string, error)

Sanitize processes input for the specified context.

Directories ¶

Path Synopsis
Package analyzer provides an AST-based static analyser that detects HTTP handlers reading user input without go-safeinput sanitisation.
Package analyzer provides an AST-based static analyser that detects HTTP handlers reading user input without go-safeinput sanitisation.
cmd
analyzer command
Command analyzer runs the AgenticAnalyzer across a Go source tree, reports unsanitized HTTP input with CWE-mapped fix suggestions, and emits GitHub Actions workflow annotations so findings appear inline on PRs.
Command analyzer runs the AgenticAnalyzer across a Go source tree, reports unsanitized HTTP input with CWE-mapped fix suggestions, and emits GitHub Actions workflow annotations so findings appear inline on PRs.
examples
agentic/after
Package after shows the same handlers from the "before" package, rewritten using go-safeinput to eliminate the vulnerabilities.
Package after shows the same handlers from the "before" package, rewritten using go-safeinput to eliminate the vulnerabilities.
agentic/before
Package before shows common Go HTTP handlers that contain unsanitized input vulnerabilities.
Package before shows common Go HTTP handlers that contain unsanitized input vulnerabilities.
Package html provides XSS prevention (CWE-79) using pure Go.
Package html provides XSS prevention (CWE-79) using pure Go.
Package middleware provides SafeHTTP, a drop-in net/http middleware that automatically sanitizes all query parameters and form values before they reach the wrapped handler.
Package middleware provides SafeHTTP, a drop-in net/http middleware that automatically sanitizes all query parameters and form values before they reach the wrapped handler.
Package path provides path traversal prevention (CWE-22).
Package path provides path traversal prevention (CWE-22).
Package safedecode provides a safe JSON decoder with protection against CWE-502 (Deserialization of Untrusted Data).
Package safedecode provides a safe JSON decoder with protection against CWE-502 (Deserialization of Untrusted Data).
Package safedeserialize provides secure deserialization utilities for Go that mitigate CWE-502: Deserialization of Untrusted Data.
Package safedeserialize provides secure deserialization utilities for Go that mitigate CWE-502: Deserialization of Untrusted Data.
examples command
Package main demonstrates usage of the safedeserialize package.
Package main demonstrates usage of the safedeserialize package.
Package sql provides SQL injection prevention (CWE-89).
Package sql provides SQL injection prevention (CWE-89).

Jump to

Keyboard shortcuts

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