π Image
README
ΒΆ
go-safeinput
π CI
π Go Report Card
π codecov
π Go Reference
π Image
π΄ 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
- Installation
- Quick Start
- Usage
- Safe Deserialization (CWE-502)
- Agentic AI Support
- Supported Contexts
- Requirements
- Development
- Contributing
- License
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.v3for 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:
- Tests
analyzer,middleware, andsafedecode - Runs the analyzer and posts findings as inline PR annotations
- Uploads
agentic-findings.jsonas 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.
π Image
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 ΒΆ
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 ΒΆ
SanitizeShellArg sanitizes shell command arguments (CWE-78). Only allows alphanumeric characters, dash, underscore, period, and forward slash.
func StripNullBytes ΒΆ
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 )
type Sanitizer ΒΆ
type Sanitizer struct {
// contains filtered or unexported fields
}
Sanitizer provides the main sanitization interface.
func (*Sanitizer) MustSanitize ΒΆ
MustSanitize panics on error.
π Image
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). |
