safety

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

Documentation

Overview

Package safety provides security analysis tools for Trace.

Description

This package implements trust flow analysis, vulnerability scanning, error handling auditing, secret detection, auth enforcement checking, and trust boundary analysis. It is the foundation for Aleutian's security-first approach to AI-assisted coding.

Thread Safety

All types in this package are safe for concurrent use after initialization.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrSymbolNotFound indicates the requested symbol doesn't exist.
	ErrSymbolNotFound = errors.New("symbol not found")

	// ErrGraphNotReady indicates the graph hasn't been frozen.
	ErrGraphNotReady = errors.New("graph not ready (not frozen)")

	// ErrInvalidInput indicates invalid input parameters.
	ErrInvalidInput = errors.New("invalid input")

	// ErrTimeoutExceeded indicates the operation timed out.
	ErrTimeoutExceeded = errors.New("analysis timeout exceeded")

	// ErrMaxNodesExceeded indicates the node limit was reached.
	ErrMaxNodesExceeded = errors.New("maximum nodes exceeded")

	// ErrMaxDepthExceeded indicates the depth limit was reached.
	ErrMaxDepthExceeded = errors.New("maximum depth exceeded")

	// ErrMemoryExceeded indicates the memory limit was reached.
	ErrMemoryExceeded = errors.New("memory limit exceeded")

	// ErrContextCanceled indicates the context was canceled.
	ErrContextCanceled = errors.New("context canceled")

	// ErrNoVulnerabilityFound indicates no matching vulnerability exists.
	ErrNoVulnerabilityFound = errors.New("no vulnerability found with that ID")
)

Common errors for the safety package.

Functions

This section is empty.

Types

type AuditConfig

type AuditConfig struct {
	Focus  string // "all", "fail_open", "info_leak"
	Limits ResourceLimits
}

AuditConfig holds configuration for error auditing.

func DefaultAuditConfig

func DefaultAuditConfig() *AuditConfig

DefaultAuditConfig returns sensible defaults for auditing.

func (*AuditConfig) ApplyOptions

func (c *AuditConfig) ApplyOptions(opts ...AuditOption)

ApplyOptions applies a list of options to the config.

type AuditOption

type AuditOption func(*AuditConfig)

AuditOption configures ErrorAuditor.AuditErrorHandling.

func WithAuditFocus

func WithAuditFocus(focus string) AuditOption

WithAuditFocus sets the focus area for auditing.

type AuthCheck

type AuthCheck struct {
	Scope            string           `json:"scope"`
	Framework        string           `json:"framework"`
	Endpoints        []EndpointAuth   `json:"endpoints"`
	MissingAuth      int              `json:"missing_auth"`
	MissingAuthz     int              `json:"missing_authz"`
	Suggestions      []string         `json:"suggestions,omitempty"`
	PartialFailures  []PartialFailure `json:"partial_failures,omitempty"`
	FrameworkDetails *FrameworkInfo   `json:"framework_details,omitempty"`
	Duration         time.Duration    `json:"duration"`
}

AuthCheck is the result of auth enforcement check.

type AuthCheckConfig

type AuthCheckConfig struct {
	Framework string // Framework hint (auto-detected if empty)
	CheckType string // "both", "authentication", "authorization"
	Limits    ResourceLimits
}

AuthCheckConfig holds configuration for auth checking.

func DefaultAuthCheckConfig

func DefaultAuthCheckConfig() *AuthCheckConfig

DefaultAuthCheckConfig returns sensible defaults for auth checking.

func (*AuthCheckConfig) ApplyOptions

func (c *AuthCheckConfig) ApplyOptions(opts ...AuthCheckOption)

ApplyOptions applies a list of options to the config.

type AuthCheckOption

type AuthCheckOption func(*AuthCheckConfig)

AuthCheckOption configures AuthChecker.CheckAuthEnforcement.

func WithAuthCheckType

func WithAuthCheckType(checkType string) AuthCheckOption

WithAuthCheckType sets what to check.

func WithFrameworkHint

func WithFrameworkHint(fw string) AuthCheckOption

WithFrameworkHint provides a framework name hint.

type AuthChecker

type AuthChecker interface {
	// CheckAuthEnforcement checks auth on endpoints.
	//
	// Description:
	//   Analyzes HTTP handlers and routes to verify they have proper
	//   authentication and authorization middleware.
	//
	// Inputs:
	//   ctx - Context for cancellation and timeout.
	//   scope - The scope to check (package path).
	//   opts - Optional configuration (framework hint, check type).
	//
	// Outputs:
	//   *AuthCheck - The check result with endpoints and issues.
	//   error - Non-nil if scope not found or operation canceled.
	CheckAuthEnforcement(ctx context.Context, scope string, opts ...AuthCheckOption) (*AuthCheck, error)
}

AuthChecker checks authentication and authorization enforcement.

Description:

AuthChecker detects endpoints missing authentication or authorization
middleware. It supports multiple web frameworks (Gin, Echo, FastAPI, etc.).

Thread Safety:

Implementations must be safe for concurrent use.

type BoundaryCrossing

type BoundaryCrossing struct {
	ID            string     `json:"id"`
	From          *TrustZone `json:"from"`
	To            *TrustZone `json:"to"`
	CrossingAt    string     `json:"crossing_at"`
	DataPath      []string   `json:"data_path"`
	HasValidation bool       `json:"has_validation"`
	ValidationFn  string     `json:"validation_fn,omitempty"`
}

BoundaryCrossing represents data moving between zones.

type BoundaryOption

type BoundaryOption func(*boundaryConfig)

BoundaryOption configures TrustBoundaryAnalyzer.AnalyzeTrustBoundary.

func WithShowZones

func WithShowZones(show bool) BoundaryOption

WithShowZones includes full zone map in output.

type BoundaryViolation

type BoundaryViolation struct {
	Crossing    *BoundaryCrossing `json:"crossing"`
	Severity    Severity          `json:"severity"`
	MissingStep string            `json:"missing_step"`
	CWE         string            `json:"cwe"`
	Remediation string            `json:"remediation"`
}

BoundaryViolation represents an unsafe crossing.

type DataTaint

type DataTaint int

DataTaint tracks the taintedness state of specific data.

Description:

DataTaint represents whether data has been validated/sanitized.
This is used for taint tracking during trust flow analysis to
determine if untrusted data reaches sensitive sinks.

Thread Safety:

DataTaint is an immutable value type, safe for concurrent use.
const (
	// TaintUnknown indicates the data has not been analyzed.
	TaintUnknown DataTaint = iota

	// TaintClean indicates the data is sanitized or a constant.
	// Safe to use in any sink.
	TaintClean

	// TaintUntrusted indicates the data is from an external source
	// and has not been sanitized. Dangerous if it reaches a sink.
	TaintUntrusted

	// TaintMixed indicates the data is merged from multiple sources
	// where at least one may be untrusted. Conservative assumption.
	TaintMixed
)

func MergeTaints

func MergeTaints(taints ...DataTaint) DataTaint

MergeTaints returns the most conservative taint from multiple values.

Description:

Implements the abstract interpretation lattice for taint states:
  UNTRUSTED ∪ CLEAN = UNTRUSTED (conservative)
  MIXED ∪ anything = MIXED (unless UNTRUSTED)
  UNKNOWN ∪ anything = that thing

Inputs:

taints - Variable number of DataTaint values to merge.

Outputs:

DataTaint - The most conservative (least trusted) taint state.

Thread Safety:

This function is safe for concurrent use.

func (DataTaint) String

func (t DataTaint) String() string

String returns the string representation of DataTaint.

type EndpointAuth

type EndpointAuth struct {
	Name              string   `json:"name"`
	Type              string   `json:"type"` // http, grpc, graphql, websocket
	Path              string   `json:"path"`
	Method            string   `json:"method"`
	Framework         string   `json:"framework"`
	HasAuthentication bool     `json:"has_authentication"`
	AuthMethod        string   `json:"auth_method,omitempty"`
	HasAuthorization  bool     `json:"has_authorization"`
	AuthzMethod       string   `json:"authz_method,omitempty"`
	Risk              Severity `json:"risk,omitempty"`
	IsAdminEndpoint   bool     `json:"is_admin_endpoint"`
	HandlesData       bool     `json:"handles_data"`
}

EndpointAuth describes auth status of an endpoint.

type ErrorAudit

type ErrorAudit struct {
	Scope           string           `json:"scope"`
	Issues          []ErrorIssue     `json:"issues"`
	Summary         ErrorSummary     `json:"summary"`
	PartialFailures []PartialFailure `json:"partial_failures,omitempty"`
	Duration        time.Duration    `json:"duration"`
}

ErrorAudit is the result of error handling audit.

type ErrorAuditor

type ErrorAuditor interface {
	// AuditErrorHandling audits error handling in a scope.
	//
	// Description:
	//   Analyzes error handling patterns to detect fail-open conditions,
	//   information leaks (stack traces, internal paths), and swallowed errors.
	//
	// Inputs:
	//   ctx - Context for cancellation and timeout.
	//   scope - The scope to audit (package path or file path).
	//   opts - Optional configuration (focus area, etc.).
	//
	// Outputs:
	//   *ErrorAudit - The audit result with issues found.
	//   error - Non-nil if scope not found or operation canceled.
	AuditErrorHandling(ctx context.Context, scope string, opts ...AuditOption) (*ErrorAudit, error)
}

ErrorAuditor audits error handling for security issues.

Description:

ErrorAuditor detects fail-open patterns, information leaks, and
improper error handling that could lead to security bypasses.

Thread Safety:

Implementations must be safe for concurrent use.

type ErrorIssue

type ErrorIssue struct {
	Type       string   `json:"type"` // fail_open, leak_info, swallow, expose_stack
	Severity   Severity `json:"severity"`
	Location   string   `json:"location"`
	Line       int      `json:"line"`
	Code       string   `json:"code,omitempty"`
	Context    string   `json:"context"`
	Risk       string   `json:"risk"`
	Suggestion string   `json:"suggestion"`
	CWE        string   `json:"cwe,omitempty"`
}

ErrorIssue is a detected error handling problem.

type ErrorSummary

type ErrorSummary struct {
	TotalErrors     int `json:"total_errors"`
	Handled         int `json:"handled"`
	Swallowed       int `json:"swallowed"`
	InfoLeaks       int `json:"info_leaks"`
	FailOpenPaths   int `json:"fail_open_paths"`
	FailClosedPaths int `json:"fail_closed_paths"`
}

ErrorSummary summarizes error audit results.

type Exploitability

type Exploitability string

Exploitability indicates how likely a vulnerability can be exploited.

const (
	ExploitabilityYes     Exploitability = "yes"     // Proven exploitable
	ExploitabilityNo      Exploitability = "no"      // Not exploitable
	ExploitabilityUnknown Exploitability = "unknown" // Cannot determine
)

type FrameworkAnalyzer

type FrameworkAnalyzer interface {
	// Name returns the framework name.
	Name() string

	// DetectRoutes finds HTTP routes in the scope.
	DetectRoutes(g *graph.Graph, scope string) ([]Route, error)

	// DetectMiddleware finds middleware on a route.
	DetectMiddleware(route Route) ([]Middleware, error)

	// IsAuthMiddleware checks if middleware provides authentication.
	// Returns (isAuth, methodName).
	IsAuthMiddleware(m Middleware) (bool, string)

	// IsAuthzMiddleware checks if middleware provides authorization.
	// Returns (isAuthz, methodName).
	IsAuthzMiddleware(m Middleware) (bool, string)
}

FrameworkAnalyzer understands framework-specific middleware patterns.

Description:

FrameworkAnalyzer enables framework-aware security analysis for
web frameworks like Gin, Echo, Chi, FastAPI, Flask, NestJS, etc.

Thread Safety:

Implementations must be safe for concurrent use.

type FrameworkInfo

type FrameworkInfo struct {
	Name       string   `json:"name"`
	Confidence float64  `json:"confidence"`
	Indicators []string `json:"indicators"`
	Version    string   `json:"version,omitempty"`
}

FrameworkInfo describes detected framework details.

type HardcodedSecret

type HardcodedSecret struct {
	Type     string   `json:"type"` // api_key, password, private_key, etc.
	Location string   `json:"location"`
	Line     int      `json:"line"`
	Context  string   `json:"context"` // Masked code around secret
	Severity Severity `json:"severity"`
}

HardcodedSecret is a detected secret in code.

type InputSource

type InputSource struct {
	ID          string `json:"id"`
	Name        string `json:"name"`
	Category    string `json:"category"` // http, env, file, cli, etc.
	Location    string `json:"location"`
	Description string `json:"description,omitempty"`
}

InputSource describes where untrusted input enters.

type InputTrace

type InputTrace struct {
	// Source is the input source that was traced.
	Source InputSource `json:"source"`

	// Path is the sequence of steps from source to sinks.
	Path []TraceStep `json:"path"`

	// Sinks are the sensitive sinks reached by the input.
	Sinks []Sink `json:"sinks"`

	// Sanitizers are the sanitization points found along the path.
	Sanitizers []Sanitizer `json:"sanitizers"`

	// Vulnerabilities are confirmed security issues.
	Vulnerabilities []Vulnerability `json:"vulnerabilities,omitempty"`

	// Confidence is the overall confidence in this trace (0.0-1.0).
	Confidence float64 `json:"confidence"`

	// Limitations lists what couldn't be analyzed.
	Limitations []string `json:"limitations,omitempty"`

	// PartialFailures lists analysis gaps.
	PartialFailures []PartialFailure `json:"partial_failures,omitempty"`

	// Duration is how long the trace took.
	Duration time.Duration `json:"duration"`
}

InputTrace is the result of tracing user input through code.

type InputTracer

type InputTracer interface {
	// TraceUserInput traces data flow from an input source.
	//
	// Description:
	//   Follows data from the source through function calls, tracking
	//   taint state at each step. Reports vulnerabilities when untrusted
	//   data reaches sensitive sinks without sanitization.
	//
	// Inputs:
	//   ctx - Context for cancellation and timeout.
	//   sourceID - The symbol ID of the input source to trace from.
	//   opts - Optional configuration (max depth, sink filters, etc.).
	//
	// Outputs:
	//   *InputTrace - The trace result with path, sinks, and vulnerabilities.
	//   error - Non-nil if source not found or operation canceled.
	TraceUserInput(ctx context.Context, sourceID string, opts ...TraceOption) (*InputTrace, error)
}

InputTracer traces untrusted input through code to find vulnerabilities.

Description:

InputTracer performs taint analysis, tracking where untrusted data
flows and whether it's sanitized before reaching sensitive sinks.
This is the core interface for CB-23's trust flow analysis.

Thread Safety:

Implementations must be safe for concurrent use.

type Middleware

type Middleware struct {
	Name     string `json:"name"`
	Location string `json:"location"`
	Type     string `json:"type,omitempty"` // auth, authz, logging, etc.
}

Middleware describes a middleware function.

type PartialFailure

type PartialFailure struct {
	// Scope is the file or function that failed.
	Scope string `json:"scope"`

	// Reason explains why the analysis failed.
	Reason string `json:"reason"`

	// Impact describes what security properties couldn't be verified.
	Impact string `json:"impact"`

	// Severity indicates how serious this gap is.
	Severity Severity `json:"severity"`
}

PartialFailure describes what couldn't be analyzed.

Description:

PartialFailure records analysis gaps when part of the analysis
fails but the rest can continue. This enables graceful degradation
while maintaining transparency about what was missed.

type RemediationVerifier

type RemediationVerifier interface {
	// VerifyRemediation verifies a security fix.
	//
	// Description:
	//   Re-runs the specific check that found the issue on the new code
	//   to verify the vulnerability is fixed.
	//
	// Inputs:
	//   ctx - Context for cancellation and timeout.
	//   issueID - The ID of the security issue being fixed.
	//   newCode - The patched code to verify.
	//
	// Outputs:
	//   *VerificationResult - Whether the fix worked.
	//   error - Non-nil if issue not found or operation canceled.
	VerifyRemediation(ctx context.Context, issueID string, newCode string) (*VerificationResult, error)
}

RemediationVerifier verifies that security fixes work.

Description:

RemediationVerifier re-runs analysis on patched code to verify that
a security fix actually resolves the issue and doesn't introduce new ones.

Thread Safety:

Implementations must be safe for concurrent use.

type ResourceLimits

type ResourceLimits struct {
	// MaxMemoryBytes is the maximum memory to use (0 = unlimited).
	MaxMemoryBytes int64 `json:"max_memory_bytes"`

	// MaxNodes is the maximum graph nodes to visit.
	MaxNodes int `json:"max_nodes"`

	// MaxDepth is the maximum call chain depth to traverse.
	MaxDepth int `json:"max_depth"`

	// Timeout is the hard timeout for the operation.
	Timeout time.Duration `json:"timeout"`
}

ResourceLimits defines memory and computation bounds for analysis.

Description:

ResourceLimits prevents runaway analysis on large codebases by
enforcing hard limits on memory, nodes visited, depth, and time.

Thread Safety:

ResourceLimits is an immutable value type, safe for concurrent use.

func DefaultResourceLimits

func DefaultResourceLimits() ResourceLimits

DefaultResourceLimits returns conservative defaults.

Description:

Returns resource limits suitable for most analyses. These limits
balance thoroughness with performance.

Outputs:

ResourceLimits - Default configuration with:
  - 256MB memory limit
  - 50,000 node limit
  - 20 depth limit
  - 30 second timeout

type Route

type Route struct {
	Path       string   `json:"path"`
	Method     string   `json:"method"`
	Handler    string   `json:"handler"`
	Location   string   `json:"location"`
	Middleware []string `json:"middleware,omitempty"`
}

Route describes an HTTP route.

type Sanitizer

type Sanitizer struct {
	ID           string   `json:"id"`
	Name         string   `json:"name"`
	Location     string   `json:"location"`
	MakesSafeFor []string `json:"makes_safe_for"` // Sink categories this sanitizes
	IsComplete   bool     `json:"is_complete"`    // Fully sanitizes or needs more?
	Notes        string   `json:"notes,omitempty"`
}

Sanitizer describes a function that makes data safe.

type ScanConfig

type ScanConfig struct {
	MinSeverity   Severity
	MinConfidence float64
	Parallelism   int
	Limits        ResourceLimits
}

ScanConfig holds configuration for security scanning.

func DefaultScanConfig

func DefaultScanConfig() *ScanConfig

DefaultScanConfig returns sensible defaults for scanning.

func (*ScanConfig) ApplyOptions

func (c *ScanConfig) ApplyOptions(opts ...ScanOption)

ApplyOptions applies a list of options to the config.

type ScanOption

type ScanOption func(*ScanConfig)

ScanOption configures SecurityScanner.ScanForSecurityIssues.

func WithMinConfidence

func WithMinConfidence(conf float64) ScanOption

WithMinConfidence sets the minimum confidence to report.

func WithMinSeverity

func WithMinSeverity(s Severity) ScanOption

WithMinSeverity sets the minimum severity to report.

func WithParallelism

func WithParallelism(p int) ScanOption

WithParallelism sets the number of parallel workers.

type ScanResult

type ScanResult struct {
	Scope           string           `json:"scope"`
	Issues          []SecurityIssue  `json:"issues"`
	Summary         ScanSummary      `json:"summary"`
	PartialFailures []PartialFailure `json:"partial_failures,omitempty"`
	Confidence      float64          `json:"confidence"`
	CoveragePercent float64          `json:"coverage_percent"`
	Duration        time.Duration    `json:"duration"`
}

ScanResult is the result of a security scan.

type ScanSummary

type ScanSummary struct {
	TotalIssues  int `json:"total_issues"`
	Critical     int `json:"critical"`
	High         int `json:"high"`
	Medium       int `json:"medium"`
	Low          int `json:"low"`
	Suppressed   int `json:"suppressed"`
	FilesScanned int `json:"files_scanned"`
}

ScanSummary summarizes scan results.

type SecretFinder

type SecretFinder interface {
	// FindHardcodedSecrets finds secrets in a scope.
	//
	// Description:
	//   Scans for common secret patterns: API keys, passwords, private
	//   keys, connection strings, and cloud credentials.
	//
	// Inputs:
	//   ctx - Context for cancellation and timeout.
	//   scope - The scope to scan (package path or file path).
	//
	// Outputs:
	//   []HardcodedSecret - All secrets found (masked in output).
	//   error - Non-nil if scope not found or operation canceled.
	FindHardcodedSecrets(ctx context.Context, scope string) ([]HardcodedSecret, error)
}

SecretFinder finds hardcoded secrets in code.

Description:

SecretFinder detects API keys, passwords, private keys, and other
credentials that are hardcoded in source code.

Thread Safety:

Implementations must be safe for concurrent use.

type SecurityIssue

type SecurityIssue struct {
	ID              string   `json:"id"`
	Type            string   `json:"type"`
	Severity        Severity `json:"severity"`
	Confidence      float64  `json:"confidence"`
	Location        string   `json:"location"`
	Line            int      `json:"line"`
	Code            string   `json:"code,omitempty"`
	Description     string   `json:"description"`
	Remediation     string   `json:"remediation"`
	CWE             string   `json:"cwe"`
	CVSS            float64  `json:"cvss,omitempty"`
	DataFlowProven  bool     `json:"data_flow_proven"`
	Suppressed      bool     `json:"suppressed"`
	SuppressionNote string   `json:"suppression_note,omitempty"`
}

SecurityIssue is a detected security vulnerability.

type SecurityScanner

type SecurityScanner interface {
	// ScanForSecurityIssues scans a scope for vulnerabilities.
	//
	// Description:
	//   Scans the specified scope (package, file, or symbol) for security
	//   issues using pattern matching and trust flow analysis.
	//
	// Inputs:
	//   ctx - Context for cancellation and timeout.
	//   scope - The scope to scan (package path, file path, or symbol ID).
	//   opts - Optional configuration (min severity, min confidence, etc.).
	//
	// Outputs:
	//   *ScanResult - The scan result with issues found.
	//   error - Non-nil if scope not found or operation canceled.
	ScanForSecurityIssues(ctx context.Context, scope string, opts ...ScanOption) (*ScanResult, error)
}

SecurityScanner scans code for security vulnerabilities.

Description:

SecurityScanner performs SAST-lite scanning, detecting common
vulnerability patterns like SQL injection, XSS, command injection,
and more. It integrates with trust flow analysis for higher confidence.

Thread Safety:

Implementations must be safe for concurrent use.

type Severity

type Severity string

Severity indicates the severity of a security finding.

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

type Sink

type Sink struct {
	ID          string `json:"id"`
	Name        string `json:"name"`
	Category    string `json:"category"` // sql, command, xss, path, ssrf, etc.
	Location    string `json:"location"`
	IsDangerous bool   `json:"is_dangerous"`
	CWE         string `json:"cwe,omitempty"`
}

Sink describes a sensitive operation that receives data.

type TraceConfig

type TraceConfig struct {
	MaxDepth       int
	MaxNodes       int
	SinkCategories []string
	Limits         ResourceLimits
}

TraceConfig holds configuration for input tracing.

func DefaultTraceConfig

func DefaultTraceConfig() *TraceConfig

DefaultTraceConfig returns sensible defaults for tracing.

func (*TraceConfig) ApplyOptions

func (c *TraceConfig) ApplyOptions(opts ...TraceOption)

ApplyOptions applies a list of options to the config.

type TraceOption

type TraceOption func(*TraceConfig)

TraceOption configures InputTracer.TraceUserInput.

func WithMaxDepth

func WithMaxDepth(depth int) TraceOption

WithMaxDepth sets the maximum trace depth.

func WithMaxNodes

func WithMaxNodes(nodes int) TraceOption

WithMaxNodes sets the maximum nodes to visit.

func WithResourceLimits

func WithResourceLimits(limits ResourceLimits) TraceOption

WithResourceLimits sets resource constraints.

func WithSinkCategories

func WithSinkCategories(categories ...string) TraceOption

WithSinkCategories filters to specific sink types.

type TraceStep

type TraceStep struct {
	SymbolID  string    `json:"symbol_id"`
	Name      string    `json:"name"`
	Location  string    `json:"location"`
	Taint     DataTaint `json:"taint"`
	TaintedBy string    `json:"tainted_by,omitempty"` // Source of taint
}

TraceStep is one step in the data flow path.

type TrustBoundary

type TrustBoundary struct {
	Scope           string              `json:"scope"`
	Zones           []TrustZone         `json:"zones,omitempty"`
	Crossings       []BoundaryCrossing  `json:"crossings"`
	Violations      []BoundaryViolation `json:"violations"`
	Recommendations []string            `json:"recommendations,omitempty"`
	PartialFailures []PartialFailure    `json:"partial_failures,omitempty"`
	Duration        time.Duration       `json:"duration"`
}

TrustBoundary is the result of trust boundary analysis.

type TrustBoundaryAnalyzer

type TrustBoundaryAnalyzer interface {
	// AnalyzeTrustBoundary analyzes trust zones and crossings.
	//
	// Description:
	//   Automatically detects trust zones in the codebase and identifies
	//   boundary crossings where validation may be missing.
	//
	// Inputs:
	//   ctx - Context for cancellation and timeout.
	//   scope - The scope to analyze (package path).
	//   opts - Optional configuration (show zones, etc.).
	//
	// Outputs:
	//   *TrustBoundary - The analysis result with zones, crossings, violations.
	//   error - Non-nil if scope not found or operation canceled.
	AnalyzeTrustBoundary(ctx context.Context, scope string, opts ...BoundaryOption) (*TrustBoundary, error)
}

TrustBoundaryAnalyzer analyzes trust boundaries and zone crossings.

Description:

TrustBoundaryAnalyzer implements a formal trust zone model, detecting
where untrusted data crosses into trusted zones without validation.
This is Aleutian's unique security differentiator.

Thread Safety:

Implementations must be safe for concurrent use.

type TrustLevel

type TrustLevel int

TrustLevel classifies the trust zone of code or data.

Description:

TrustLevel represents the inherent trustworthiness of a code region
or data source. Higher levels indicate more trusted code that should
be protected from lower-level inputs.

Thread Safety:

TrustLevel is an immutable value type, safe for concurrent use.
const (
	// TrustExternal represents untrusted external input.
	// Sources: HTTP requests, CLI args, file reads, environment variables.
	// Treatment: NEVER trust, always validate before use.
	TrustExternal TrustLevel = iota

	// TrustValidation represents validation/sanitization points.
	// Sources: Input validators, sanitizers, type converters.
	// Treatment: Data crossing this boundary should be validated.
	TrustValidation

	// TrustInternal represents internal business logic.
	// Sources: Service layer, domain logic, internal APIs.
	// Treatment: Conditionally trust, validate inputs from external.
	TrustInternal

	// TrustPrivileged represents admin/system operations.
	// Sources: Admin endpoints, system commands, privileged APIs.
	// Treatment: Highly trusted, protect from external access.
	TrustPrivileged
)

func (TrustLevel) String

func (t TrustLevel) String() string

String returns the string representation of TrustLevel.

type TrustZone

type TrustZone struct {
	ID          string     `json:"id"`
	Name        string     `json:"name"`
	Level       TrustLevel `json:"level"`
	EntryPoints []string   `json:"entry_points"`
	ExitPoints  []string   `json:"exit_points"`
	Files       []string   `json:"files"`
}

TrustZone represents a region of code with uniform trust level.

type VerificationResult

type VerificationResult struct {
	IssueID       string          `json:"issue_id"`
	OriginalIssue *SecurityIssue  `json:"original_issue"`
	IsFixed       bool            `json:"is_fixed"`
	StillPresent  bool            `json:"still_present"`
	NewIssues     []SecurityIssue `json:"new_issues,omitempty"`
	Explanation   string          `json:"explanation"`
}

VerificationResult is the result of remediation verification.

type Vulnerability

type Vulnerability struct {
	ID             string         `json:"id"`
	Type           string         `json:"type"` // sql_injection, xss, etc.
	CWE            string         `json:"cwe"`
	Severity       Severity       `json:"severity"`
	Confidence     float64        `json:"confidence"`
	Exploitability Exploitability `json:"exploitability"`
	Location       string         `json:"location"`
	Line           int            `json:"line"`
	Code           string         `json:"code,omitempty"`
	Description    string         `json:"description"`
	Remediation    string         `json:"remediation"`
	DataFlowProven bool           `json:"data_flow_proven"`
}

Vulnerability is a confirmed security issue.

Directories

Path Synopsis
Package trust provides trust boundary analysis for security scanning.
Package trust provides trust boundary analysis for security scanning.
Package trust_flow provides trust flow analysis for security scanning.
Package trust_flow provides trust flow analysis for security scanning.

Jump to

Keyboard shortcuts

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