error_audit

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Mar 11, 2026 License: AGPL-3.0 Imports: 9 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DefaultFailOpenPatterns = map[string]*FailOpenPattern{
	"go": {
		Language:          "go",
		ErrorCheckPattern: `if\s+(?:\w+\s*[:=].*)?(?:err\w*)\s*!=\s*nil\s*\{`,
		ReturnPattern:     `\breturn\b`,
		PanicPattern:      `\bpanic\s*\(`,
	},
	"python": {
		Language:          "python",
		ErrorCheckPattern: `except\s+(?:\w+(?:\s*,\s*\w+)*)?(?:\s+as\s+\w+)?\s*:`,
		ReturnPattern:     `\breturn\b|\braise\b`,
		PanicPattern:      `\braise\b`,
	},
	"typescript": {
		Language:          "typescript",
		ErrorCheckPattern: `catch\s*\(\s*\w*\s*\)\s*\{`,
		ReturnPattern:     `\breturn\b|\bthrow\b`,
		PanicPattern:      `\bthrow\b`,
	},
	"java": {
		Language:          "java",
		ErrorCheckPattern: `catch\s*\(\s*\w+\s+\w+\s*\)\s*\{`,
		ReturnPattern:     `\breturn\b|\bthrow\b`,
		PanicPattern:      `\bthrow\b`,
	},
}

DefaultFailOpenPatterns contains language-specific fail-open patterns.

View Source
var DefaultInfoLeakPatterns = []*InfoLeakPattern{

	{
		Type:        "stack_trace",
		Pattern:     `(?:runtime/debug\.Stack|debug\.PrintStack|traceback\.format_exc|traceback\.print_exc)`,
		Severity:    safety.SeverityHigh,
		Description: "Stack trace exposed to users",
		CWE:         "CWE-209",
	},
	{
		Type:        "stack_trace",
		Pattern:     `(?:\.stack|Error\.stack|err\.stack)\s*[,)]`,
		Severity:    safety.SeverityMedium,
		Description: "Error stack property exposed",
		CWE:         "CWE-209",
	},

	{
		Type:        "internal_path",
		Pattern:     `(?:"/home/|"/var/|"/usr/|"/opt/|"C:\\|"/root/)`,
		Severity:    safety.SeverityLow,
		Description: "Internal file path exposed in string",
		CWE:         "CWE-200",
	},

	{
		Type:        "db_error",
		Pattern:     `(?:pq:|mysql:|sqlite3:|SQLSTATE|ORA-\d+).*(?:Write|Response|Send|json)`,
		Severity:    safety.SeverityHigh,
		Description: "Database error message exposed to user",
		CWE:         "CWE-209",
	},

	{
		Type:        "config_detail",
		Pattern:     `(?:connection.*refused|ECONNREFUSED|timeout|host.*not.*found).*(?:Write|Response|Send)`,
		Severity:    safety.SeverityMedium,
		Description: "Infrastructure error exposed to user",
		CWE:         "CWE-200",
	},

	{
		Type:        "verbose_error",
		Pattern:     `(?:Write|Response|Send|json|fmt\.Fprint).*(?:err\.Error\(\)|error\.Error\(\))`,
		Severity:    safety.SeverityMedium,
		Description: "Full error message sent to client",
		CWE:         "CWE-209",
	},

	{
		Type:        "debug_info",
		Pattern:     `(?:debug|Debug|DEBUG).*(?:true|True|TRUE|enabled|Enabled).*(?:prod|Prod|PROD|production|Production)`,
		Severity:    safety.SeverityHigh,
		Description: "Debug mode enabled in production context",
		CWE:         "CWE-489",
	},

	{
		Type:        "sensitive_field",
		Pattern:     `(?:password|secret|token|key|credential|auth).*(?:invalid|incorrect|wrong|failed).*(?:Write|Response|Send)`,
		Severity:    safety.SeverityMedium,
		Description: "Sensitive field name in error response",
		CWE:         "CWE-209",
	},
}

DefaultInfoLeakPatterns contains patterns for detecting information leaks.

View Source
var ErrorSwallowPatterns = map[string]*regexp.Regexp{
	"go":         regexp.MustCompile(`if\s+err\s*!=\s*nil\s*\{\s*\}`),
	"python":     regexp.MustCompile(`except.*:\s*pass\s*$`),
	"typescript": regexp.MustCompile(`catch\s*\([^)]*\)\s*\{\s*\}`),
	"java":       regexp.MustCompile(`catch\s*\([^)]*\)\s*\{\s*\}`),
}

ErrorSwallowPattern matches empty error handling blocks.

View Source
var SecurityFunctions = []string{

	"checkAuth", "validateAuth", "authenticate", "verifyAuth",
	"ValidateToken", "VerifyToken", "CheckToken", "ParseToken",
	"login", "signin", "signIn", "Login", "SignIn",
	"verifyPassword", "checkPassword", "ValidatePassword",

	"authorize", "Authorize", "checkPermission", "CheckPermission",
	"hasPermission", "HasPermission", "isAllowed", "IsAllowed",
	"checkAccess", "CheckAccess", "verifyAccess", "VerifyAccess",
	"canAccess", "CanAccess", "isAuthorized", "IsAuthorized",

	"validate", "Validate", "sanitize", "Sanitize",
	"verify", "Verify", "check", "Check",

	"authMiddleware", "AuthMiddleware", "requireAuth", "RequireAuth",
	"ensureAuth", "EnsureAuth", "mustAuth", "MustAuth",
}

SecurityFunctions are function name patterns that are security-sensitive. Fail-open in these functions is CRITICAL.

Functions

func FindSwallowedErrors

func FindSwallowedErrors(content, language string) [][]int

FindSwallowedErrors finds empty error handling blocks.

func IsSecurityFunction

func IsSecurityFunction(funcName string) bool

IsSecurityFunction checks if a function name is security-sensitive.

Types

type ErrorAuditorImpl

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

ErrorAuditorImpl implements the safety.ErrorAuditor interface.

Description:

ErrorAuditorImpl detects error handling issues that could lead to
security vulnerabilities, including fail-open patterns, information
leaks, and swallowed errors.

Thread Safety:

ErrorAuditorImpl is safe for concurrent use after initialization.

func NewErrorAuditor

func NewErrorAuditor(g *graph.Graph, idx *index.SymbolIndex) *ErrorAuditorImpl

NewErrorAuditor creates a new error auditor.

Description:

Creates an auditor with default patterns for detecting error
handling issues across multiple languages.

Inputs:

g - The code graph.
idx - The symbol index.

Outputs:

*ErrorAuditorImpl - The configured auditor.

func (*ErrorAuditorImpl) AuditErrorHandling

func (a *ErrorAuditorImpl) AuditErrorHandling(
	ctx context.Context,
	scope string,
	opts ...safety.AuditOption,
) (*safety.ErrorAudit, error)

AuditErrorHandling audits error handling in a scope.

Description:

Analyzes error handling patterns to detect:
  - Fail-open conditions (missing returns after error checks)
  - Information leaks (stack traces, internal paths in responses)
  - Swallowed errors (empty catch blocks)

Inputs:

ctx - Context for cancellation and timeout.
scope - The scope to audit (package path or file path).
opts - Optional configuration (focus area, etc.).

Outputs:

*safety.ErrorAudit - The audit result with issues found.
error - Non-nil if scope not found or operation canceled.

Errors:

safety.ErrInvalidInput - Scope is empty.
safety.ErrContextCanceled - Context was canceled.

Thread Safety:

This method is safe for concurrent use.

func (*ErrorAuditorImpl) ClearFileCache

func (a *ErrorAuditorImpl) ClearFileCache()

ClearFileCache clears the file content cache.

func (*ErrorAuditorImpl) SetFileContent

func (a *ErrorAuditorImpl) SetFileContent(filePath, content string)

SetFileContent sets file content for auditing.

type ErrorCheckBlock

type ErrorCheckBlock struct {
	Start      int
	End        int
	Line       int
	Content    string
	HasReturn  bool
	HasPanic   bool
	IsFailOpen bool
}

ErrorCheckBlock represents an error handling block.

type FailOpenPattern

type FailOpenPattern struct {
	// Language is the programming language.
	Language string

	// ErrorCheckPattern matches error check statements.
	ErrorCheckPattern string

	// ReturnPattern matches return statements.
	ReturnPattern string

	// PanicPattern matches panic/raise statements.
	PanicPattern string
	// contains filtered or unexported fields
}

FailOpenPattern defines patterns for detecting fail-open error handling.

func (*FailOpenPattern) CompilePatterns

func (p *FailOpenPattern) CompilePatterns()

CompilePatterns compiles all regex patterns.

func (*FailOpenPattern) FindErrorChecks

func (p *FailOpenPattern) FindErrorChecks(content string) []ErrorCheckBlock

FindErrorChecks finds all error check blocks in content.

type InfoLeakPattern

type InfoLeakPattern struct {
	// Type categorizes the leak (stack_trace, internal_path, db_error, etc.)
	Type string

	// Pattern is the regex to match.
	Pattern string

	// Severity indicates how serious this leak is.
	Severity safety.Severity

	// Description explains the risk.
	Description string

	// CWE is the Common Weakness Enumeration ID.
	CWE string
	// contains filtered or unexported fields
}

InfoLeakPattern defines a pattern for detecting information leaks.

func (*InfoLeakPattern) Match

func (p *InfoLeakPattern) Match(content string) [][]int

Match checks if content matches this pattern.

Jump to

Keyboard shortcuts

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