validate

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: 16 Imported by: 0

Documentation

Index

Constants

View Source
const PatternVersion = "2026.01.26"

PatternVersion is the current version of the pattern database.

Variables

This section is empty.

Functions

func AllPatterns

func AllPatterns() map[string][]DangerousPattern

AllPatterns returns all dangerous patterns.

Types

type ASTScanner

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

ASTScanner scans code using AST analysis for dangerous patterns.

Thread Safety: Individual Scan calls are safe for concurrent use. The scanner maintains no state between calls. Tree-sitter parsers are created per-call to avoid sharing issues.

func NewASTScanner

func NewASTScanner() *ASTScanner

NewASTScanner creates a new AST-based scanner.

func (*ASTScanner) Scan

func (s *ASTScanner) Scan(ctx context.Context, source []byte, language, filePath string) ([]ValidationWarning, error)

Scan scans source code for dangerous patterns using AST analysis.

Description:

Parses the source code using tree-sitter and walks the AST
looking for function calls and patterns that match known
dangerous patterns. Uses AST analysis to avoid false positives
from patterns appearing in comments or strings.

Inputs:

ctx - Context for cancellation
source - Source code bytes
language - Language identifier (go, python, javascript, typescript)
filePath - File path for error reporting

Outputs:

[]ValidationWarning - Detected dangerous patterns
error - Non-nil if parsing fails

Thread Safety: Safe for concurrent use. Parser created per-call.

func (*ASTScanner) ScanForSQLInjection

func (s *ASTScanner) ScanForSQLInjection(ctx context.Context, source []byte, language, filePath string) []ValidationWarning

ScanForSQLInjection checks for SQL injection patterns. This requires more context than simple pattern matching.

type DangerousPattern

type DangerousPattern struct {
	// Name is the pattern identifier.
	Name string

	// Language is the language this pattern applies to ("" for all).
	Language string

	// NodeType is the AST node type to match (for AST-based detection).
	NodeType string

	// FuncNames are function names that trigger this pattern.
	FuncNames []string

	// Severity is the severity level.
	Severity Severity

	// Message describes the issue.
	Message string

	// Suggestion describes how to fix the issue.
	Suggestion string

	// Blocking indicates if this pattern should block patches.
	Blocking bool

	// WarnType is the warning type category.
	WarnType WarnType
}

DangerousPattern defines a pattern to detect in code.

func GoPatterns

func GoPatterns() []DangerousPattern

GoPatterns returns dangerous patterns for Go code.

func JavaScriptPatterns

func JavaScriptPatterns() []DangerousPattern

JavaScriptPatterns returns dangerous patterns for JavaScript/TypeScript.

func PythonPatterns

func PythonPatterns() []DangerousPattern

PythonPatterns returns dangerous patterns for Python code.

type ErrorType

type ErrorType string

ErrorType represents the type of validation error.

const (
	ErrorTypeSizeLimit  ErrorType = "SIZE_LIMIT"
	ErrorTypeDiffParse  ErrorType = "DIFF_PARSE"
	ErrorTypeSyntax     ErrorType = "SYNTAX"
	ErrorTypePermission ErrorType = "PERMISSION"
	ErrorTypeInternal   ErrorType = "INTERNAL"
	ErrorTypeLint       ErrorType = "LINT"
)

type PatchStats

type PatchStats struct {
	// LinesAdded is the number of lines added.
	LinesAdded int `json:"lines_added"`

	// LinesRemoved is the number of lines removed.
	LinesRemoved int `json:"lines_removed"`

	// FilesAffected is the number of files affected.
	FilesAffected int `json:"files_affected"`
}

PatchStats contains statistics about the patch.

type PatchValidator

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

PatchValidator validates patches for safety.

Thread Safety: Individual Validate calls are safe for concurrent use. The validator maintains no state between calls. Tree-sitter parsers are created per-call to avoid sharing issues.

func NewPatchValidator

func NewPatchValidator(config ValidatorConfig) (*PatchValidator, error)

NewPatchValidator creates a new patch validator.

Description:

Creates a PatchValidator with the given configuration. The validator
checks patches for size limits, syntax errors, dangerous patterns,
and hardcoded secrets.

Inputs:

config - Validator configuration

Outputs:

*PatchValidator - The configured validator
error - Non-nil if configuration is invalid

Thread Safety: Safe to share between goroutines.

func (*PatchValidator) SetLintRunner

func (v *PatchValidator) SetLintRunner(runner *lint.LintRunner)

SetLintRunner sets a custom lint runner for the validator.

Description:

Allows injection of a pre-configured lint runner, useful for
testing or sharing a runner across validators.

Inputs:

runner - The lint runner to use

Thread Safety: Not safe to call concurrently with Validate.

func (*PatchValidator) Validate

func (v *PatchValidator) Validate(ctx context.Context, patchContent, projectRoot string) (*ValidationResult, error)

Validate validates a patch for safety.

Description:

Runs a multi-stage validation pipeline on the patch:
1. Size check - reject patches over maxLines
2. Diff parsing - validate diff format
3. Syntax validation - parse full file after applying patch
4. Linter check - run external linters (golangci-lint, ruff, eslint)
5. Pattern scanning - AST-based dangerous pattern detection
6. Secret scanning - check for hardcoded secrets
7. Permission check - verify files are writable

Inputs:

ctx - Context for cancellation
patchContent - The patch content (unified diff format)
projectRoot - Project root directory for file resolution

Outputs:

*ValidationResult - Validation result with errors and warnings
error - Non-nil if validation pipeline itself fails

Thread Safety: Safe for concurrent use. Parser created per-call.

type PermissionIssue

type PermissionIssue struct {
	// File is the file path.
	File string `json:"file"`

	// Issue describes the permission problem.
	Issue string `json:"issue"`
}

PermissionIssue represents a file permission problem.

type SecretPattern

type SecretPattern struct {
	// Name is the pattern identifier.
	Name string

	// Pattern is the regex pattern.
	Pattern string

	// MinEntropy overrides the default minimum entropy.
	MinEntropy float64

	// Keywords are context keywords that must appear nearby.
	Keywords []string

	// Severity is the severity level.
	Severity Severity

	// Message describes the issue.
	Message string
}

SecretPattern defines a pattern for detecting secrets.

func SecretPatterns

func SecretPatterns() []SecretPattern

SecretPatterns returns patterns for detecting hardcoded secrets.

type SecretScanner

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

SecretScanner scans code for hardcoded secrets.

func NewSecretScanner

func NewSecretScanner(config ValidatorConfig) (*SecretScanner, error)

NewSecretScanner creates a new secret scanner.

func (*SecretScanner) Scan

func (s *SecretScanner) Scan(content []byte, filePath string) []ValidationWarning

Scan scans content for hardcoded secrets.

Description:

Checks content against known secret patterns using regex matching
combined with entropy analysis to reduce false positives. Skips
files matching the allowlist (test files, fixtures).

Inputs:

content - Source code content
filePath - File path (for allowlist checking)

Outputs:

[]ValidationWarning - Detected secrets

func (*SecretScanner) ScanPath

func (s *SecretScanner) ScanPath(filePath string) bool

ScanPath returns whether a path should be scanned. This is a quick pre-check before content scanning.

type Severity

type Severity string

Severity represents the severity level of a warning.

const (
	SeverityCritical Severity = "CRITICAL"
	SeverityHigh     Severity = "HIGH"
	SeverityMedium   Severity = "MEDIUM"
	SeverityLow      Severity = "LOW"
)

type ValidationError

type ValidationError struct {
	// Type is the error type.
	Type ErrorType `json:"type"`

	// Message is a human-readable error message.
	Message string `json:"message"`

	// File is the file where the error occurred.
	File string `json:"file,omitempty"`

	// Line is the line number where the error occurred.
	Line int `json:"line,omitempty"`
}

ValidationError represents a blocking validation error.

type ValidationResult

type ValidationResult struct {
	// Valid indicates whether the patch passed validation.
	Valid bool `json:"valid"`

	// Errors contains blocking validation errors.
	Errors []ValidationError `json:"errors,omitempty"`

	// Warnings contains non-blocking warnings.
	Warnings []ValidationWarning `json:"warnings,omitempty"`

	// Permissions contains file permission issues.
	Permissions []PermissionIssue `json:"permissions,omitempty"`

	// Stats contains patch statistics.
	Stats PatchStats `json:"stats"`

	// PatternVersion is the version of the pattern database used.
	PatternVersion string `json:"pattern_version"`

	// ValidatedAt is when validation occurred (Unix milliseconds UTC).
	ValidatedAt int64 `json:"validated_at"`
}

ValidationResult contains the result of patch validation.

type ValidationWarning

type ValidationWarning struct {
	// Type is the warning type.
	Type WarnType `json:"type"`

	// Pattern is the dangerous pattern that was matched.
	Pattern string `json:"pattern"`

	// File is the file where the pattern was found.
	File string `json:"file"`

	// Line is the line number where the pattern was found.
	Line int `json:"line"`

	// Severity is the severity level.
	Severity Severity `json:"severity"`

	// Message is a human-readable warning message.
	Message string `json:"message"`

	// Suggestion is a suggestion for fixing the issue.
	Suggestion string `json:"suggestion,omitempty"`

	// Blocking indicates if this warning should block the patch.
	Blocking bool `json:"blocking"`
}

ValidationWarning represents a non-blocking warning.

type ValidatorConfig

type ValidatorConfig struct {
	// MaxLines is the maximum number of lines allowed in a patch.
	MaxLines int

	// BlockDangerous determines if dangerous patterns block validation.
	BlockDangerous bool

	// WarnOnly makes all patterns warnings instead of blockers.
	WarnOnly bool

	// MinPatternVersion is the minimum required pattern version.
	MinPatternVersion string

	// AllowlistPaths are path patterns to skip for secret scanning.
	AllowlistPaths []string

	// MinSecretEntropy is the minimum entropy for secret detection.
	MinSecretEntropy float64

	// EnableLinter enables the linter integration.
	// When enabled, linting is performed on patched files.
	EnableLinter bool

	// BlockOnLintErrors blocks patches that have linter errors.
	// Only applies when EnableLinter is true.
	BlockOnLintErrors bool
}

ValidatorConfig configures the patch validator.

func DefaultValidatorConfig

func DefaultValidatorConfig() ValidatorConfig

DefaultValidatorConfig returns the default configuration.

type WarnType

type WarnType string

WarnType represents the type of validation warning.

const (
	WarnTypeDangerousPattern WarnType = "DANGEROUS_PATTERN"
	WarnTypeSecret           WarnType = "SECRET"
	WarnTypeSSRF             WarnType = "SSRF"
	WarnTypeSQLInjection     WarnType = "SQL_INJECTION"
	WarnTypeTemplateInject   WarnType = "TEMPLATE_INJECTION"
	WarnTypePrototypePollute WarnType = "PROTOTYPE_POLLUTION"
	WarnTypeDeserialization  WarnType = "DESERIALIZATION"
	WarnTypePathTraversal    WarnType = "PATH_TRAVERSAL"
	WarnTypeLint             WarnType = "LINT"
)

Jump to

Keyboard shortcuts

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