vulnerability

package
v0.1.6 Latest Latest
Warning

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

Go to latest
Published: Apr 14, 2026 License: GPL-3.0 Imports: 12 Imported by: 0

Documentation

Overview

Package vulnerability provides the vulnerability domain model.

Index

Constants

View Source
const (
	LocationTypeSource       = "source"       // Where tainted data enters (e.g., user input)
	LocationTypeIntermediate = "intermediate" // Data transformation/propagation steps
	LocationTypeSink         = "sink"         // Where vulnerability occurs (e.g., SQL query)
	LocationTypeSanitizer    = "sanitizer"    // Where data is sanitized (safe path)
)

Valid location types for data flow locations. These map to SARIF threadFlowLocation roles.

View Source
const (
	// MaxSnippetSize is the maximum size of a code snippet in bytes (10KB).
	// Larger snippets are truncated to prevent memory exhaustion and DB bloat.
	MaxSnippetSize = 10 * 1024

	// MaxMessageSize is the maximum size of a message in bytes (2KB).
	MaxMessageSize = 2 * 1024

	// MaxLabelSize is the maximum size of a label in bytes (500 chars).
	MaxLabelSize = 500

	// MaxPathSize is the maximum size of a file path in bytes (1000 chars).
	MaxPathSize = 1000

	// MaxDataFlowsPerFinding is the maximum number of data flows allowed per finding.
	// Prevents DoS by limiting memory/storage consumption.
	MaxDataFlowsPerFinding = 50

	// MaxLocationsPerDataFlow is the maximum number of locations allowed per data flow.
	// Prevents excessively long attack paths from consuming resources.
	MaxLocationsPerDataFlow = 100

	// MaxFunctionNameSize is the maximum size of a function name in bytes.
	MaxFunctionNameSize = 500

	// MaxClassNameSize is the maximum size of a class name in bytes.
	MaxClassNameSize = 500
)

Size limits for data flow fields (DoS protection).

Variables

View Source
var (
	ErrVulnerabilityNotFound      = fmt.Errorf("vulnerability %w", shared.ErrNotFound)
	ErrVulnerabilityAlreadyExists = fmt.Errorf("vulnerability %w", shared.ErrAlreadyExists)
	ErrFindingNotFound            = fmt.Errorf("finding %w", shared.ErrNotFound)
	ErrFindingAlreadyExists       = fmt.Errorf("finding %w", shared.ErrAlreadyExists)
)

Domain errors for vulnerability.

View Source
var ErrConcurrentModification = fmt.Errorf("%w: approval was modified by another user", shared.ErrConflict)

ErrConcurrentModification is returned when an approval was modified by another user.

View Source
var ErrSelfApproval = fmt.Errorf("%w: cannot approve your own request", shared.ErrValidation)

ErrSelfApproval is returned when a user tries to approve their own request.

ValidStatusTransitions defines valid status transitions.

Closed-loop lifecycle:

new → confirmed → in_progress → fix_applied → resolved
                                     ↑              ↑
                                  Dev/Owner      Scanner verify
                                  (fix_apply)    OR Security manual

Dev/Owner can mark fix_applied but CANNOT resolve directly. Scanner or Security (findings:verify) transitions fix_applied → resolved. confirmed → resolved is kept as Admin/Owner escape hatch for urgent cases.

Terminal: false_positive, accepted, duplicate (can reopen to confirmed)

Functions

func FindingAllowedSortFields

func FindingAllowedSortFields() map[string]string

FindingAllowedSortFields returns the allowed sort fields for findings. severity uses a CASE expression so critical sorts highest, not alphabetically.

func FindingAlreadyExistsError

func FindingAlreadyExistsError(fingerprint string) error

FindingAlreadyExistsError returns an already exists error with the fingerprint.

func FindingNotFoundError

func FindingNotFoundError(id shared.ID) error

FindingNotFoundError returns a not found error with the finding ID.

func GenerateFingerprintWithStrategy

func GenerateFingerprintWithStrategy(f *Finding) string

GenerateFingerprintWithStrategy generates a fingerprint using the appropriate strategy. It also populates partial_fingerprints for multi-algorithm support.

func IsValidCVE

func IsValidCVE(cveID string) bool

IsValidCVE checks if the CVE ID format is valid.

func IsValidLocationType

func IsValidLocationType(locationType string) bool

IsValidLocationType checks if a location type is valid.

func VulnerabilityAllowedSortFields

func VulnerabilityAllowedSortFields() map[string]string

VulnerabilityAllowedSortFields returns the allowed sort fields for vulnerabilities.

func VulnerabilityAlreadyExistsError

func VulnerabilityAlreadyExistsError(cveID string) error

VulnerabilityAlreadyExistsError returns an already exists error with the CVE ID.

func VulnerabilityNotFoundByCVEError

func VulnerabilityNotFoundByCVEError(cveID string) error

VulnerabilityNotFoundByCVEError returns a not found error with the CVE ID.

func VulnerabilityNotFoundError

func VulnerabilityNotFoundError(id shared.ID) error

VulnerabilityNotFoundError returns a not found error with the vulnerability ID.

Types

type ActivityChanges

type ActivityChanges struct {
	// Status changes
	OldStatus string `json:"old_status,omitempty"`
	NewStatus string `json:"new_status,omitempty"`
	Reason    string `json:"reason,omitempty"`

	// Severity changes
	OldSeverity string `json:"old_severity,omitempty"`
	NewSeverity string `json:"new_severity,omitempty"`

	// Assignment
	AssigneeID    string `json:"assignee_id,omitempty"`
	AssigneeName  string `json:"assignee_name,omitempty"`
	AssigneeEmail string `json:"assignee_email,omitempty"`

	// Comments
	CommentID string `json:"comment_id,omitempty"`
	Preview   string `json:"preview,omitempty"` // First 100 chars of comment

	// Scanning
	ScanID   string `json:"scan_id,omitempty"`
	Scanner  string `json:"scanner,omitempty"`
	ScanType string `json:"scan_type,omitempty"`

	// Linking
	LinkedType string `json:"linked_type,omitempty"` // jira, github, etc.
	LinkedID   string `json:"linked_id,omitempty"`
	LinkedURL  string `json:"linked_url,omitempty"`

	// Triage
	TriageStatus string `json:"triage_status,omitempty"`
	TriageReason string `json:"triage_reason,omitempty"`

	// AI Triage
	AIRiskLevel      string `json:"ai_risk_level,omitempty"`
	AIConfidence     string `json:"ai_confidence,omitempty"`
	AIRecommendation string `json:"ai_recommendation,omitempty"`
}

ActivityChanges provides typed access to common change patterns.

type ActivitySource

type ActivitySource string

ActivitySource represents where the activity originated.

const (
	SourceAPI       ActivitySource = "api"
	SourceUI        ActivitySource = "ui"
	SourceCI        ActivitySource = "ci"
	SourceWebhook   ActivitySource = "webhook"
	SourceScheduled ActivitySource = "scheduled"
	SourceAuto      ActivitySource = "auto"
	SourceImport    ActivitySource = "import"
)

type ActivityType

type ActivityType string

ActivityType represents the type of finding activity.

const (
	// Lifecycle activities
	ActivityCreated         ActivityType = "created"
	ActivityStatusChanged   ActivityType = "status_changed"
	ActivitySeverityChanged ActivityType = "severity_changed"
	ActivityResolved        ActivityType = "resolved"
	ActivityReopened        ActivityType = "reopened"

	// Assignment activities
	ActivityAssigned   ActivityType = "assigned"
	ActivityUnassigned ActivityType = "unassigned"

	// Triage activities
	ActivityTriageUpdated       ActivityType = "triage_updated"
	ActivityFalsePositiveMarked ActivityType = "false_positive_marked"
	ActivityDuplicateMarked     ActivityType = "duplicate_marked"
	ActivityDuplicateUnmarked   ActivityType = "duplicate_unmarked"

	// Verification & remediation activities
	ActivityVerified           ActivityType = "verified"            // Finding verified by user
	ActivityRemediationUpdated ActivityType = "remediation_updated" // Remediation info updated
	ActivityMetadataUpdated    ActivityType = "metadata_updated"    // Finding metadata updated
	ActivityAcceptanceExpired  ActivityType = "acceptance_expired"  // Risk acceptance expired

	// Comment activities
	ActivityCommentAdded   ActivityType = "comment_added"
	ActivityCommentUpdated ActivityType = "comment_updated"
	ActivityCommentDeleted ActivityType = "comment_deleted"

	// Scanning activities
	ActivityScanDetected ActivityType = "scan_detected"
	ActivityAutoResolved ActivityType = "auto_resolved"
	ActivityAutoReopened ActivityType = "auto_reopened"

	// Integration activities
	ActivityLinked   ActivityType = "linked"
	ActivityUnlinked ActivityType = "unlinked"

	// SLA activities
	ActivitySLAWarning ActivityType = "sla_warning"
	ActivitySLABreach  ActivityType = "sla_breach"

	// AI activities
	ActivityAITriageRequested ActivityType = "ai_triage_requested" // User requested AI triage
	ActivityAITriage          ActivityType = "ai_triage"           // AI triage completed successfully
	ActivityAITriageFailed    ActivityType = "ai_triage_failed"    // AI triage failed

	// Approval activities
	ActivityApprovalRequested ActivityType = "approval_requested" // User requested status approval
	ActivityApprovalApproved  ActivityType = "approval_approved"  // Approval was approved
	ActivityApprovalRejected  ActivityType = "approval_rejected"  // Approval was rejected
	ActivityApprovalCanceled  ActivityType = "approval_canceled"  // Approval was canceled by requester
)

type ActorType

type ActorType string

ActorType represents who/what performed the activity.

const (
	ActorTypeUser        ActorType = "user"
	ActorTypeSystem      ActorType = "system"
	ActorTypeScanner     ActorType = "scanner"
	ActorTypeIntegration ActorType = "integration"
	ActorTypeAI          ActorType = "ai"
)

type AffectedVersion

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

AffectedVersion represents an affected version range.

func NewAffectedVersion

func NewAffectedVersion(ecosystem, pkg, introduced, fixed string) AffectedVersion

NewAffectedVersion creates a new AffectedVersion.

func (AffectedVersion) Ecosystem

func (a AffectedVersion) Ecosystem() string

Ecosystem returns the ecosystem.

func (AffectedVersion) Fixed

func (a AffectedVersion) Fixed() string

Fixed returns the fixed version.

func (AffectedVersion) Introduced

func (a AffectedVersion) Introduced() string

Introduced returns the introduced version.

func (AffectedVersion) Package

func (a AffectedVersion) Package() string

Package returns the package name.

type Approval added in v0.1.2

type Approval struct {
	ID              shared.ID
	TenantID        shared.ID
	FindingID       shared.ID
	RequestedStatus string
	RequestedBy     shared.ID
	Justification   string
	ApprovedBy      *shared.ID
	ApprovedAt      *time.Time
	RejectedBy      *shared.ID
	RejectedAt      *time.Time
	RejectionReason string
	Status          ApprovalStatus
	ExpiresAt       *time.Time
	CreatedAt       time.Time
	Version         int
}

Approval represents a finding status approval request.

func NewApproval added in v0.1.2

func NewApproval(
	tenantID, findingID, requestedBy shared.ID,
	requestedStatus, justification string,
	expiresAt *time.Time,
) *Approval

NewApproval creates a new pending approval request.

func (*Approval) Approve added in v0.1.2

func (a *Approval) Approve(approvedBy shared.ID) error

Approve marks the approval as approved.

func (*Approval) Cancel added in v0.1.2

func (a *Approval) Cancel() error

Cancel marks the approval as canceled.

func (*Approval) Expire added in v0.1.2

func (a *Approval) Expire() error

Expire marks an approved approval as expired. This is used by the background expiration controller when the acceptance period ends.

func (*Approval) IsExpired added in v0.1.2

func (a *Approval) IsExpired() bool

IsExpired returns true if the approval has expired.

func (*Approval) IsPending added in v0.1.2

func (a *Approval) IsPending() bool

IsPending returns true if the approval is still pending.

func (*Approval) Reject added in v0.1.2

func (a *Approval) Reject(rejectedBy shared.ID, reason string) error

Reject marks the approval as rejected.

type ApprovalFilter added in v0.1.2

type ApprovalFilter struct {
	TenantID  *shared.ID
	FindingID *shared.ID
	Status    *ApprovalStatus
}

ApprovalFilter represents filter options for listing approvals.

type ApprovalRepository added in v0.1.2

type ApprovalRepository interface {
	// Create creates a new approval request.
	Create(ctx context.Context, approval *Approval) error

	// GetByTenantAndID retrieves an approval by tenant and ID.
	// Note: No GetByID without tenant — all queries must be tenant-scoped for isolation.
	GetByTenantAndID(ctx context.Context, tenantID, id shared.ID) (*Approval, error)

	// ListByFinding retrieves all approvals for a finding.
	ListByFinding(ctx context.Context, tenantID, findingID shared.ID) ([]*Approval, error)

	// ListPending retrieves all pending approvals for a tenant.
	ListPending(ctx context.Context, tenantID shared.ID, page pagination.Pagination) (pagination.Result[*Approval], error)

	// Update updates an approval.
	Update(ctx context.Context, approval *Approval) error

	// ListExpiredApproved retrieves all approved approvals that have expired.
	// This is a cross-tenant query used by the background expiration controller.
	// Returns approvals where status='approved', expires_at IS NOT NULL, and expires_at < NOW().
	ListExpiredApproved(ctx context.Context, limit int) ([]*Approval, error)
}

ApprovalRepository defines the interface for finding status approval persistence.

type ApprovalStatus added in v0.1.2

type ApprovalStatus string

ApprovalStatus represents the status of a finding status approval request.

const (
	ApprovalStatusPending  ApprovalStatus = "pending"
	ApprovalStatusApproved ApprovalStatus = "approved"
	ApprovalStatusRejected ApprovalStatus = "rejected"
	ApprovalStatusCanceled ApprovalStatus = "canceled"
	ApprovalStatusExpired  ApprovalStatus = "expired"
)

type ArtifactLocation

type ArtifactLocation struct {
	URI       string `json:"uri,omitempty"`
	URIBaseID string `json:"uri_base_id,omitempty"`
}

ArtifactLocation represents the location of an artifact file.

type Attachment

type Attachment struct {
	Type             AttachmentType    `json:"type,omitempty"`              // Attachment type for UI categorization
	Description      string            `json:"description,omitempty"`       // Human-readable description
	ArtifactLocation *ArtifactLocation `json:"artifact_location,omitempty"` // Location of the artifact
	Regions          []FindingLocation `json:"regions,omitempty"`           // Relevant regions in the artifact
	Rectangles       []Rectangle       `json:"rectangles,omitempty"`        // Highlight areas (for images)
}

Attachment represents an artifact or evidence file (SARIF attachment with extensions).

type AttachmentType

type AttachmentType string

AttachmentType represents the type of attachment.

const (
	AttachmentTypeEvidence   AttachmentType = "evidence"   // Supporting evidence (CVE details, advisory links)
	AttachmentTypeScreenshot AttachmentType = "screenshot" // Screenshot image
	AttachmentTypeDocument   AttachmentType = "document"   // Documentation, reports
	AttachmentTypeReference  AttachmentType = "reference"  // External reference links
	AttachmentTypeCode       AttachmentType = "code"       // Code snippet or file
	AttachmentTypeOther      AttachmentType = "other"      // Other attachment types
)

type BaselineState

type BaselineState string

BaselineState represents the finding's status relative to a baseline (SARIF baselineState).

const (
	BaselineStateNew       BaselineState = "new"       // Not present in baseline
	BaselineStateUnchanged BaselineState = "unchanged" // Identical to baseline
	BaselineStateUpdated   BaselineState = "updated"   // Modified since baseline
	BaselineStateAbsent    BaselineState = "absent"    // Was in baseline, now gone
)

func ParseBaselineState

func ParseBaselineState(s string) (BaselineState, error)

ParseBaselineState parses a string into a BaselineState.

func (BaselineState) IsValid

func (b BaselineState) IsValid() bool

IsValid checks if the baseline state is valid.

func (BaselineState) String

func (b BaselineState) String() string

String returns the string representation.

type BatchCreateResult

type BatchCreateResult struct {
	// Created is the number of findings successfully created.
	Created int
	// Updated is the number of existing findings updated (via ON CONFLICT).
	Updated int
	// Skipped is the number of findings skipped due to errors.
	Skipped int
	// Errors contains error messages for failed findings.
	// Key is the finding index (0-based), value is the error message.
	Errors map[int]string
}

BatchCreateResult contains the result of a batch create operation. It supports partial success - some findings may fail while others succeed.

func (*BatchCreateResult) HasErrors

func (r *BatchCreateResult) HasErrors() bool

HasErrors returns true if any findings failed to create.

func (*BatchCreateResult) TotalProcessed

func (r *BatchCreateResult) TotalProcessed() int

TotalProcessed returns the total number of findings processed.

type CISAKEV

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

CISAKEV represents CISA Known Exploited Vulnerabilities data.

func NewCISAKEV

func NewCISAKEV(dateAdded, dueDate time.Time, ransomwareUse, notes string) CISAKEV

NewCISAKEV creates a new CISAKEV.

func (CISAKEV) DateAdded

func (c CISAKEV) DateAdded() time.Time

DateAdded returns the date added to KEV.

func (CISAKEV) DueDate

func (c CISAKEV) DueDate() time.Time

DueDate returns the remediation due date.

func (CISAKEV) IsPastDue

func (c CISAKEV) IsPastDue() bool

IsPastDue checks if the due date has passed.

func (CISAKEV) IsZero

func (c CISAKEV) IsZero() bool

IsZero checks if the CISAKEV is empty.

func (CISAKEV) Notes

func (c CISAKEV) Notes() string

Notes returns additional notes.

func (CISAKEV) RansomwareUse

func (c CISAKEV) RansomwareUse() string

RansomwareUse returns ransomware use info.

type ComplianceDetails

type ComplianceDetails struct {
	Framework   string           `json:"framework,omitempty"`    // CIS, SOC2, PCI-DSS, HIPAA, GDPR, ISO27001, NIST
	ControlID   string           `json:"control_id,omitempty"`   // Control ID within framework
	ControlName string           `json:"control_name,omitempty"` // Human-readable control name
	Section     string           `json:"section,omitempty"`      // Section/domain within framework
	Result      ComplianceResult `json:"result,omitempty"`       // pass, fail, manual, not_applicable
	Evidence    string           `json:"evidence,omitempty"`     // Evidence for the result
}

ComplianceDetails contains details specific to compliance findings.

type ComplianceFingerprintStrategy

type ComplianceFingerprintStrategy struct{}

ComplianceFingerprintStrategy generates fingerprints for compliance findings. Focuses on: asset, framework, control ID, and resource path.

func (*ComplianceFingerprintStrategy) Generate

func (*ComplianceFingerprintStrategy) Name

type ComplianceResult

type ComplianceResult string

ComplianceResult represents the result of a compliance check.

const (
	ComplianceResultPass          ComplianceResult = "pass"
	ComplianceResultFail          ComplianceResult = "fail"
	ComplianceResultManual        ComplianceResult = "manual"
	ComplianceResultNotApplicable ComplianceResult = "not_applicable"
	ComplianceResultError         ComplianceResult = "error"
	ComplianceResultUnknown       ComplianceResult = "unknown"
)

func (ComplianceResult) IsValid

func (c ComplianceResult) IsValid() bool

IsValid checks if the compliance result is valid.

type DASTFingerprintStrategy

type DASTFingerprintStrategy struct{}

DASTFingerprintStrategy generates fingerprints for DAST findings. Focuses on: asset, rule, endpoint URL, and parameter name.

func (*DASTFingerprintStrategy) Generate

func (s *DASTFingerprintStrategy) Generate(f *Finding) string

func (*DASTFingerprintStrategy) Name

func (s *DASTFingerprintStrategy) Name() string

type DataExposureRisk

type DataExposureRisk string

DataExposureRisk represents the risk of data exposure from a finding.

const (
	DataExposureRiskNone     DataExposureRisk = "none"     // No data exposure risk
	DataExposureRiskLow      DataExposureRisk = "low"      // Low data exposure risk
	DataExposureRiskMedium   DataExposureRisk = "medium"   // Medium data exposure risk
	DataExposureRiskHigh     DataExposureRisk = "high"     // High data exposure risk
	DataExposureRiskCritical DataExposureRisk = "critical" // Critical data exposure risk
)

func AllDataExposureRisks

func AllDataExposureRisks() []DataExposureRisk

AllDataExposureRisks returns all valid data exposure risks.

func ParseDataExposureRisk

func ParseDataExposureRisk(s string) (DataExposureRisk, error)

ParseDataExposureRisk parses a string into a DataExposureRisk.

func (DataExposureRisk) IsValid

func (d DataExposureRisk) IsValid() bool

IsValid checks if the data exposure risk is valid.

func (DataExposureRisk) RiskMultiplier

func (d DataExposureRisk) RiskMultiplier() float64

RiskMultiplier returns a risk multiplier based on data exposure risk.

func (DataExposureRisk) String

func (d DataExposureRisk) String() string

String returns the string representation.

type DataFlow

type DataFlow struct {
	Index      int            `json:"index"`                // Flow index within finding
	Message    string         `json:"message,omitempty"`    // Flow description
	Importance string         `json:"importance,omitempty"` // essential, important, unimportant
	Steps      []DataFlowStep `json:"steps,omitempty"`      // Ordered steps from source to sink

	// Extended taint tracking metadata (from CTIS DataFlow)
	Tainted           bool     `json:"tainted"`                      // Whether data is still tainted at sink
	TaintType         string   `json:"taint_type,omitempty"`         // user_input, file_read, env_var, network, database, etc.
	VulnerabilityType string   `json:"vulnerability_type,omitempty"` // sql_injection, xss, command_injection, etc.
	Confidence        int      `json:"confidence,omitempty"`         // 0-100 confidence score
	Interprocedural   bool     `json:"interprocedural,omitempty"`    // Whether flow crosses function boundaries
	CrossFile         bool     `json:"cross_file,omitempty"`         // Whether flow crosses file boundaries
	CallPath          []string `json:"call_path,omitempty"`          // Ordered list of function names in call chain
}

DataFlow represents a complete data flow trace (taint tracking path).

func (DataFlow) GetSink

func (d DataFlow) GetSink() *DataFlowStep

GetSink returns the sink step (last step with location_type = "sink").

func (DataFlow) GetSource

func (d DataFlow) GetSource() *DataFlowStep

GetSource returns the source step (first step with location_type = "source").

type DataFlowRepository

type DataFlowRepository interface {
	// CreateDataFlow persists a new data flow.
	CreateDataFlow(ctx context.Context, flow *FindingDataFlow) error

	// CreateDataFlowBatch persists multiple data flows.
	CreateDataFlowBatch(ctx context.Context, flows []*FindingDataFlow) error

	// GetDataFlowByID retrieves a data flow by ID.
	GetDataFlowByID(ctx context.Context, id shared.ID) (*FindingDataFlow, error)

	// ListDataFlowsByFinding retrieves all data flows for a finding.
	ListDataFlowsByFinding(ctx context.Context, findingID shared.ID) ([]*FindingDataFlow, error)

	// GetDataFlowsWithLocations retrieves all data flows for a finding with their locations in a single query.
	// This is an optimized method to avoid N+1 queries when loading data flows.
	// Returns a map of flow ID -> []FlowLocation for efficient lookup.
	GetDataFlowsWithLocations(ctx context.Context, findingID shared.ID) ([]*FindingDataFlow, map[string][]*FindingFlowLocation, error)

	// GetDataFlowsWithLocationsByTenant retrieves data flows with tenant verification.
	// SECURITY: Provides defense-in-depth by verifying finding belongs to tenant.
	// Use when tenant context is available to prevent IDOR attacks.
	GetDataFlowsWithLocationsByTenant(ctx context.Context, findingID, tenantID shared.ID) ([]*FindingDataFlow, map[string][]*FindingFlowLocation, error)

	// DeleteDataFlowsByFinding removes all data flows for a finding.
	DeleteDataFlowsByFinding(ctx context.Context, findingID shared.ID) error

	// CreateFlowLocation persists a new flow location.
	CreateFlowLocation(ctx context.Context, location *FindingFlowLocation) error

	// CreateFlowLocationBatch persists multiple flow locations.
	CreateFlowLocationBatch(ctx context.Context, locations []*FindingFlowLocation) error

	// GetFlowLocationByID retrieves a flow location by ID.
	GetFlowLocationByID(ctx context.Context, id shared.ID) (*FindingFlowLocation, error)

	// ListFlowLocationsByDataFlow retrieves all locations for a data flow.
	ListFlowLocationsByDataFlow(ctx context.Context, dataFlowID shared.ID) ([]*FindingFlowLocation, error)

	// ListFlowLocationsByFile retrieves all flow locations in a file for a specific tenant.
	// SECURITY: Requires tenantID to enforce tenant isolation.
	// Useful for attack path analysis: "find all data flows through this file".
	ListFlowLocationsByFile(ctx context.Context, tenantID shared.ID, filePath string, page pagination.Pagination) (pagination.Result[*FindingFlowLocation], error)

	// ListFlowLocationsByFunction retrieves all flow locations in a function for a specific tenant.
	// SECURITY: Requires tenantID to enforce tenant isolation.
	// Useful for attack path analysis: "find all data flows through this function".
	ListFlowLocationsByFunction(ctx context.Context, tenantID shared.ID, functionName string, page pagination.Pagination) (pagination.Result[*FindingFlowLocation], error)

	// ListSourcesAndSinks retrieves all source and sink locations for a finding.
	// Useful for displaying the entry/exit points of taint tracking.
	ListSourcesAndSinks(ctx context.Context, findingID shared.ID) ([]*FindingFlowLocation, error)

	// DeleteFlowLocationsByDataFlow removes all locations for a data flow.
	DeleteFlowLocationsByDataFlow(ctx context.Context, dataFlowID shared.ID) error
}

DataFlowRepository defines the interface for finding data flow persistence.

type DataFlowStep

type DataFlowStep struct {
	Index              int              `json:"index"`                          // Step order (0 = source)
	LocationType       string           `json:"location_type"`                  // source, intermediate, sink, sanitizer
	Location           *FindingLocation `json:"location,omitempty"`             // Physical location
	Label              string           `json:"label,omitempty"`                // Variable/expression name
	Message            string           `json:"message,omitempty"`              // What happens at this step
	NestingLevel       int              `json:"nesting_level,omitempty"`        // For display indentation
	Importance         string           `json:"importance,omitempty"`           // essential, important, unimportant
	FunctionName       string           `json:"function_name,omitempty"`        // Function context
	ClassName          string           `json:"class_name,omitempty"`           // Class context
	ModuleName         string           `json:"module_name,omitempty"`          // Module context
	FullyQualifiedName string           `json:"fully_qualified_name,omitempty"` // Full path

	// Extended operation tracking (from CTIS DataFlowLocation)
	Operation      string `json:"operation,omitempty"`       // assignment, call, return, parameter, concat, etc.
	CalledFunction string `json:"called_function,omitempty"` // For call operations: the function being called
	ParameterIndex int    `json:"parameter_index,omitempty"` // For parameter operations: 0-indexed parameter position
	TaintState     string `json:"taint_state,omitempty"`     // tainted, sanitized, unknown
	Transformation string `json:"transformation,omitempty"`  // encode, decode, escape, hash, encrypt, etc.
}

DataFlowStep represents a single step in a data flow trace.

type DefaultFingerprintStrategy

type DefaultFingerprintStrategy struct{}

DefaultFingerprintStrategy is the legacy fingerprint algorithm for backward compatibility.

func (*DefaultFingerprintStrategy) Generate

func (s *DefaultFingerprintStrategy) Generate(f *Finding) string

func (*DefaultFingerprintStrategy) Name

type ExploitMaturity

type ExploitMaturity string

ExploitMaturity represents the exploit maturity level.

const (
	ExploitMaturityNone           ExploitMaturity = "none"
	ExploitMaturityProofOfConcept ExploitMaturity = "poc"
	ExploitMaturityFunctional     ExploitMaturity = "functional"
	ExploitMaturityWeaponized     ExploitMaturity = "weaponized"
)

func (ExploitMaturity) IsValid

func (e ExploitMaturity) IsValid() bool

IsValid checks if the exploit maturity is valid.

func (ExploitMaturity) String

func (e ExploitMaturity) String() string

String returns the string representation.

type ExposureVector

type ExposureVector string

ExposureVector represents how a finding can be exploited.

const (
	ExposureVectorNetwork     ExposureVector = "network"      // Remotely exploitable over network
	ExposureVectorLocal       ExposureVector = "local"        // Local access required
	ExposureVectorPhysical    ExposureVector = "physical"     // Physical access required
	ExposureVectorAdjacentNet ExposureVector = "adjacent_net" // Same network segment required
	ExposureVectorUnknown     ExposureVector = "unknown"      // Unknown exposure vector
)

func AllExposureVectors

func AllExposureVectors() []ExposureVector

AllExposureVectors returns all valid exposure vectors.

func ParseExposureVector

func ParseExposureVector(s string) (ExposureVector, error)

ParseExposureVector parses a string into an ExposureVector.

func (ExposureVector) IsValid

func (e ExposureVector) IsValid() bool

IsValid checks if the exposure vector is valid.

func (ExposureVector) RiskMultiplier

func (e ExposureVector) RiskMultiplier() float64

RiskMultiplier returns a risk multiplier based on exposure vector.

func (ExposureVector) String

func (e ExposureVector) String() string

String returns the string representation.

type Finding

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

Finding represents a specific instance of a vulnerability in an asset.

func NewFinding

func NewFinding(
	tenantID shared.ID,
	assetID shared.ID,
	source FindingSource,
	toolName string,
	severity Severity,
	message string,
) (*Finding, error)

NewFinding creates a new Finding.

func ReconstituteFinding

func ReconstituteFinding(data FindingData) *Finding

ReconstituteFinding recreates a Finding from persistence.

func (*Finding) ASVSControlID

func (f *Finding) ASVSControlID() string

ASVSControlID returns the ASVS control ID.

func (*Finding) ASVSControlURL

func (f *Finding) ASVSControlURL() string

ASVSControlURL returns the ASVS control URL.

func (*Finding) ASVSLevel

func (f *Finding) ASVSLevel() *int

ASVSLevel returns the ASVS level (1, 2, or 3).

func (*Finding) ASVSSection

func (f *Finding) ASVSSection() string

ASVSSection returns the ASVS section.

func (*Finding) AcceptanceExpiresAt

func (f *Finding) AcceptanceExpiresAt() *time.Time

AcceptanceExpiresAt returns when the risk acceptance expires.

func (*Finding) AddAttachment

func (f *Finding) AddAttachment(attachment Attachment)

AddAttachment adds an attachment.

func (*Finding) AddComplianceImpact

func (f *Finding) AddComplianceImpact(framework string)

AddComplianceImpact adds a compliance framework to the impact list.

func (*Finding) AddDataFlow

func (f *Finding) AddDataFlow(flow DataFlow)

AddDataFlow adds a data flow.

func (*Finding) AddPartialFingerprint

func (f *Finding) AddPartialFingerprint(key, value string)

AddPartialFingerprint adds a partial fingerprint.

func (*Finding) AddRelatedLocation

func (f *Finding) AddRelatedLocation(location FindingLocation)

AddRelatedLocation adds a related location.

func (*Finding) AddStack

func (f *Finding) AddStack(stack StackTrace)

AddStack adds a stack trace.

func (*Finding) AddTag

func (f *Finding) AddTag(tag string)

AddTag adds a tag.

func (*Finding) AddWorkItemURI

func (f *Finding) AddWorkItemURI(uri string)

AddWorkItemURI adds a work item URI.

func (*Finding) Age

func (f *Finding) Age() time.Duration

Age returns the age of the finding since creation.

func (*Finding) AgentID

func (f *Finding) AgentID() *shared.ID

AgentID returns the agent ID that submitted this finding.

func (*Finding) AssetID

func (f *Finding) AssetID() shared.ID

AssetID returns the asset ID.

func (*Finding) Assign

func (f *Finding) Assign(userID, assignerID shared.ID) error

Assign assigns the finding to a user.

func (*Finding) AssignedAt

func (f *Finding) AssignedAt() *time.Time

AssignedAt returns when the finding was assigned.

func (*Finding) AssignedBy

func (f *Finding) AssignedBy() *shared.ID

AssignedBy returns who assigned the finding.

func (*Finding) AssignedTo

func (f *Finding) AssignedTo() *shared.ID

AssignedTo returns who the finding is assigned to.

func (*Finding) Attachments

func (f *Finding) Attachments() []Attachment

Attachments returns the attachments.

func (*Finding) AttackPrerequisites

func (f *Finding) AttackPrerequisites() string

AttackPrerequisites returns the attack prerequisites.

func (*Finding) BaselineState

func (f *Finding) BaselineState() string

BaselineState returns the baseline state.

func (*Finding) BranchID

func (f *Finding) BranchID() *shared.ID

BranchID returns the branch ID.

func (*Finding) CTEMRiskFactor

func (f *Finding) CTEMRiskFactor() float64

CTEMRiskFactor returns a risk multiplier based on CTEM factors.

func (*Finding) CVEID

func (f *Finding) CVEID() string

CVEID returns the CVE ID.

func (*Finding) CVSSScore

func (f *Finding) CVSSScore() *float64

CVSSScore returns the CVSS score.

func (*Finding) CVSSVector

func (f *Finding) CVSSVector() string

CVSSVector returns the CVSS vector.

func (*Finding) CWEIDs

func (f *Finding) CWEIDs() []string

CWEIDs returns the CWE IDs.

func (*Finding) CanTransitionTo

func (f *Finding) CanTransitionTo(newStatus FindingStatus) bool

CanTransitionTo checks if the finding can transition to the given status. Uses the ValidStatusTransitions defined in value_objects.go

func (*Finding) ClosedAt

func (f *Finding) ClosedAt() *time.Time

ClosedAt returns the closed time.

func (*Finding) ClosedBy

func (f *Finding) ClosedBy() *shared.ID

ClosedBy returns who closed the finding.

func (*Finding) CommentsCount

func (f *Finding) CommentsCount() int

CommentsCount returns the number of comments.

func (*Finding) ComplianceControlDescription

func (f *Finding) ComplianceControlDescription() string

ComplianceControlDescription returns the compliance control description (for compliance findings).

func (*Finding) ComplianceControlID

func (f *Finding) ComplianceControlID() string

ComplianceControlID returns the compliance control ID (for compliance findings).

func (*Finding) ComplianceControlName

func (f *Finding) ComplianceControlName() string

ComplianceControlName returns the compliance control name (for compliance findings).

func (*Finding) ComplianceFramework

func (f *Finding) ComplianceFramework() string

ComplianceFramework returns the compliance framework (for compliance findings).

func (*Finding) ComplianceFrameworkVersion

func (f *Finding) ComplianceFrameworkVersion() string

ComplianceFrameworkVersion returns the compliance framework version (for compliance findings).

func (*Finding) ComplianceImpact

func (f *Finding) ComplianceImpact() []string

ComplianceImpact returns the compliance frameworks impacted.

func (*Finding) ComplianceResult

func (f *Finding) ComplianceResult() string

ComplianceResult returns the compliance result (for compliance findings).

func (*Finding) ComplianceSection

func (f *Finding) ComplianceSection() string

ComplianceSection returns the compliance section (for compliance findings).

func (*Finding) ComponentID

func (f *Finding) ComponentID() *shared.ID

ComponentID returns the component ID.

func (*Finding) Confidence

func (f *Finding) Confidence() *int

Confidence returns the confidence score (0-100).

func (*Finding) ContextSnippet

func (f *Finding) ContextSnippet() string

ContextSnippet returns the surrounding code context.

func (*Finding) ContextStartLine

func (f *Finding) ContextStartLine() int

ContextStartLine returns the line number where context begins.

func (*Finding) CorrelationID

func (f *Finding) CorrelationID() string

CorrelationID returns the correlation ID.

func (*Finding) CreatedAt

func (f *Finding) CreatedAt() time.Time

CreatedAt returns the creation time.

func (*Finding) CreatedBy added in v0.1.6

func (f *Finding) CreatedBy() *shared.ID

CreatedBy returns the user ID who created this finding (if known). Nil for findings produced by automated scanners.

func (*Finding) DataExposureRisk

func (f *Finding) DataExposureRisk() DataExposureRisk

DataExposureRisk returns the data exposure risk.

func (*Finding) DataFlows

func (f *Finding) DataFlows() []DataFlow

DataFlows returns the data flows (for SAST taint tracking).

func (*Finding) DecrementCommentsCount

func (f *Finding) DecrementCommentsCount()

DecrementCommentsCount decrements the comments count.

func (*Finding) DeleteMetadata

func (f *Finding) DeleteMetadata(key string)

DeleteMetadata removes a metadata key.

func (*Finding) Description

func (f *Finding) Description() string

Description returns the description.

func (*Finding) DuplicateCount

func (f *Finding) DuplicateCount() int

DuplicateCount returns the number of duplicates.

func (*Finding) DuplicateOf

func (f *Finding) DuplicateOf() *shared.ID

DuplicateOf returns the ID of the finding this is a duplicate of.

func (*Finding) EndColumn

func (f *Finding) EndColumn() int

EndColumn returns the end column.

func (*Finding) EndLine

func (f *Finding) EndLine() int

EndLine returns the end line.

func (*Finding) EnrichFrom

func (f *Finding) EnrichFrom(other *Finding)

EnrichFrom updates this finding with non-null values from another finding using selective enrichment rules: - Protected fields (status, resolution, resolved_by, resolved_at) are NEVER overwritten - FirstWins fields (secret_type, web3_chain, etc.) only set if currently empty - LastWins fields (description, snippet, etc.) update with new non-null values - MaxValue fields (cvss_score) keep the maximum value - Append fields (tags, cwe_ids) accumulate unique values - Merge fields (metadata) deep merge objects

func (*Finding) EstimatedFixTime

func (f *Finding) EstimatedFixTime() *int

EstimatedFixTime returns the estimated fix time in minutes.

func (*Finding) ExposureVector

func (f *Finding) ExposureVector() ExposureVector

ExposureVector returns the exposure vector.

func (*Finding) FilePath

func (f *Finding) FilePath() string

FilePath returns the file path.

func (*Finding) FindingType

func (f *Finding) FindingType() FindingType

FindingType returns the finding type discriminator.

func (*Finding) Fingerprint

func (f *Finding) Fingerprint() string

Fingerprint returns the fingerprint.

func (*Finding) FirstDetectedAt

func (f *Finding) FirstDetectedAt() time.Time

FirstDetectedAt returns when the finding was first detected.

func (*Finding) FirstDetectedBranch

func (f *Finding) FirstDetectedBranch() string

FirstDetectedBranch returns the branch where first detected.

func (*Finding) FirstDetectedCommit

func (f *Finding) FirstDetectedCommit() string

FirstDetectedCommit returns the commit where first detected.

func (*Finding) FixCode

func (f *Finding) FixCode() string

FixCode returns the auto-fix code snippet.

func (*Finding) FixComplexity

func (f *Finding) FixComplexity() FixComplexity

FixComplexity returns the fix complexity.

func (*Finding) FixRegex

func (f *Finding) FixRegex() *FixRegex

FixRegex returns the regex-based fix pattern.

func (*Finding) ForceStatus added in v0.1.2

func (f *Finding) ForceStatus(status FindingStatus)

ForceStatus sets the finding status bypassing transition validation. Internal use only — for pentest service to set pentest-specific statuses.

func (*Finding) GenerateFingerprint

func (f *Finding) GenerateFingerprint() string

GenerateFingerprint generates a fingerprint based on finding attributes.

func (*Finding) HasComponent

func (f *Finding) HasComponent() bool

HasComponent checks if the finding is linked to a component.

func (*Finding) HasDataFlow

func (f *Finding) HasDataFlow() bool

HasDataFlow returns true if this finding has data flow traces. This is a lightweight flag populated from database for list views.

func (*Finding) HasLocation

func (f *Finding) HasLocation() bool

HasLocation checks if the finding has location info.

func (*Finding) HasVulnerability

func (f *Finding) HasVulnerability() bool

HasVulnerability checks if the finding is linked to a vulnerability.

func (*Finding) HostedViewerURI

func (f *Finding) HostedViewerURI() string

HostedViewerURI returns the hosted viewer URI.

func (*Finding) ID

func (f *Finding) ID() shared.ID

ID returns the finding ID.

func (*Finding) Impact

func (f *Finding) Impact() string

Impact returns the impact level.

func (*Finding) IncrementCommentsCount

func (f *Finding) IncrementCommentsCount()

IncrementCommentsCount increments the comments count.

func (*Finding) IncrementDuplicateCount

func (f *Finding) IncrementDuplicateCount()

IncrementDuplicateCount increments the duplicate count.

func (*Finding) IncrementOccurrenceCount

func (f *Finding) IncrementOccurrenceCount()

IncrementOccurrenceCount increments the occurrence count.

func (*Finding) IsClosed

func (f *Finding) IsClosed() bool

IsClosed checks if the finding is closed.

func (*Finding) IsCritical

func (f *Finding) IsCritical() bool

IsCritical checks if the finding is critical.

func (*Finding) IsFalsePositive

func (f *Finding) IsFalsePositive() bool

IsFalsePositive checks if the finding is marked as false positive.

func (*Finding) IsHighOrCritical

func (f *Finding) IsHighOrCritical() bool

IsHighOrCritical checks if the finding is high or critical.

func (*Finding) IsHighPriorityCTEM

func (f *Finding) IsHighPriorityCTEM() bool

IsHighPriorityCTEM returns true if this is a high-priority finding based on CTEM criteria.

func (*Finding) IsInternetAccessible

func (f *Finding) IsInternetAccessible() bool

IsInternetAccessible returns whether the finding is internet accessible.

func (*Finding) IsNetworkAccessible

func (f *Finding) IsNetworkAccessible() bool

IsNetworkAccessible returns whether the finding is network accessible.

func (*Finding) IsOpen

func (f *Finding) IsOpen() bool

IsOpen checks if the finding is open.

func (*Finding) IsResolved

func (f *Finding) IsResolved() bool

IsResolved checks if the finding is resolved.

func (*Finding) IsTriaged

func (f *Finding) IsTriaged() bool

IsTriaged returns true if the finding has been triaged (status != new).

func (*Finding) Kind

func (f *Finding) Kind() string

Kind returns the finding kind.

func (*Finding) LastSeenAt

func (f *Finding) LastSeenAt() time.Time

LastSeenAt returns when the finding was last seen.

func (*Finding) LastSeenBranch

func (f *Finding) LastSeenBranch() string

LastSeenBranch returns the branch where last seen.

func (*Finding) LastSeenCommit

func (f *Finding) LastSeenCommit() string

LastSeenCommit returns the commit where last seen.

func (*Finding) Likelihood

func (f *Finding) Likelihood() string

Likelihood returns the likelihood level.

func (*Finding) Location

func (f *Finding) Location() string

Location returns a formatted location string.

func (*Finding) MarkAsDuplicate

func (f *Finding) MarkAsDuplicate(originalID shared.ID) error

MarkAsDuplicate marks the finding as a duplicate.

func (*Finding) Message

func (f *Finding) Message() string

Message returns the message.

func (*Finding) Metadata

func (f *Finding) Metadata() map[string]any

Metadata returns a copy of the metadata.

func (*Finding) MisconfigActual

func (f *Finding) MisconfigActual() string

MisconfigActual returns the actual configuration value.

func (*Finding) MisconfigCause

func (f *Finding) MisconfigCause() string

MisconfigCause returns the misconfiguration cause/reason.

func (*Finding) MisconfigExpected

func (f *Finding) MisconfigExpected() string

MisconfigExpected returns the expected configuration value.

func (*Finding) MisconfigPolicyID

func (f *Finding) MisconfigPolicyID() string

MisconfigPolicyID returns the misconfiguration policy ID.

func (*Finding) MisconfigPolicyName

func (f *Finding) MisconfigPolicyName() string

MisconfigPolicyName returns the misconfiguration policy name.

func (*Finding) MisconfigResourceName

func (f *Finding) MisconfigResourceName() string

MisconfigResourceName returns the misconfiguration resource name.

func (*Finding) MisconfigResourcePath

func (f *Finding) MisconfigResourcePath() string

MisconfigResourcePath returns the misconfiguration resource path.

func (*Finding) MisconfigResourceType

func (f *Finding) MisconfigResourceType() string

MisconfigResourceType returns the misconfiguration resource type.

func (*Finding) OWASPIDs

func (f *Finding) OWASPIDs() []string

OWASPIDs returns the OWASP IDs.

func (*Finding) OccurrenceCount

func (f *Finding) OccurrenceCount() int

OccurrenceCount returns the occurrence count.

func (*Finding) PartialFingerprints

func (f *Finding) PartialFingerprints() map[string]string

PartialFingerprints returns a copy of the partial fingerprints.

func (*Finding) PentestCampaignID added in v0.1.2

func (f *Finding) PentestCampaignID() *shared.ID

PentestCampaignID returns the pentest campaign ID (nil for non-pentest findings).

func (*Finding) Rank

func (f *Finding) Rank() *float64

Rank returns the rank score.

func (*Finding) Recommendation

func (f *Finding) Recommendation() string

Recommendation returns the recommendation.

func (*Finding) RelatedIssueURL

func (f *Finding) RelatedIssueURL() string

RelatedIssueURL returns the related issue URL.

func (*Finding) RelatedLocations

func (f *Finding) RelatedLocations() []FindingLocation

RelatedLocations returns the related locations.

func (*Finding) RelatedPRURL

func (f *Finding) RelatedPRURL() string

RelatedPRURL returns the related PR URL.

func (*Finding) Remediation

func (f *Finding) Remediation() *FindingRemediation

Remediation returns the remediation JSONB object.

func (*Finding) RemediationType

func (f *Finding) RemediationType() RemediationType

RemediationType returns the remediation type.

func (*Finding) RemedyAvailable

func (f *Finding) RemedyAvailable() bool

RemedyAvailable returns whether a remedy is available.

func (*Finding) RemoveComplianceImpact

func (f *Finding) RemoveComplianceImpact(framework string)

RemoveComplianceImpact removes a compliance framework from the impact list.

func (*Finding) RemoveTag

func (f *Finding) RemoveTag(tag string)

RemoveTag removes a tag.

func (*Finding) ReputationalImpact

func (f *Finding) ReputationalImpact() bool

ReputationalImpact returns whether there is reputational impact.

func (*Finding) Resolution

func (f *Finding) Resolution() string

Resolution returns the resolution.

func (*Finding) ResolutionMethod added in v0.1.3

func (f *Finding) ResolutionMethod() string

ResolutionMethod returns how the finding was resolved.

func (*Finding) ResolvedAt

func (f *Finding) ResolvedAt() *time.Time

ResolvedAt returns the resolved time.

func (*Finding) ResolvedBy

func (f *Finding) ResolvedBy() *shared.ID

ResolvedBy returns who resolved the finding.

func (*Finding) RuleID

func (f *Finding) RuleID() string

RuleID returns the rule ID.

func (*Finding) RuleName

func (f *Finding) RuleName() string

RuleName returns the rule name.

func (*Finding) SLADeadline

func (f *Finding) SLADeadline() *time.Time

SLADeadline returns the SLA deadline.

func (*Finding) SLAStatus

func (f *Finding) SLAStatus() SLAStatus

SLAStatus returns the SLA status.

func (*Finding) ScanID

func (f *Finding) ScanID() string

ScanID returns the scan ID.

func (*Finding) SecretAgeInDays

func (f *Finding) SecretAgeInDays() int

SecretAgeInDays returns the age of the secret in days (for secret findings).

func (*Finding) SecretCommitCount

func (f *Finding) SecretCommitCount() int

SecretCommitCount returns the number of commits containing this secret (for secret findings).

func (*Finding) SecretEntropy

func (f *Finding) SecretEntropy() *float64

SecretEntropy returns the secret entropy (for secret findings).

func (*Finding) SecretExpiresAt

func (f *Finding) SecretExpiresAt() *time.Time

SecretExpiresAt returns the secret expiration time (for secret findings).

func (*Finding) SecretInHistoryOnly

func (f *Finding) SecretInHistoryOnly() bool

SecretInHistoryOnly returns whether the secret is only in git history (for secret findings).

func (*Finding) SecretMaskedValue

func (f *Finding) SecretMaskedValue() string

SecretMaskedValue returns the masked value of the secret (for secret findings).

func (*Finding) SecretRevoked

func (f *Finding) SecretRevoked() *bool

SecretRevoked returns whether the secret has been revoked (for secret findings).

func (*Finding) SecretRotationDueAt

func (f *Finding) SecretRotationDueAt() *time.Time

SecretRotationDueAt returns when the secret rotation is due (for secret findings).

func (*Finding) SecretScopes

func (f *Finding) SecretScopes() []string

SecretScopes returns the secret scopes/permissions (for secret findings).

func (*Finding) SecretService

func (f *Finding) SecretService() string

SecretService returns the secret service (for secret findings).

func (*Finding) SecretType

func (f *Finding) SecretType() string

SecretType returns the secret type (for secret findings).

func (*Finding) SecretValid

func (f *Finding) SecretValid() *bool

SecretValid returns whether the secret is valid (for secret findings).

func (*Finding) SecretVerifiedAt

func (f *Finding) SecretVerifiedAt() *time.Time

SecretVerifiedAt returns when the secret was verified (for secret findings).

func (*Finding) SetASVSControlID

func (f *Finding) SetASVSControlID(controlID string)

SetASVSControlID sets the ASVS control ID.

func (*Finding) SetASVSControlURL

func (f *Finding) SetASVSControlURL(url string)

SetASVSControlURL sets the ASVS control URL.

func (*Finding) SetASVSLevel

func (f *Finding) SetASVSLevel(level *int)

SetASVSLevel sets the ASVS level.

func (*Finding) SetASVSSection

func (f *Finding) SetASVSSection(section string)

SetASVSSection sets the ASVS section.

func (*Finding) SetAgentID

func (f *Finding) SetAgentID(agentID shared.ID)

SetAgentID sets the agent ID that submitted this finding.

func (*Finding) SetAttachments

func (f *Finding) SetAttachments(attachments []Attachment)

SetAttachments sets the attachments.

func (*Finding) SetAttackPrerequisites

func (f *Finding) SetAttackPrerequisites(prerequisites string)

SetAttackPrerequisites sets the attack prerequisites.

func (*Finding) SetBaselineState

func (f *Finding) SetBaselineState(state string)

SetBaselineState sets the baseline state.

func (*Finding) SetBranchID

func (f *Finding) SetBranchID(id shared.ID)

SetBranchID sets the branch ID.

func (*Finding) SetBranchInfo

func (f *Finding) SetBranchInfo(branchName string, commitSHA string)

SetBranchInfo sets branch tracking information. Note: isDefaultBranch is determined by branch_id FK to asset_branches.is_default, not stored on finding.

func (*Finding) SetClassification

func (f *Finding) SetClassification(cveID string, cvssScore *float64, cvssVector string, cweIDs, owaspIDs []string) error

SetClassification sets the CVE/CWE/CVSS classification.

func (*Finding) SetComplianceControlDescription

func (f *Finding) SetComplianceControlDescription(description string)

SetComplianceControlDescription sets the compliance control description (for compliance findings).

func (*Finding) SetComplianceControlID

func (f *Finding) SetComplianceControlID(controlID string)

SetComplianceControlID sets the compliance control ID (for compliance findings).

func (*Finding) SetComplianceControlName

func (f *Finding) SetComplianceControlName(controlName string)

SetComplianceControlName sets the compliance control name (for compliance findings).

func (*Finding) SetComplianceDetails

func (f *Finding) SetComplianceDetails(framework, controlID, controlName, result, section string)

SetComplianceDetails sets all compliance-related fields at once.

func (*Finding) SetComplianceFramework

func (f *Finding) SetComplianceFramework(framework string)

SetComplianceFramework sets the compliance framework (for compliance findings).

func (*Finding) SetComplianceFrameworkVersion

func (f *Finding) SetComplianceFrameworkVersion(version string)

SetComplianceFrameworkVersion sets the compliance framework version (for compliance findings).

func (*Finding) SetComplianceImpact

func (f *Finding) SetComplianceImpact(frameworks []string)

SetComplianceImpact sets the compliance frameworks impacted.

func (*Finding) SetComplianceResult

func (f *Finding) SetComplianceResult(result string)

SetComplianceResult sets the compliance result (for compliance findings).

func (*Finding) SetComplianceSection

func (f *Finding) SetComplianceSection(section string)

SetComplianceSection sets the compliance section (for compliance findings).

func (*Finding) SetComponentID

func (f *Finding) SetComponentID(id shared.ID)

SetComponentID sets the component ID.

func (*Finding) SetConfidence

func (f *Finding) SetConfidence(confidence *int) error

SetConfidence sets the confidence score.

func (*Finding) SetContextSnippet

func (f *Finding) SetContextSnippet(snippet string)

SetContextSnippet sets the surrounding code context.

func (*Finding) SetContextStartLine

func (f *Finding) SetContextStartLine(line int)

SetContextStartLine sets the line number where context begins.

func (*Finding) SetCorrelationID

func (f *Finding) SetCorrelationID(id string)

SetCorrelationID sets the correlation ID.

func (*Finding) SetCreatedBy added in v0.1.6

func (f *Finding) SetCreatedBy(userID shared.ID)

SetCreatedBy assigns a creator user ID. Used when a pentester manually authors a finding through the unified API.

func (*Finding) SetDataExposureRisk

func (f *Finding) SetDataExposureRisk(risk DataExposureRisk) error

SetDataExposureRisk sets the data exposure risk.

func (*Finding) SetDataFlows

func (f *Finding) SetDataFlows(flows []DataFlow)

SetDataFlows sets the data flows for taint tracking.

func (*Finding) SetDescription

func (f *Finding) SetDescription(description string)

SetDescription sets the description.

func (*Finding) SetEstimatedFixTime

func (f *Finding) SetEstimatedFixTime(minutes *int)

SetEstimatedFixTime sets the estimated fix time in minutes.

func (*Finding) SetExposureInfo

func (f *Finding) SetExposureInfo(vector ExposureVector, networkAccessible, internetAccessible bool, prerequisites string) error

SetExposureInfo sets all exposure-related fields at once.

func (*Finding) SetExposureVector

func (f *Finding) SetExposureVector(vector ExposureVector) error

SetExposureVector sets the exposure vector.

func (*Finding) SetFindingType

func (f *Finding) SetFindingType(findingType FindingType)

SetFindingType sets the finding type discriminator.

func (*Finding) SetFingerprint

func (f *Finding) SetFingerprint(fingerprint string)

SetFingerprint sets the fingerprint.

func (*Finding) SetFirstDetectedBranch

func (f *Finding) SetFirstDetectedBranch(branch string)

SetFirstDetectedBranch sets the branch where the finding was first detected.

func (*Finding) SetFirstDetectedCommit

func (f *Finding) SetFirstDetectedCommit(commit string)

SetFirstDetectedCommit sets the commit where the finding was first detected.

func (*Finding) SetFixCode

func (f *Finding) SetFixCode(code string)

SetFixCode sets the auto-fix code snippet.

func (*Finding) SetFixComplexity

func (f *Finding) SetFixComplexity(complexity FixComplexity) error

SetFixComplexity sets the fix complexity.

func (*Finding) SetFixRegex

func (f *Finding) SetFixRegex(regex *FixRegex)

SetFixRegex sets the regex-based fix pattern.

func (*Finding) SetHasDataFlow

func (f *Finding) SetHasDataFlow(has bool)

SetHasDataFlow sets the hasDataFlow flag (used by repository for list views).

func (*Finding) SetHostedViewerURI

func (f *Finding) SetHostedViewerURI(uri string)

SetHostedViewerURI sets the hosted viewer URI.

func (*Finding) SetImpact

func (f *Finding) SetImpact(impact string)

SetImpact sets the impact level.

func (*Finding) SetInternetAccessible

func (f *Finding) SetInternetAccessible(accessible bool)

SetInternetAccessible sets whether the finding is internet accessible.

func (*Finding) SetKind

func (f *Finding) SetKind(kind string)

SetKind sets the finding kind.

func (*Finding) SetLastSeenBranch

func (f *Finding) SetLastSeenBranch(branch string)

SetLastSeenBranch sets the branch where the finding was last seen.

func (*Finding) SetLastSeenCommit

func (f *Finding) SetLastSeenCommit(commit string)

SetLastSeenCommit sets the commit where the finding was last seen.

func (*Finding) SetLikelihood

func (f *Finding) SetLikelihood(likelihood string)

SetLikelihood sets the likelihood level.

func (*Finding) SetLocation

func (f *Finding) SetLocation(filePath string, startLine, endLine, startColumn, endColumn int)

SetLocation sets the file location.

func (*Finding) SetMetadata

func (f *Finding) SetMetadata(key string, value any)

SetMetadata sets a metadata key-value pair.

func (*Finding) SetMisconfigActual

func (f *Finding) SetMisconfigActual(actual string)

SetMisconfigActual sets the actual configuration value.

func (*Finding) SetMisconfigCause

func (f *Finding) SetMisconfigCause(cause string)

SetMisconfigCause sets the misconfiguration cause/reason.

func (*Finding) SetMisconfigDetails

func (f *Finding) SetMisconfigDetails(policyID, resourceType, resourceName, resourcePath, expected, actual string)

SetMisconfigDetails sets all misconfiguration-related fields at once.

func (*Finding) SetMisconfigExpected

func (f *Finding) SetMisconfigExpected(expected string)

SetMisconfigExpected sets the expected configuration value.

func (*Finding) SetMisconfigPolicyID

func (f *Finding) SetMisconfigPolicyID(policyID string)

SetMisconfigPolicyID sets the misconfiguration policy ID.

func (*Finding) SetMisconfigPolicyName

func (f *Finding) SetMisconfigPolicyName(policyName string)

SetMisconfigPolicyName sets the misconfiguration policy name.

func (*Finding) SetMisconfigResourceName

func (f *Finding) SetMisconfigResourceName(resourceName string)

SetMisconfigResourceName sets the misconfiguration resource name.

func (*Finding) SetMisconfigResourcePath

func (f *Finding) SetMisconfigResourcePath(resourcePath string)

SetMisconfigResourcePath sets the misconfiguration resource path.

func (*Finding) SetMisconfigResourceType

func (f *Finding) SetMisconfigResourceType(resourceType string)

SetMisconfigResourceType sets the misconfiguration resource type.

func (*Finding) SetNetworkAccessible

func (f *Finding) SetNetworkAccessible(accessible bool)

SetNetworkAccessible sets whether the finding is network accessible.

func (*Finding) SetOccurrenceCount

func (f *Finding) SetOccurrenceCount(count int)

SetOccurrenceCount sets the occurrence count.

func (*Finding) SetPartialFingerprints

func (f *Finding) SetPartialFingerprints(fingerprints map[string]string)

SetPartialFingerprints sets the partial fingerprints.

func (*Finding) SetPentestCampaignID added in v0.1.2

func (f *Finding) SetPentestCampaignID(id *shared.ID)

SetPentestCampaignID sets the pentest campaign reference.

func (*Finding) SetRank

func (f *Finding) SetRank(rank *float64) error

SetRank sets the rank score.

func (*Finding) SetRecommendation

func (f *Finding) SetRecommendation(recommendation string)

SetRecommendation sets the recommendation.

func (*Finding) SetRelatedIssue

func (f *Finding) SetRelatedIssue(url string)

SetRelatedIssue sets the related issue URL.

func (*Finding) SetRelatedLocations

func (f *Finding) SetRelatedLocations(locations []FindingLocation)

SetRelatedLocations sets the related locations.

func (*Finding) SetRelatedPR

func (f *Finding) SetRelatedPR(url string)

SetRelatedPR sets the related PR URL.

func (*Finding) SetRemediation

func (f *Finding) SetRemediation(r *FindingRemediation)

SetRemediation sets the remediation JSONB object.

func (*Finding) SetRemediationInfo

func (f *Finding) SetRemediationInfo(remType RemediationType, estimatedMinutes *int, complexity FixComplexity, available bool) error

SetRemediationInfo sets all remediation-related fields at once.

func (*Finding) SetRemediationType

func (f *Finding) SetRemediationType(remType RemediationType) error

SetRemediationType sets the remediation type.

func (*Finding) SetRemedyAvailable

func (f *Finding) SetRemedyAvailable(available bool)

SetRemedyAvailable sets whether a remedy is available.

func (*Finding) SetReputationalImpact

func (f *Finding) SetReputationalImpact(impact bool)

SetReputationalImpact sets whether there is reputational impact.

func (*Finding) SetResolutionMethod added in v0.1.3

func (f *Finding) SetResolutionMethod(method string) error

SetResolutionMethod sets the resolution method (system-only, not via API input). Validates against known ResolutionMethod constants to prevent invalid state.

func (*Finding) SetRuleID

func (f *Finding) SetRuleID(ruleID string)

SetRuleID sets the rule ID.

func (*Finding) SetRuleName

func (f *Finding) SetRuleName(ruleName string)

SetRuleName sets the rule name.

func (*Finding) SetSARIFCoreFields

func (f *Finding) SetSARIFCoreFields(baselineState, kind string, rank *float64, occurrenceCount int, correlationID string) error

SetSARIFCoreFields sets the core SARIF fields at once.

func (*Finding) SetSARIFRiskAssessment

func (f *Finding) SetSARIFRiskAssessment(confidence *int, impact, likelihood string, vulnerabilityClass, subcategory []string) error

SetSARIFRiskAssessment sets all risk assessment fields at once.

func (*Finding) SetSLADeadline

func (f *Finding) SetSLADeadline(deadline time.Time)

SetSLADeadline sets the SLA deadline.

func (*Finding) SetScanID

func (f *Finding) SetScanID(scanID string)

SetScanID sets the scan ID.

func (*Finding) SetSecretAgeInDays

func (f *Finding) SetSecretAgeInDays(ageInDays int)

SetSecretAgeInDays sets the age of the secret in days (for secret findings).

func (*Finding) SetSecretCommitCount

func (f *Finding) SetSecretCommitCount(commitCount int)

SetSecretCommitCount sets the number of commits containing this secret (for secret findings).

func (*Finding) SetSecretDetails

func (f *Finding) SetSecretDetails(secretType, service string, valid, revoked *bool, entropy *float64, expiresAt *time.Time)

SetSecretDetails sets all secret-related fields at once.

func (*Finding) SetSecretEntropy

func (f *Finding) SetSecretEntropy(entropy *float64)

SetSecretEntropy sets the secret entropy (for secret findings).

func (*Finding) SetSecretExpiresAt

func (f *Finding) SetSecretExpiresAt(expiresAt *time.Time)

SetSecretExpiresAt sets the secret expiration time (for secret findings).

func (*Finding) SetSecretInHistoryOnly

func (f *Finding) SetSecretInHistoryOnly(inHistoryOnly bool)

SetSecretInHistoryOnly sets whether the secret is only in git history (for secret findings).

func (*Finding) SetSecretMaskedValue

func (f *Finding) SetSecretMaskedValue(maskedValue string)

SetSecretMaskedValue sets the masked value of the secret (for secret findings).

func (*Finding) SetSecretRevoked

func (f *Finding) SetSecretRevoked(revoked *bool)

SetSecretRevoked sets whether the secret has been revoked (for secret findings).

func (*Finding) SetSecretRotationDueAt

func (f *Finding) SetSecretRotationDueAt(rotationDueAt *time.Time)

SetSecretRotationDueAt sets when the secret rotation is due (for secret findings).

func (*Finding) SetSecretScopes

func (f *Finding) SetSecretScopes(scopes []string)

SetSecretScopes sets the secret scopes/permissions (for secret findings).

func (*Finding) SetSecretService

func (f *Finding) SetSecretService(service string)

SetSecretService sets the secret service (for secret findings).

func (*Finding) SetSecretType

func (f *Finding) SetSecretType(secretType string)

SetSecretType sets the secret type (for secret findings).

func (*Finding) SetSecretValid

func (f *Finding) SetSecretValid(valid *bool)

SetSecretValid sets whether the secret is valid (for secret findings).

func (*Finding) SetSecretVerifiedAt

func (f *Finding) SetSecretVerifiedAt(verifiedAt *time.Time)

SetSecretVerifiedAt sets when the secret was verified (for secret findings).

func (*Finding) SetSnippet

func (f *Finding) SetSnippet(snippet string)

SetSnippet sets the code snippet.

func (*Finding) SetSourceMetadata added in v0.1.2

func (f *Finding) SetSourceMetadata(meta map[string]any)

SetSourceMetadata sets source-specific metadata.

func (*Finding) SetStacks

func (f *Finding) SetStacks(stacks []StackTrace)

SetStacks sets the stack traces.

func (*Finding) SetSubcategory

func (f *Finding) SetSubcategory(subcategories []string)

SetSubcategory sets the subcategories.

func (*Finding) SetTags

func (f *Finding) SetTags(tags []string)

SetTags sets the tags.

func (*Finding) SetTitle

func (f *Finding) SetTitle(title string)

SetTitle sets the title.

func (*Finding) SetToolID added in v0.1.2

func (f *Finding) SetToolID(id *shared.ID)

SetToolID sets the tool ID (FK reference to tools table).

func (*Finding) SetToolVersion

func (f *Finding) SetToolVersion(version string)

SetToolVersion sets the tool version.

func (*Finding) SetVulnerabilityClass

func (f *Finding) SetVulnerabilityClass(classes []string)

SetVulnerabilityClass sets the vulnerability classes.

func (*Finding) SetVulnerabilityID

func (f *Finding) SetVulnerabilityID(id shared.ID)

SetVulnerabilityID sets the vulnerability ID.

func (*Finding) SetWeb3BytecodeOffset

func (f *Finding) SetWeb3BytecodeOffset(offset int)

SetWeb3BytecodeOffset sets the bytecode offset (for web3 findings).

func (*Finding) SetWeb3Chain

func (f *Finding) SetWeb3Chain(chain string)

SetWeb3Chain sets the blockchain chain (for web3 findings).

func (*Finding) SetWeb3ChainID

func (f *Finding) SetWeb3ChainID(chainID int64)

SetWeb3ChainID sets the blockchain chain ID (for web3 findings).

func (*Finding) SetWeb3ContractAddress

func (f *Finding) SetWeb3ContractAddress(address string)

SetWeb3ContractAddress sets the smart contract address (for web3 findings).

func (*Finding) SetWeb3Details

func (f *Finding) SetWeb3Details(chain string, chainID int64, contractAddress, swcID, functionSignature, txHash string)

SetWeb3Details sets all web3-related fields at once.

func (*Finding) SetWeb3FunctionSelector

func (f *Finding) SetWeb3FunctionSelector(selector string)

SetWeb3FunctionSelector sets the function selector (for web3 findings).

func (*Finding) SetWeb3FunctionSignature

func (f *Finding) SetWeb3FunctionSignature(signature string)

SetWeb3FunctionSignature sets the function signature (for web3 findings).

func (*Finding) SetWeb3SWCID

func (f *Finding) SetWeb3SWCID(swcID string)

SetWeb3SWCID sets the SWC ID (for web3 findings).

func (*Finding) SetWeb3TxHash

func (f *Finding) SetWeb3TxHash(txHash string)

SetWeb3TxHash sets the transaction hash (for web3 findings).

func (*Finding) SetWorkItemURIs

func (f *Finding) SetWorkItemURIs(uris []string)

SetWorkItemURIs sets the work item URIs.

func (*Finding) Severity

func (f *Finding) Severity() Severity

Severity returns the severity.

func (*Finding) Snippet

func (f *Finding) Snippet() string

Snippet returns the code snippet.

func (*Finding) Source

func (f *Finding) Source() FindingSource

Source returns the finding source.

func (*Finding) SourceMetadata added in v0.1.2

func (f *Finding) SourceMetadata() map[string]any

SourceMetadata returns the source-specific metadata.

func (*Finding) Stacks

func (f *Finding) Stacks() []StackTrace

Stacks returns the stack traces.

func (*Finding) StartColumn

func (f *Finding) StartColumn() int

StartColumn returns the start column.

func (*Finding) StartLine

func (f *Finding) StartLine() int

StartLine returns the start line.

func (*Finding) Status

func (f *Finding) Status() FindingStatus

Status returns the status.

func (*Finding) Subcategory

func (f *Finding) Subcategory() []string

Subcategory returns the subcategories.

func (*Finding) Tags

func (f *Finding) Tags() []string

Tags returns the tags.

func (*Finding) TenantID

func (f *Finding) TenantID() shared.ID

TenantID returns the tenant ID.

func (*Finding) TimeToResolve

func (f *Finding) TimeToResolve() *time.Duration

TimeToResolve returns the time to resolve if resolved.

func (*Finding) Title

func (f *Finding) Title() string

Title returns the title.

func (*Finding) ToolID added in v0.1.2

func (f *Finding) ToolID() *shared.ID

ToolID returns the tool ID (FK reference to tools table).

func (*Finding) ToolName

func (f *Finding) ToolName() string

ToolName returns the tool name.

func (*Finding) ToolVersion

func (f *Finding) ToolVersion() string

ToolVersion returns the tool version.

func (*Finding) TransitionStatus

func (f *Finding) TransitionStatus(newStatus FindingStatus, resolution string, actorID *shared.ID) error

TransitionStatus transitions the status with workflow validation.

func (*Finding) Unassign

func (f *Finding) Unassign()

Unassign removes the assignment.

func (*Finding) UpdateLastSeen

func (f *Finding) UpdateLastSeen(branch, commit string)

UpdateLastSeen updates the last seen tracking.

func (*Finding) UpdateMessage

func (f *Finding) UpdateMessage(message string)

UpdateMessage updates the message.

func (*Finding) UpdateSLAStatus

func (f *Finding) UpdateSLAStatus()

UpdateSLAStatus updates the SLA status based on current time and deadline.

func (*Finding) UpdateSeverity

func (f *Finding) UpdateSeverity(severity Severity) error

UpdateSeverity updates the severity.

func (*Finding) UpdateStatus

func (f *Finding) UpdateStatus(status FindingStatus, resolution string, resolvedBy *shared.ID) error

UpdateStatus updates the status with optional resolution.

func (*Finding) UpdateStatusWithReason

func (f *Finding) UpdateStatusWithReason(status FindingStatus, _, resolution string, resolvedBy *shared.ID) error

UpdateStatusWithReason updates the status. Reason should be recorded in finding_activities. This is a convenience method that calls UpdateStatus - reason tracking is handled by the service layer.

func (*Finding) UpdatedAt

func (f *Finding) UpdatedAt() time.Time

UpdatedAt returns the last update time.

func (*Finding) VerifiedAt

func (f *Finding) VerifiedAt() *time.Time

VerifiedAt returns when the fix was verified.

func (*Finding) VerifiedBy

func (f *Finding) VerifiedBy() *shared.ID

VerifiedBy returns who verified the fix.

func (*Finding) Verify

func (f *Finding) Verify(verifiedBy shared.ID) error

Verify marks the finding fix as verified.

func (*Finding) VulnerabilityClass

func (f *Finding) VulnerabilityClass() []string

VulnerabilityClass returns the vulnerability classes.

func (*Finding) VulnerabilityID

func (f *Finding) VulnerabilityID() *shared.ID

VulnerabilityID returns the vulnerability ID.

func (*Finding) Web3BytecodeOffset

func (f *Finding) Web3BytecodeOffset() int

Web3BytecodeOffset returns the bytecode offset (for web3 findings).

func (*Finding) Web3Chain

func (f *Finding) Web3Chain() string

Web3Chain returns the blockchain chain (for web3 findings).

func (*Finding) Web3ChainID

func (f *Finding) Web3ChainID() int64

Web3ChainID returns the blockchain chain ID (for web3 findings).

func (*Finding) Web3ContractAddress

func (f *Finding) Web3ContractAddress() string

Web3ContractAddress returns the smart contract address (for web3 findings).

func (*Finding) Web3FunctionSelector

func (f *Finding) Web3FunctionSelector() string

Web3FunctionSelector returns the function selector (for web3 findings).

func (*Finding) Web3FunctionSignature

func (f *Finding) Web3FunctionSignature() string

Web3FunctionSignature returns the function signature (for web3 findings).

func (*Finding) Web3SWCID

func (f *Finding) Web3SWCID() string

Web3SWCID returns the SWC ID (for web3 findings).

func (*Finding) Web3TxHash

func (f *Finding) Web3TxHash() string

Web3TxHash returns the transaction hash (for web3 findings).

func (*Finding) WorkItemURIs

func (f *Finding) WorkItemURIs() []string

WorkItemURIs returns the work item URIs.

type FindingActivity

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

FindingActivity represents an immutable audit trail entry for a finding. This entity is APPEND-ONLY - once created, it should never be modified or deleted.

func NewAITriageActivity

func NewAITriageActivity(
	tenantID, findingID shared.ID,
	triageResultID string,
	severityAssessment string,
	riskScore float64,
	priorityRank int,
	falsePositiveLikelihood float64,
	summary string,
	sourceMetadata map[string]interface{},
) (*FindingActivity, error)

NewAITriageActivity creates an activity for AI triage events.

func NewAITriageFailedActivity

func NewAITriageFailedActivity(
	tenantID, findingID shared.ID,
	triageResultID string,
	errorMessage string,
	sourceMetadata map[string]interface{},
) (*FindingActivity, error)

NewAITriageFailedActivity creates an activity for failed AI triage events.

func NewAssignmentActivity

func NewAssignmentActivity(
	tenantID, findingID shared.ID,
	actorID *shared.ID,
	assigneeID, assigneeName, assigneeEmail string,
	source ActivitySource,
) (*FindingActivity, error)

NewAssignmentActivity creates an activity for assignment changes.

func NewCommentActivity

func NewCommentActivity(
	tenantID, findingID shared.ID,
	actorID *shared.ID,
	activityType ActivityType,
	commentID string,
	content string,
	source ActivitySource,
) (*FindingActivity, error)

NewCommentActivity creates an activity for comment events. content is the full comment text, stored in changes for display.

func NewFindingActivity

func NewFindingActivity(
	tenantID shared.ID,
	findingID shared.ID,
	activityType ActivityType,
	actorID *shared.ID,
	actorType ActorType,
	changes map[string]interface{},
	source ActivitySource,
	sourceMetadata map[string]interface{},
) (*FindingActivity, error)

NewFindingActivity creates a new finding activity.

func NewScanDetectedActivity

func NewScanDetectedActivity(
	tenantID, findingID shared.ID,
	scanID, scanner, scanType string,
	sourceMetadata map[string]interface{},
) (*FindingActivity, error)

NewScanDetectedActivity creates an activity for scan detections.

func NewSeverityChangeActivity

func NewSeverityChangeActivity(
	tenantID, findingID shared.ID,
	actorID *shared.ID,
	oldSeverity, newSeverity string,
	source ActivitySource,
) (*FindingActivity, error)

NewSeverityChangeActivity creates an activity for severity changes.

func NewStatusChangeActivity

func NewStatusChangeActivity(
	tenantID, findingID shared.ID,
	actorID *shared.ID,
	oldStatus, newStatus string,
	reason string,
	source ActivitySource,
) (*FindingActivity, error)

NewStatusChangeActivity creates an activity for status changes.

func ReconstituteFindingActivity

func ReconstituteFindingActivity(
	id shared.ID,
	tenantID shared.ID,
	findingID shared.ID,
	activityType ActivityType,
	actorID *shared.ID,
	actorType ActorType,
	actorName string,
	actorEmail string,
	changes map[string]interface{},
	source ActivitySource,
	sourceMetadata map[string]interface{},
	createdAt time.Time,
) *FindingActivity

ReconstituteFindingActivity recreates a FindingActivity from persistence.

func (*FindingActivity) ActivityType

func (a *FindingActivity) ActivityType() ActivityType

func (*FindingActivity) ActorEmail

func (a *FindingActivity) ActorEmail() string

func (*FindingActivity) ActorID

func (a *FindingActivity) ActorID() *shared.ID

func (*FindingActivity) ActorName

func (a *FindingActivity) ActorName() string

func (*FindingActivity) ActorType

func (a *FindingActivity) ActorType() ActorType

func (*FindingActivity) Changes

func (a *FindingActivity) Changes() map[string]interface{}

func (*FindingActivity) ChangesJSON

func (a *FindingActivity) ChangesJSON() ([]byte, error)

ChangesJSON returns the changes as JSON bytes.

func (*FindingActivity) CreatedAt

func (a *FindingActivity) CreatedAt() time.Time

func (*FindingActivity) FindingID

func (a *FindingActivity) FindingID() shared.ID

func (*FindingActivity) ID

func (a *FindingActivity) ID() shared.ID

func (*FindingActivity) ParsedChanges

func (a *FindingActivity) ParsedChanges() (*ActivityChanges, error)

ParsedChanges returns the changes parsed into a typed struct.

func (*FindingActivity) Source

func (a *FindingActivity) Source() ActivitySource

func (*FindingActivity) SourceMetadata

func (a *FindingActivity) SourceMetadata() map[string]interface{}

func (*FindingActivity) SourceMetadataJSON

func (a *FindingActivity) SourceMetadataJSON() ([]byte, error)

SourceMetadataJSON returns the source metadata as JSON bytes.

func (*FindingActivity) TenantID

func (a *FindingActivity) TenantID() shared.ID

type FindingActivityFilter

type FindingActivityFilter struct {
	ActivityTypes []ActivityType
	ActorTypes    []ActorType
	ActorIDs      []shared.ID
	Sources       []ActivitySource
	Since         *time.Time
	Until         *time.Time
}

FindingActivityFilter defines criteria for filtering activities.

func NewFindingActivityFilter

func NewFindingActivityFilter() FindingActivityFilter

NewFindingActivityFilter creates a new empty filter.

func (FindingActivityFilter) WithActivityTypes

func (f FindingActivityFilter) WithActivityTypes(types ...ActivityType) FindingActivityFilter

WithActivityTypes filters by activity types.

func (FindingActivityFilter) WithActorTypes

func (f FindingActivityFilter) WithActorTypes(types ...ActorType) FindingActivityFilter

WithActorTypes filters by actor types.

func (FindingActivityFilter) WithSince

WithSince filters activities after a time.

func (FindingActivityFilter) WithUntil

WithUntil filters activities before a time.

type FindingActivityRepository

type FindingActivityRepository interface {
	// Create persists a new activity record.
	Create(ctx context.Context, activity *FindingActivity) error

	// CreateBatch persists multiple activity records in a single INSERT for performance.
	CreateBatch(ctx context.Context, activities []*FindingActivity) error

	// GetByID retrieves an activity by ID.
	GetByID(ctx context.Context, id shared.ID) (*FindingActivity, error)

	// ListByFinding returns activities for a finding with pagination.
	// Security: tenantID is required to ensure tenant isolation.
	ListByFinding(ctx context.Context, findingID shared.ID, tenantID shared.ID, filter FindingActivityFilter, page pagination.Pagination) (pagination.Result[*FindingActivity], error)

	// CountByFinding counts activities for a finding.
	// Security: tenantID is required to ensure tenant isolation.
	CountByFinding(ctx context.Context, findingID shared.ID, tenantID shared.ID, filter FindingActivityFilter) (int64, error)

	// ListByTenant returns activities for a tenant with pagination.
	ListByTenant(ctx context.Context, tenantID shared.ID, filter FindingActivityFilter, page pagination.Pagination) (pagination.Result[*FindingActivity], error)

	// DeleteByCommentID removes the comment_added activity for a given comment ID.
	// Exception to append-only: user comment content is not an audit event.
	// Security: tenantID is required to prevent cross-tenant data modification.
	DeleteByCommentID(ctx context.Context, tenantID shared.ID, commentID string) error

	// UpdateContentByCommentID updates the content in the comment_added activity for a given comment ID.
	// Exception to append-only: user comment content is not an audit event.
	// Security: tenantID is required to prevent cross-tenant data modification.
	UpdateContentByCommentID(ctx context.Context, tenantID shared.ID, commentID string, content string) error
}

FindingActivityRepository defines the interface for finding activity persistence. This is an APPEND-ONLY store - activities should never be updated or deleted.

type FindingComment

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

FindingComment represents a comment on a finding.

func NewFindingComment

func NewFindingComment(
	findingID shared.ID,
	authorID shared.ID,
	content string,
) (*FindingComment, error)

NewFindingComment creates a new comment.

func NewStatusChangeComment

func NewStatusChangeComment(
	findingID shared.ID,
	authorID shared.ID,
	content string,
	oldStatus FindingStatus,
	newStatus FindingStatus,
) (*FindingComment, error)

NewStatusChangeComment creates a comment for a status change.

func ReconstituteFindingComment

func ReconstituteFindingComment(
	id shared.ID,
	findingID shared.ID,
	authorID shared.ID,
	authorName string,
	authorEmail string,
	content string,
	isStatusChange bool,
	oldStatus FindingStatus,
	newStatus FindingStatus,
	createdAt time.Time,
	updatedAt time.Time,
) *FindingComment

ReconstituteFindingComment recreates a FindingComment from persistence.

func (*FindingComment) AuthorEmail

func (c *FindingComment) AuthorEmail() string

func (*FindingComment) AuthorID

func (c *FindingComment) AuthorID() shared.ID

func (*FindingComment) AuthorName

func (c *FindingComment) AuthorName() string

func (*FindingComment) Content

func (c *FindingComment) Content() string

func (*FindingComment) CreatedAt

func (c *FindingComment) CreatedAt() time.Time

func (*FindingComment) FindingID

func (c *FindingComment) FindingID() shared.ID

func (*FindingComment) ID

func (c *FindingComment) ID() shared.ID

func (*FindingComment) IsStatusChange

func (c *FindingComment) IsStatusChange() bool

func (*FindingComment) NewStatus

func (c *FindingComment) NewStatus() FindingStatus

func (*FindingComment) OldStatus

func (c *FindingComment) OldStatus() FindingStatus

func (*FindingComment) UpdateContent

func (c *FindingComment) UpdateContent(content string) error

func (*FindingComment) UpdatedAt

func (c *FindingComment) UpdatedAt() time.Time

type FindingCommentRepository

type FindingCommentRepository interface {
	// Create persists a new comment.
	Create(ctx context.Context, comment *FindingComment) error

	// GetByID retrieves a comment by ID.
	GetByID(ctx context.Context, id shared.ID) (*FindingComment, error)

	// Update updates an existing comment.
	Update(ctx context.Context, comment *FindingComment) error

	// Delete removes a comment.
	Delete(ctx context.Context, id shared.ID) error

	// ListByFinding returns all comments for a finding.
	ListByFinding(ctx context.Context, findingID shared.ID) ([]*FindingComment, error)

	// CountByFinding counts comments for a finding.
	CountByFinding(ctx context.Context, findingID shared.ID) (int, error)
}

FindingCommentRepository defines the interface for finding comment persistence.

type FindingData

type FindingData struct {
	ID              shared.ID
	TenantID        shared.ID
	VulnerabilityID *shared.ID
	AssetID         shared.ID
	BranchID        *shared.ID
	ComponentID     *shared.ID

	// Pentest / Source-specific
	PentestCampaignID *shared.ID
	SourceMetadata    map[string]any

	// Tool
	Source      FindingSource
	ToolName    string
	ToolID      *shared.ID
	ToolVersion string
	RuleID      string
	RuleName    string
	AgentID     *shared.ID

	// Finding type discriminator
	FindingType FindingType

	// Specialized finding details (extracted from metadata)
	// Secret details
	SecretType          string
	SecretService       string
	SecretValid         *bool
	SecretRevoked       *bool
	SecretEntropy       *float64
	SecretExpiresAt     *time.Time
	SecretVerifiedAt    *time.Time
	SecretRotationDueAt *time.Time
	SecretAgeInDays     int
	SecretScopes        []string
	SecretMaskedValue   string
	SecretInHistoryOnly bool
	SecretCommitCount   int

	// Compliance details
	ComplianceFramework          string
	ComplianceControlID          string
	ComplianceControlName        string
	ComplianceResult             string
	ComplianceSection            string
	ComplianceFrameworkVersion   string
	ComplianceControlDescription string

	// Web3 details
	Web3Chain             string
	Web3ChainID           int64
	Web3ContractAddress   string
	Web3SWCID             string
	Web3FunctionSignature string
	Web3TxHash            string
	Web3FunctionSelector  string
	Web3BytecodeOffset    int

	// Misconfiguration details
	MisconfigPolicyID     string
	MisconfigPolicyName   string
	MisconfigResourceType string
	MisconfigResourceName string
	MisconfigResourcePath string
	MisconfigExpected     string
	MisconfigActual       string
	MisconfigCause        string

	// Data flows
	DataFlows   []DataFlow
	HasDataFlow bool // Lightweight flag for list views

	// Location
	FilePath         string
	StartLine        int
	EndLine          int
	StartColumn      int
	EndColumn        int
	Snippet          string
	ContextSnippet   string
	ContextStartLine int

	// Content
	Title          string
	Description    string
	Message        string
	Recommendation string

	// Remediation (JSONB in database)
	Remediation *FindingRemediation

	// Classification
	Severity   Severity
	CVSSScore  *float64
	CVSSVector string
	CVEID      string
	CWEIDs     []string
	OWASPIDs   []string
	Tags       []string

	// Status
	// Note: Reasons for status changes are tracked in finding_activities.changes JSONB
	Status           FindingStatus
	Resolution       string
	ResolutionMethod string // How resolved: legacy, scan_verified, security_reviewed, admin_direct
	ResolvedAt       *time.Time
	ResolvedBy       *shared.ID // User who resolved (FK to users.id)

	// Assignment
	AssignedTo *shared.ID
	AssignedAt *time.Time
	AssignedBy *shared.ID

	// Verification
	VerifiedAt *time.Time
	VerifiedBy *shared.ID

	// SLA
	SLADeadline *time.Time
	SLAStatus   SLAStatus

	// Detection
	FirstDetectedAt     time.Time
	LastSeenAt          time.Time
	FirstDetectedBranch string
	FirstDetectedCommit string
	LastSeenBranch      string
	LastSeenCommit      string

	// Integration
	RelatedIssueURL string
	RelatedPRURL    string

	// Dedup
	DuplicateOf    *shared.ID
	DuplicateCount int
	CommentsCount  int

	// Closing (for verified/closed status)
	ClosedAt *time.Time
	ClosedBy *shared.ID

	// Risk acceptance expiration
	AcceptanceExpiresAt *time.Time

	// Identification
	ScanID      string
	Fingerprint string

	// Meta
	Metadata  map[string]any
	CreatedAt time.Time
	UpdatedAt time.Time
	CreatedBy *shared.ID // Pentest ownership: who authored the finding

	// CTEM: Exposure Vector
	ExposureVector       ExposureVector
	IsNetworkAccessible  bool
	IsInternetAccessible bool
	AttackPrerequisites  string

	// CTEM: Remediation Context
	RemediationType  RemediationType
	EstimatedFixTime *int
	FixComplexity    FixComplexity
	RemedyAvailable  bool
	FixCode          string    // Auto-fix code snippet
	FixRegex         *FixRegex // Regex-based fix pattern

	// ASVS (Application Security Verification Standard) compliance
	ASVSSection    string
	ASVSControlID  string
	ASVSControlURL string
	ASVSLevel      *int

	// CTEM: Business Impact
	DataExposureRisk   DataExposureRisk
	ReputationalImpact bool
	ComplianceImpact   []string

	// SARIF 2.1.0 Fields
	Confidence          *int
	Impact              string
	Likelihood          string
	VulnerabilityClass  []string
	Subcategory         []string
	BaselineState       string
	Kind                string
	Rank                *float64
	OccurrenceCount     int
	CorrelationID       string
	PartialFingerprints map[string]string
	RelatedLocations    []FindingLocation
	Stacks              []StackTrace
	Attachments         []Attachment
	WorkItemURIs        []string
	HostedViewerURI     string
}

FindingData contains all data needed to reconstitute a Finding from persistence.

type FindingDataFlow

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

FindingDataFlow represents a data flow trace (taint tracking path) for a finding. Maps to SARIF codeFlows - showing how data flows from source to sink.

func NewFindingDataFlow

func NewFindingDataFlow(
	findingID shared.ID,
	flowIndex int,
	message string,
	importance string,
) (*FindingDataFlow, error)

NewFindingDataFlow creates a new FindingDataFlow.

func ReconstituteFindingDataFlow

func ReconstituteFindingDataFlow(data FindingDataFlowData) *FindingDataFlow

ReconstituteFindingDataFlow recreates a FindingDataFlow from persistence.

func (*FindingDataFlow) CreatedAt

func (f *FindingDataFlow) CreatedAt() time.Time

func (*FindingDataFlow) FindingID

func (f *FindingDataFlow) FindingID() shared.ID

func (*FindingDataFlow) FlowIndex

func (f *FindingDataFlow) FlowIndex() int

func (*FindingDataFlow) ID

func (f *FindingDataFlow) ID() shared.ID

func (*FindingDataFlow) Importance

func (f *FindingDataFlow) Importance() string

func (*FindingDataFlow) Message

func (f *FindingDataFlow) Message() string

type FindingDataFlowData

type FindingDataFlowData struct {
	ID         shared.ID
	FindingID  shared.ID
	FlowIndex  int
	Message    string
	Importance string
	CreatedAt  time.Time
}

FindingDataFlowData contains all data needed to reconstitute a FindingDataFlow from persistence.

type FindingFilter

type FindingFilter struct {
	TenantID        *shared.ID
	AssetID         *shared.ID // Reference to parent asset
	BranchID        *shared.ID // Optional: for repository assets, specific branch
	ComponentID     *shared.ID
	VulnerabilityID *shared.ID
	Severities      []Severity
	Statuses        []FindingStatus
	ExcludeStatuses []FindingStatus
	Sources         []FindingSource
	ToolName        *string
	RuleID          *string
	ScanID          *string
	FilePath        *string
	Search          *string  // Full-text search across title, description, and file path
	CVEIDs          []string // Filter by CVE IDs (e.g., ["CVE-2021-44228", "CVE-2021-45046"])
	AssetTags       []string // Filter by asset tags (requires JOIN with assets table)

	// Pentest filters
	PentestCampaignID  *shared.ID  // Filter by pentest campaign
	PentestCampaignIDs []shared.ID // Restrict to a set of campaigns (visibility filter — caller-resolved)
	// PentestCampaignMemberUserID: restrict findings to pentest campaigns where
	// the given user is a member (subquery). Cheaper than resolving IDs in Go for
	// users with many memberships.
	PentestCampaignMemberUserID *shared.ID

	// Finding type discriminator filters
	FindingTypes []FindingType

	// Specialized finding filters
	// Secret filters
	SecretType    *string
	SecretService *string
	SecretValid   *bool

	// Compliance filters
	ComplianceFramework *string
	ComplianceControlID *string
	ComplianceResult    *string

	// Web3 filters
	Web3Chain           *string
	Web3ContractAddress *string
	Web3SWCID           *string

	// Misconfiguration filters
	MisconfigPolicyID     *string
	MisconfigResourceType *string

	// Layer 2: Data Scope - filter findings by user's group membership on assets
	// When set, only findings for assets accessible to this user are returned.
	// Backward compat: if user has no group assignments, all findings are visible.
	DataScopeUserID *shared.ID
}

FindingFilter defines criteria for filtering findings.

func NewFindingFilter

func NewFindingFilter() FindingFilter

NewFindingFilter creates a new empty filter.

func (FindingFilter) IsEmpty

func (f FindingFilter) IsEmpty() bool

IsEmpty checks if no filters are applied.

func (FindingFilter) WithAssetID

func (f FindingFilter) WithAssetID(assetID shared.ID) FindingFilter

WithAssetID sets the asset ID filter.

func (FindingFilter) WithAssetTags added in v0.1.3

func (f FindingFilter) WithAssetTags(tags []string) FindingFilter

WithAssetTags adds an asset tags filter (requires JOIN with assets table).

func (FindingFilter) WithBranchID

func (f FindingFilter) WithBranchID(branchID shared.ID) FindingFilter

WithBranchID sets the branch ID filter.

func (FindingFilter) WithCVEIDs added in v0.1.3

func (f FindingFilter) WithCVEIDs(cveIDs []string) FindingFilter

WithCVEIDs adds a CVE IDs filter.

func (FindingFilter) WithComplianceControlID

func (f FindingFilter) WithComplianceControlID(controlID string) FindingFilter

WithComplianceControlID filters by compliance control ID.

func (FindingFilter) WithComplianceFramework

func (f FindingFilter) WithComplianceFramework(framework string) FindingFilter

WithComplianceFramework filters by compliance framework.

func (FindingFilter) WithComplianceResult

func (f FindingFilter) WithComplianceResult(result string) FindingFilter

WithComplianceResult filters by compliance result.

func (FindingFilter) WithComponentID

func (f FindingFilter) WithComponentID(compID shared.ID) FindingFilter

WithComponentID sets the component ID filter.

func (FindingFilter) WithDataScopeUserID added in v0.1.2

func (f FindingFilter) WithDataScopeUserID(id shared.ID) FindingFilter

WithDataScopeUserID adds a data scope filter by user's group membership on assets.

func (FindingFilter) WithExcludeStatuses added in v0.1.2

func (f FindingFilter) WithExcludeStatuses(statuses ...FindingStatus) FindingFilter

WithExcludeStatuses sets statuses to exclude from results.

func (FindingFilter) WithFilePath

func (f FindingFilter) WithFilePath(filePath string) FindingFilter

WithFilePath sets the file path filter.

func (FindingFilter) WithFindingTypes

func (f FindingFilter) WithFindingTypes(types ...FindingType) FindingFilter

WithFindingTypes filters by finding types.

func (FindingFilter) WithMisconfigPolicyID

func (f FindingFilter) WithMisconfigPolicyID(policyID string) FindingFilter

WithMisconfigPolicyID filters by misconfiguration policy ID.

func (FindingFilter) WithMisconfigResourceType

func (f FindingFilter) WithMisconfigResourceType(resourceType string) FindingFilter

WithMisconfigResourceType filters by misconfiguration resource type.

func (FindingFilter) WithRuleID

func (f FindingFilter) WithRuleID(ruleID string) FindingFilter

WithRuleID sets the rule ID filter.

func (FindingFilter) WithScanID

func (f FindingFilter) WithScanID(scanID string) FindingFilter

WithScanID sets the scan ID filter.

func (FindingFilter) WithSearch

func (f FindingFilter) WithSearch(search string) FindingFilter

WithSearch sets the full-text search filter.

func (FindingFilter) WithSecretService

func (f FindingFilter) WithSecretService(secretService string) FindingFilter

WithSecretService filters by secret service.

func (FindingFilter) WithSecretType

func (f FindingFilter) WithSecretType(secretType string) FindingFilter

WithSecretType filters by secret type.

func (FindingFilter) WithSecretValid

func (f FindingFilter) WithSecretValid(valid bool) FindingFilter

WithSecretValid filters by secret validity.

func (FindingFilter) WithSeverities

func (f FindingFilter) WithSeverities(severities ...Severity) FindingFilter

WithSeverities sets the severities filter.

func (FindingFilter) WithSources

func (f FindingFilter) WithSources(sources ...FindingSource) FindingFilter

WithSources sets the sources filter.

func (FindingFilter) WithStatuses

func (f FindingFilter) WithStatuses(statuses ...FindingStatus) FindingFilter

WithStatuses sets the statuses filter.

func (FindingFilter) WithTenantID

func (f FindingFilter) WithTenantID(tenantID shared.ID) FindingFilter

WithTenantID sets the tenant ID filter.

func (FindingFilter) WithToolName

func (f FindingFilter) WithToolName(toolName string) FindingFilter

WithToolName sets the tool name filter.

func (FindingFilter) WithVulnerabilityID

func (f FindingFilter) WithVulnerabilityID(vulnID shared.ID) FindingFilter

WithVulnerabilityID sets the vulnerability ID filter.

func (FindingFilter) WithWeb3Chain

func (f FindingFilter) WithWeb3Chain(chain string) FindingFilter

WithWeb3Chain filters by blockchain chain.

func (FindingFilter) WithWeb3ContractAddress

func (f FindingFilter) WithWeb3ContractAddress(address string) FindingFilter

WithWeb3ContractAddress filters by smart contract address.

func (FindingFilter) WithWeb3SWCID

func (f FindingFilter) WithWeb3SWCID(swcID string) FindingFilter

WithWeb3SWCID filters by SWC ID.

type FindingFlowLocation

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

FindingFlowLocation represents a single step in a data flow trace. Maps to SARIF threadFlowLocation - each step from source to sink.

func NewFindingFlowLocation

func NewFindingFlowLocation(
	dataFlowID shared.ID,
	stepIndex int,
	locationType string,
) (*FindingFlowLocation, error)

NewFindingFlowLocation creates a new FindingFlowLocation.

func ReconstituteFindingFlowLocation

func ReconstituteFindingFlowLocation(data FindingFlowLocationData) *FindingFlowLocation

ReconstituteFindingFlowLocation recreates a FindingFlowLocation from persistence.

func (*FindingFlowLocation) ClassName

func (f *FindingFlowLocation) ClassName() string

func (*FindingFlowLocation) DataFlowID

func (f *FindingFlowLocation) DataFlowID() shared.ID

func (*FindingFlowLocation) EndColumn

func (f *FindingFlowLocation) EndColumn() int

func (*FindingFlowLocation) EndLine

func (f *FindingFlowLocation) EndLine() int

func (*FindingFlowLocation) FilePath

func (f *FindingFlowLocation) FilePath() string

func (*FindingFlowLocation) FullyQualifiedName

func (f *FindingFlowLocation) FullyQualifiedName() string

func (*FindingFlowLocation) FunctionName

func (f *FindingFlowLocation) FunctionName() string

func (*FindingFlowLocation) ID

func (f *FindingFlowLocation) ID() shared.ID

func (*FindingFlowLocation) Importance

func (f *FindingFlowLocation) Importance() string

func (*FindingFlowLocation) IsIntermediate

func (f *FindingFlowLocation) IsIntermediate() bool

IsIntermediate returns true if this location is an intermediate step.

func (*FindingFlowLocation) IsSanitizer

func (f *FindingFlowLocation) IsSanitizer() bool

IsSanitizer returns true if this location is a sanitizer (safe path).

func (*FindingFlowLocation) IsSink

func (f *FindingFlowLocation) IsSink() bool

IsSink returns true if this location is the vulnerable sink.

func (*FindingFlowLocation) IsSource

func (f *FindingFlowLocation) IsSource() bool

IsSource returns true if this location is the taint source.

func (*FindingFlowLocation) Label

func (f *FindingFlowLocation) Label() string

func (*FindingFlowLocation) LocationType

func (f *FindingFlowLocation) LocationType() string

func (*FindingFlowLocation) Message

func (f *FindingFlowLocation) Message() string

func (*FindingFlowLocation) ModuleName

func (f *FindingFlowLocation) ModuleName() string

func (*FindingFlowLocation) NestingLevel

func (f *FindingFlowLocation) NestingLevel() int

func (*FindingFlowLocation) SetContext

func (f *FindingFlowLocation) SetContext(label, message string, nestingLevel int, importance string)

func (*FindingFlowLocation) SetLogicalLocation

func (f *FindingFlowLocation) SetLogicalLocation(functionName, className, fullyQualifiedName, moduleName string)

func (*FindingFlowLocation) SetPhysicalLocation

func (f *FindingFlowLocation) SetPhysicalLocation(filePath string, startLine, endLine, startColumn, endColumn int, snippet string)

func (*FindingFlowLocation) Snippet

func (f *FindingFlowLocation) Snippet() string

func (*FindingFlowLocation) StartColumn

func (f *FindingFlowLocation) StartColumn() int

func (*FindingFlowLocation) StartLine

func (f *FindingFlowLocation) StartLine() int

func (*FindingFlowLocation) StepIndex

func (f *FindingFlowLocation) StepIndex() int

func (*FindingFlowLocation) ToFindingLocation

func (f *FindingFlowLocation) ToFindingLocation() FindingLocation

ToFindingLocation converts to a FindingLocation value object.

type FindingFlowLocationData

type FindingFlowLocationData struct {
	ID           shared.ID
	DataFlowID   shared.ID
	StepIndex    int
	LocationType string

	// Physical
	FilePath    string
	StartLine   int
	EndLine     int
	StartColumn int
	EndColumn   int
	Snippet     string

	// Logical
	FunctionName       string
	ClassName          string
	FullyQualifiedName string
	ModuleName         string

	// Context
	Label        string
	Message      string
	NestingLevel int
	Importance   string
}

FindingFlowLocationData contains all data needed to reconstitute a FindingFlowLocation from persistence.

type FindingGroup added in v0.1.3

type FindingGroup struct {
	GroupKey  string         // CVE ID, asset UUID, owner UUID, severity, etc.
	GroupType string         // "cve", "asset", "owner", "component", "severity", "source", "finding_type"
	Label     string         // Human-readable: "Apache Log4j RCE", "Host C", "Alice", "critical"
	Severity  string         // Top severity in group (for sorting)
	Metadata  map[string]any // Extra info: cvss_score, epss_score, asset_type, email, etc.
	Stats     FindingGroupStats
}

FindingGroup represents a group of findings aggregated by a dimension.

type FindingGroupStats added in v0.1.3

type FindingGroupStats struct {
	Total          int     `json:"total"`
	Open           int     `json:"open"` // new + confirmed
	InProgress     int     `json:"in_progress"`
	FixApplied     int     `json:"fix_applied"`
	Resolved       int     `json:"resolved"` // resolved + verified
	AffectedAssets int     `json:"affected_assets"`
	ResolvedAssets int     `json:"resolved_assets"`
	ProgressPct    float64 `json:"progress_pct"`
}

FindingGroupStats holds aggregated counts for a finding group.

type FindingKind

type FindingKind string

FindingKind represents the evaluation state of a finding (SARIF kind).

const (
	FindingKindNotApplicable FindingKind = "not_applicable" // Rule didn't apply
	FindingKindPass          FindingKind = "pass"           // Rule passed
	FindingKindFail          FindingKind = "fail"           // Rule failed (vulnerability)
	FindingKindReview        FindingKind = "review"         // Needs manual review
	FindingKindOpen          FindingKind = "open"           // Open question/issue
	FindingKindInformational FindingKind = "informational"  // FYI only
)

func ParseFindingKind

func ParseFindingKind(s string) (FindingKind, error)

ParseFindingKind parses a string into a FindingKind.

func (FindingKind) IsValid

func (k FindingKind) IsValid() bool

IsValid checks if the finding kind is valid.

func (FindingKind) String

func (k FindingKind) String() string

String returns the string representation.

type FindingListOptions

type FindingListOptions struct {
	Sort *pagination.SortOption
}

FindingListOptions contains options for listing findings (sorting).

func NewFindingListOptions

func NewFindingListOptions() FindingListOptions

NewFindingListOptions creates empty list options.

func (FindingListOptions) WithSort

WithSort adds sorting options.

type FindingLocation

type FindingLocation struct {
	Path            string           `json:"path,omitempty"`
	StartLine       int              `json:"start_line,omitempty"`
	EndLine         int              `json:"end_line,omitempty"`
	StartColumn     int              `json:"start_column,omitempty"`
	EndColumn       int              `json:"end_column,omitempty"`
	Snippet         string           `json:"snippet,omitempty"`
	ContextSnippet  string           `json:"context_snippet,omitempty"`
	Branch          string           `json:"branch,omitempty"`
	CommitSHA       string           `json:"commit_sha,omitempty"`
	Message         string           `json:"message,omitempty"` // Optional description of why this location is relevant
	LogicalLocation *LogicalLocation `json:"logical_location,omitempty"`
}

FindingLocation represents a location within code (SARIF location).

type FindingRemediation

type FindingRemediation struct {
	// Human-readable recommendation text (guidance on how to fix)
	Recommendation string `json:"recommendation,omitempty"`

	// Actual code fix to apply (for auto-fix features)
	FixCode string `json:"fix_code,omitempty"`

	// Regex-based fix pattern
	FixRegex *FixRegex `json:"fix_regex,omitempty"`

	// Step-by-step remediation instructions
	Steps []string `json:"steps,omitempty"`

	// Reference URLs for more information
	References []string `json:"references,omitempty"`

	// Effort estimate: trivial, low, medium, high
	Effort string `json:"effort,omitempty"`

	// Whether a fix is available
	FixAvailable bool `json:"fix_available,omitempty"`

	// Whether the fix can be auto-applied
	AutoFixable bool `json:"auto_fixable,omitempty"`
}

FindingRemediation contains all remediation information for a finding. Stored as JSONB in the database for flexibility and extensibility.

func (*FindingRemediation) HasFix

func (r *FindingRemediation) HasFix() bool

HasFix checks if remediation has any fix available.

func (*FindingRemediation) IsEmpty

func (r *FindingRemediation) IsEmpty() bool

IsEmpty checks if the remediation is empty.

type FindingRepository

type FindingRepository interface {
	// Create persists a new finding.
	Create(ctx context.Context, finding *Finding) error

	// CreateInTx persists a new finding within an existing transaction.
	// This is used for the transactional outbox pattern.
	CreateInTx(ctx context.Context, tx *sql.Tx, finding *Finding) error

	// CreateBatch persists multiple findings in a single transaction.
	// Deprecated: Use CreateBatchWithResult for better error handling.
	// This method uses all-or-nothing semantics - if one finding fails, all fail.
	CreateBatch(ctx context.Context, findings []*Finding) error

	// CreateBatchWithResult persists multiple findings with partial success support.
	// Uses chunked transactions to isolate failures - if one chunk fails,
	// only that chunk is retried individually to identify the bad finding.
	// Returns detailed result with created/skipped counts and per-finding errors.
	CreateBatchWithResult(ctx context.Context, findings []*Finding) (*BatchCreateResult, error)

	// GetByID retrieves a finding by ID.
	// Security: Requires tenantID to prevent cross-tenant data access (IDOR prevention).
	GetByID(ctx context.Context, tenantID, id shared.ID) (*Finding, error)

	// GetByIDs retrieves multiple findings by IDs within a tenant (batch fetch).
	// Security: Requires tenantID to prevent cross-tenant data access.
	GetByIDs(ctx context.Context, tenantID shared.ID, ids []shared.ID) ([]*Finding, error)

	// Update updates an existing finding.
	// Security: The Finding entity contains TenantID which is used to verify ownership.
	Update(ctx context.Context, finding *Finding) error

	// Delete removes a finding by ID.
	// Security: Requires tenantID to prevent cross-tenant deletion (IDOR prevention).
	Delete(ctx context.Context, tenantID, id shared.ID) error

	// List retrieves findings matching the filter with pagination and sorting.
	List(ctx context.Context, filter FindingFilter, opts FindingListOptions, page pagination.Pagination) (pagination.Result[*Finding], error)

	// ListByAssetID retrieves findings for an asset.
	// Security: Requires tenantID to prevent cross-tenant data access.
	ListByAssetID(ctx context.Context, tenantID, assetID shared.ID, opts FindingListOptions, page pagination.Pagination) (pagination.Result[*Finding], error)

	// ListByVulnerabilityID retrieves findings for a vulnerability.
	// Security: Requires tenantID to prevent cross-tenant data access.
	ListByVulnerabilityID(ctx context.Context, tenantID, vulnID shared.ID, opts FindingListOptions, page pagination.Pagination) (pagination.Result[*Finding], error)

	// ListByComponentID retrieves findings for a component.
	// Security: Requires tenantID to prevent cross-tenant data access.
	ListByComponentID(ctx context.Context, tenantID, compID shared.ID, opts FindingListOptions, page pagination.Pagination) (pagination.Result[*Finding], error)

	// Count returns the count of findings matching the filter.
	Count(ctx context.Context, filter FindingFilter) (int64, error)

	// CountByAssetID returns the count of findings for an asset.
	// Security: Requires tenantID to prevent cross-tenant data access.
	CountByAssetID(ctx context.Context, tenantID, assetID shared.ID) (int64, error)

	// CountOpenByAssetID returns the count of open findings for an asset.
	// Security: Requires tenantID to prevent cross-tenant data access.
	CountOpenByAssetID(ctx context.Context, tenantID, assetID shared.ID) (int64, error)

	// GetByFingerprint retrieves a finding by fingerprint.
	GetByFingerprint(ctx context.Context, tenantID shared.ID, fingerprint string) (*Finding, error)

	// ExistsByFingerprint checks if a finding with the given fingerprint exists.
	ExistsByFingerprint(ctx context.Context, tenantID shared.ID, fingerprint string) (bool, error)

	// CheckFingerprintsExist checks which fingerprints already exist in the database.
	// Returns a map of fingerprint -> exists boolean.
	CheckFingerprintsExist(ctx context.Context, tenantID shared.ID, fingerprints []string) (map[string]bool, error)

	// UpdateScanIDBatchByFingerprints updates scan_id for multiple findings by their fingerprints.
	// Returns the count of updated findings.
	UpdateScanIDBatchByFingerprints(ctx context.Context, tenantID shared.ID, fingerprints []string, scanID string) (int64, error)

	// UpdateSnippetBatchByFingerprints updates snippet for findings that have invalid snippets
	// ("requires login" or empty). Only updates if new snippet is valid.
	// snippets is a map of fingerprint -> new snippet
	UpdateSnippetBatchByFingerprints(ctx context.Context, tenantID shared.ID, snippets map[string]string) (int64, error)

	// BatchCountByAssetIDs returns the count of findings for multiple assets in one query.
	// Security: Requires tenantID to prevent cross-tenant data access.
	// Returns a map of assetID -> count.
	BatchCountByAssetIDs(ctx context.Context, tenantID shared.ID, assetIDs []shared.ID) (map[shared.ID]int64, error)

	// UpdateStatus updates the status of multiple findings.
	// Security: Requires tenantID to prevent cross-tenant status modification.
	UpdateStatusBatch(ctx context.Context, tenantID shared.ID, ids []shared.ID, status FindingStatus, resolution string, resolvedBy *shared.ID) error

	// DeleteByAssetID removes all findings for an asset.
	// Security: Requires tenantID to prevent cross-tenant deletion.
	DeleteByAssetID(ctx context.Context, tenantID, assetID shared.ID) error

	// DeleteByScanID removes all findings for a scan.
	DeleteByScanID(ctx context.Context, tenantID shared.ID, scanID string) error

	// GetStats returns aggregated statistics for findings.
	// dataScopeUserID: if non-nil, only count findings for assets accessible to this user.
	// assetID: if non-nil, only count findings for this specific asset
	//          (used by /findings?assetId=… so the severity cards reflect
	//          the filtered table, not the global tenant).
	GetStats(ctx context.Context, tenantID shared.ID, dataScopeUserID *shared.ID, assetID *shared.ID) (*FindingStats, error)

	// CountBySeverityForScan returns the count of findings grouped by severity for a scan.
	// Used for quality gate evaluation.
	CountBySeverityForScan(ctx context.Context, tenantID shared.ID, scanID string) (SeverityCounts, error)

	// AutoResolveStale marks findings as resolved when not found in current full scan.
	// Only affects findings on the default branch (via branch_id FK to asset_branches.is_default).
	// Only affects active statuses (new, open, confirmed, in_progress).
	// Protected statuses (false_positive, accepted, duplicate) are never auto-resolved.
	// If branchID is provided, only auto-resolves findings on that branch if it's a default branch.
	// If branchID is nil, auto-resolves findings where branch_id points to any default branch.
	// Returns the count of auto-resolved findings and their IDs for activity logging.
	AutoResolveStale(ctx context.Context, tenantID shared.ID, assetID shared.ID, toolName string, currentScanID string, branchID *shared.ID) ([]shared.ID, error)

	// AutoReopenByFingerprint reopens a previously auto-resolved finding if it reappears.
	// Only reopens findings with resolution = 'auto_fixed'.
	// Protected resolutions (false_positive, accepted_risk) are never reopened.
	// Returns the finding ID if reopened, nil if not found or protected.
	AutoReopenByFingerprint(ctx context.Context, tenantID shared.ID, fingerprint string) (*shared.ID, error)

	// AutoReopenByFingerprintsBatch reopens multiple previously auto-resolved findings in a single query.
	// This is the batch version of AutoReopenByFingerprint for better performance.
	// Only reopens findings with resolution = 'auto_fixed'.
	// Protected resolutions (false_positive, accepted_risk) are never reopened.
	// Returns a map of fingerprint -> reopened finding ID.
	AutoReopenByFingerprintsBatch(ctx context.Context, tenantID shared.ID, fingerprints []string) (map[string]shared.ID, error)

	// ExpireFeatureBranchFindings marks stale feature branch findings as resolved.
	// This is called by a background job to clean up findings on non-default branches
	// that have not been seen for a configurable period.
	// Uses JOIN with asset_branches to determine:
	// - branch_id links to a non-default branch (is_default = false)
	// - branch allows expiry (keep_when_inactive = false)
	// - retention_days per branch or defaultExpiryDays as fallback
	// Only affects findings where status IN ('new', 'open').
	// Returns the count of expired findings.
	ExpireFeatureBranchFindings(ctx context.Context, tenantID shared.ID, defaultExpiryDays int) (int64, error)

	// ExistsByIDs checks which finding IDs exist in the database.
	// Returns a map of finding ID -> exists boolean.
	// Security: Requires tenantID to prevent cross-tenant data access.
	// Used for batch validation in bulk operations (e.g., bulk AI triage).
	ExistsByIDs(ctx context.Context, tenantID shared.ID, ids []shared.ID) (map[shared.ID]bool, error)

	// GetByFingerprintsBatch retrieves multiple findings by their fingerprints in a single query.
	// Returns a map of fingerprint -> *Finding for all found findings.
	// Security: Requires tenantID to enforce tenant isolation.
	GetByFingerprintsBatch(ctx context.Context, tenantID shared.ID, fingerprints []string) (map[string]*Finding, error)

	// EnrichBatchByFingerprints enriches existing findings with new scan data using domain EnrichFrom() rules.
	// Loads existing findings by fingerprint, applies enrichment from newFindings, and batch updates.
	// Protected fields (status, resolution, assigned_to, etc.) are never modified.
	// Returns the count of enriched findings.
	EnrichBatchByFingerprints(ctx context.Context, tenantID shared.ID, newFindings []*Finding, scanID string) (int64, error)

	// ListFindingGroups returns findings grouped by a dimension (cve_id, asset_id, owner_id, etc.).
	ListFindingGroups(ctx context.Context, tenantID shared.ID, groupBy string, filter FindingFilter, page pagination.Pagination) (pagination.Result[*FindingGroup], error)

	// BulkUpdateStatusByFilter updates status for all findings matching filter.
	// Batches internally (500/tx). Excludes pentest findings.
	// Returns count of updated findings.
	BulkUpdateStatusByFilter(ctx context.Context, tenantID shared.ID, filter FindingFilter, status FindingStatus, resolution string, resolvedBy *shared.ID) (int64, error)

	// FindRelatedCVEs finds CVEs that share the same component as the given CVE.
	// Used to suggest "upgrade component X also fixes these CVEs".
	// Returns max 10 results.
	FindRelatedCVEs(ctx context.Context, tenantID shared.ID, cveID string, filter FindingFilter) ([]RelatedCVE, error)

	// ListByStatusAndAssets returns findings with a specific status on specific assets.
	// Used by auto-verify: find fix_applied findings on assets that were just scanned.
	ListByStatusAndAssets(ctx context.Context, tenantID shared.ID, status FindingStatus, assetIDs []shared.ID) ([]*Finding, error)
}

FindingRepository defines the interface for finding persistence.

type FindingSource

type FindingSource string

FindingSource represents the source/type of a finding.

## Architecture

Finding sources are managed in two layers:

  1. **Database layer** (finding_sources table): Dynamic configuration for UI dropdowns, metadata (icons, colors, categories), and runtime validation. Managed by FindingSourceService and FindingSourceCacheService.

  2. **Code layer** (constants below): Compile-time type safety for domain logic, switch statements, and tests. These constants must match the `code` field in the finding_sources database table.

## When to use what:

- Use FindingSourceCacheService.IsValidCode() for validating user input at runtime - Use the constants below for domain logic and tests (type safety) - The constants are kept in sync with the database via migration 000142_finding_sources

## Adding new sources:

1. Add a migration to insert the new source into finding_sources table 2. Add a constant below with matching code 3. Update IsValid() and AllFindingSources()

const (
	// AppSec Scanning sources
	FindingSourceSAST      FindingSource = "sast"      // Static Application Security Testing (Semgrep, CodeQL, etc.)
	FindingSourceDAST      FindingSource = "dast"      // Dynamic Application Security Testing (ZAP, Burp, Nuclei)
	FindingSourceSCA       FindingSource = "sca"       // Software Composition Analysis (Trivy, Snyk, Grype)
	FindingSourceSecret    FindingSource = "secret"    // Secret Detection (Gitleaks, Trufflehog)
	FindingSourceIaC       FindingSource = "iac"       // Infrastructure as Code (Checkov, Tfsec)
	FindingSourceContainer FindingSource = "container" // Container Scanning

	// Cloud & Infrastructure sources
	FindingSourceCSPM FindingSource = "cspm" // Cloud Security Posture Management (Wiz, Prisma Cloud)
	FindingSourceEASM FindingSource = "easm" // External Attack Surface Management (Censys, Shodan)

	// Runtime & Production sources
	FindingSourceRASP FindingSource = "rasp" // Runtime Application Self-Protection
	FindingSourceWAF  FindingSource = "waf"  // Web Application Firewall
	FindingSourceSIEM FindingSource = "siem" // Security Information and Event Management

	// Manual/Human sources
	FindingSourceManual    FindingSource = "manual"     // Manual findings/code review
	FindingSourcePentest   FindingSource = "pentest"    // Penetration testing engagement
	FindingSourceBugBounty FindingSource = "bug_bounty" // Bug bounty program
	FindingSourceRedTeam   FindingSource = "red_team"   // Red team exercise

	// External sources
	FindingSourceExternal    FindingSource = "external"     // Imported from external tools
	FindingSourceThreatIntel FindingSource = "threat_intel" // Threat intelligence feeds
	FindingSourceVendor      FindingSource = "vendor"       // Vendor security assessments

	// Legacy aliases for backward compatibility
	FindingSourceSARIF   FindingSource = "sarif"    // SARIF format (legacy)
	FindingSourceSCATool FindingSource = "sca_tool" // Legacy SCA alias
)

func AllFindingSources

func AllFindingSources() []FindingSource

AllFindingSources returns all valid finding sources (primary only, excluding legacy).

func ParseFindingSource

func ParseFindingSource(s string) (FindingSource, error)

ParseFindingSource parses a string into a FindingSource.

func (FindingSource) IsValid

func (f FindingSource) IsValid() bool

IsValid checks if the finding source is valid. NOTE: This performs static validation. For dynamic validation against the database, use the FindingSourceService.IsValidSourceCode() method.

func (FindingSource) Normalize

func (f FindingSource) Normalize() FindingSource

Normalize converts legacy source values to canonical values.

func (FindingSource) String

func (f FindingSource) String() string

String returns the string representation.

type FindingStats

type FindingStats struct {
	Total         int64
	BySeverity    map[Severity]int64
	ByStatus      map[FindingStatus]int64
	BySource      map[FindingSource]int64
	OpenCount     int64
	ResolvedCount int64
}

FindingStats contains aggregated finding statistics.

func NewFindingStats

func NewFindingStats() *FindingStats

NewFindingStats creates an empty FindingStats with initialized maps.

type FindingStatus

type FindingStatus string

FindingStatus represents the status of a finding. Simplified workflow: new → confirmed → in_progress → resolved Terminal states: false_positive, accepted, duplicate (can reopen to confirmed)

const (
	// Open states (needs action)
	FindingStatusNew        FindingStatus = "new"         // Scanner just found it
	FindingStatusConfirmed  FindingStatus = "confirmed"   // Verified as real issue, needs fix
	FindingStatusInProgress FindingStatus = "in_progress" // Developer working on fix

	// Verification state (dev marked fix, awaiting scanner/security verify)
	FindingStatusFixApplied FindingStatus = "fix_applied" // Dev/owner marked as fixed, pending verification

	// Closed states
	FindingStatusResolved      FindingStatus = "resolved"       // Verified fixed (by scan or security review)
	FindingStatusFalsePositive FindingStatus = "false_positive" // Not a real issue (requires approval)
	FindingStatusAccepted      FindingStatus = "accepted"       // Risk accepted (requires approval, has expiration)
	FindingStatusDuplicate     FindingStatus = "duplicate"      // Linked to another finding

	// Pentest-specific states (only valid for source='pentest')
	FindingStatusDraft        FindingStatus = "draft"         // Pentester drafting (hidden from dashboard)
	FindingStatusInReview     FindingStatus = "in_review"     // Peer reviewing (hidden from dashboard)
	FindingStatusRemediation  FindingStatus = "remediation"   // Dev fixing (pentest-specific)
	FindingStatusRetest       FindingStatus = "retest"        // Awaiting re-verification
	FindingStatusVerified     FindingStatus = "verified"      // Manual retest passed (pentest resolve)
	FindingStatusAcceptedRisk FindingStatus = "accepted_risk" // Risk accepted (pentest alias for accepted)
)

func ActiveFindingStatuses

func ActiveFindingStatuses() []FindingStatus

ActiveFindingStatuses returns statuses that count as "active" findings (need action).

func AllFindingStatuses

func AllFindingStatuses() []FindingStatus

AllFindingStatuses returns all valid finding statuses.

func ParseFindingStatus

func ParseFindingStatus(s string) (FindingStatus, error)

ParseFindingStatus parses a string into a FindingStatus.

func (FindingStatus) CanTransitionTo

func (f FindingStatus) CanTransitionTo(target FindingStatus) bool

CanTransitionTo checks if a status can transition to another status.

func (FindingStatus) Category

func (f FindingStatus) Category() StatusCategory

Category returns the status category.

func (FindingStatus) GetValidTransitions

func (f FindingStatus) GetValidTransitions() []FindingStatus

GetValidTransitions returns the valid transitions for this status.

func (FindingStatus) IsClosed

func (f FindingStatus) IsClosed() bool

IsClosed checks if the status represents a closed finding.

func (FindingStatus) IsFixApplied added in v0.1.3

func (f FindingStatus) IsFixApplied() bool

IsFixApplied checks if the finding has been marked as fix applied (pending verification).

func (FindingStatus) IsOpen

func (f FindingStatus) IsOpen() bool

IsOpen checks if the status represents an open finding (needs action).

func (FindingStatus) IsResolved

func (f FindingStatus) IsResolved() bool

IsResolved checks if the finding has been remediated.

func (FindingStatus) IsValid

func (f FindingStatus) IsValid() bool

IsValid checks if the finding status is valid.

func (FindingStatus) RequiresApproval

func (f FindingStatus) RequiresApproval() bool

RequiresApproval checks if transitioning to this status requires approval.

func (FindingStatus) RequiresVerifyPermission added in v0.1.3

func (f FindingStatus) RequiresVerifyPermission() bool

RequiresVerifyPermission checks if transitioning to this status from certain states requires the findings:verify permission (e.g., confirmed→resolved, fix_applied→resolved).

func (FindingStatus) String

func (f FindingStatus) String() string

String returns the string representation.

type FindingType

type FindingType string

FindingType represents the type/category of a finding. This is a discriminator for polymorphic behavior (fingerprinting, detail storage).

const (
	// FindingTypeVulnerability represents code vulnerabilities (SAST/DAST/SCA findings).
	FindingTypeVulnerability FindingType = "vulnerability"
	// FindingTypeSecret represents exposed secrets/credentials.
	FindingTypeSecret FindingType = "secret"
	// FindingTypeMisconfiguration represents IaC/infrastructure misconfigurations.
	FindingTypeMisconfiguration FindingType = "misconfiguration"
	// FindingTypeCompliance represents compliance check failures.
	FindingTypeCompliance FindingType = "compliance"
	// FindingTypeWeb3 represents blockchain/smart contract vulnerabilities.
	FindingTypeWeb3 FindingType = "web3"
)

func AllFindingTypes

func AllFindingTypes() []FindingType

AllFindingTypes returns all valid finding types.

func ParseFindingType

func ParseFindingType(s string) (FindingType, error)

ParseFindingType parses a string into a FindingType.

func (FindingType) InferFromSource

func (t FindingType) InferFromSource(source FindingSource) FindingType

InferFromSource infers the FindingType from a FindingSource.

func (FindingType) IsValid

func (t FindingType) IsValid() bool

IsValid checks if the finding type is valid.

func (FindingType) String

func (t FindingType) String() string

String returns the string representation.

type FingerprintStrategy

type FingerprintStrategy interface {
	// Generate creates a fingerprint for the given finding.
	Generate(f *Finding) string
	// Name returns the strategy name (for storing in partial_fingerprints).
	Name() string
}

FingerprintStrategy defines the interface for generating finding fingerprints. Different finding types may have different fingerprinting requirements.

func GetFingerprintStrategy

func GetFingerprintStrategy(findingType FindingType, source FindingSource) FingerprintStrategy

GetFingerprintStrategy returns the appropriate fingerprint strategy based on finding type.

type FixComplexity

type FixComplexity string

FixComplexity represents the complexity of fixing a finding.

const (
	FixComplexitySimple   FixComplexity = "simple"   // < 1 hour
	FixComplexityModerate FixComplexity = "moderate" // 1-8 hours
	FixComplexityComplex  FixComplexity = "complex"  // > 8 hours
)

func AllFixComplexities

func AllFixComplexities() []FixComplexity

AllFixComplexities returns all valid fix complexities.

func ParseFixComplexity

func ParseFixComplexity(s string) (FixComplexity, error)

ParseFixComplexity parses a string into a FixComplexity.

func (FixComplexity) EstimatedMinutes

func (f FixComplexity) EstimatedMinutes() int

EstimatedMinutes returns the estimated minutes to fix based on complexity.

func (FixComplexity) IsValid

func (f FixComplexity) IsValid() bool

IsValid checks if the fix complexity is valid.

func (FixComplexity) String

func (f FixComplexity) String() string

String returns the string representation.

type FixRegex

type FixRegex struct {
	Regex       string `json:"regex,omitempty"`       // Regular expression pattern to match
	Replacement string `json:"replacement,omitempty"` // Replacement string (may contain capture groups like $1, $2)
	Count       int    `json:"count,omitempty"`       // Number of replacements (0 = all)
}

FixRegex contains regex-based auto-fix information. Used by tools like Semgrep that provide regex replacement patterns.

func (*FixRegex) IsEmpty

func (f *FixRegex) IsEmpty() bool

IsEmpty checks if the fix regex is empty.

type ImpactLevel

type ImpactLevel string

ImpactLevel represents the impact level for risk assessment.

const (
	ImpactCritical ImpactLevel = "critical"
	ImpactHigh     ImpactLevel = "high"
	ImpactMedium   ImpactLevel = "medium"
	ImpactLow      ImpactLevel = "low"
)

func ParseImpactLevel

func ParseImpactLevel(s string) (ImpactLevel, error)

ParseImpactLevel parses a string into an ImpactLevel.

func (ImpactLevel) IsValid

func (i ImpactLevel) IsValid() bool

IsValid checks if the impact level is valid.

func (ImpactLevel) String

func (i ImpactLevel) String() string

String returns the string representation.

type LikelihoodLevel

type LikelihoodLevel string

LikelihoodLevel represents the likelihood level for risk assessment.

const (
	LikelihoodHigh   LikelihoodLevel = "high"
	LikelihoodMedium LikelihoodLevel = "medium"
	LikelihoodLow    LikelihoodLevel = "low"
)

func ParseLikelihoodLevel

func ParseLikelihoodLevel(s string) (LikelihoodLevel, error)

ParseLikelihoodLevel parses a string into a LikelihoodLevel.

func (LikelihoodLevel) IsValid

func (l LikelihoodLevel) IsValid() bool

IsValid checks if the likelihood level is valid.

func (LikelihoodLevel) String

func (l LikelihoodLevel) String() string

String returns the string representation.

type LogicalLocation

type LogicalLocation struct {
	Name               string `json:"name,omitempty"`
	Kind               string `json:"kind,omitempty"` // function, method, class, module, etc.
	FullyQualifiedName string `json:"fully_qualified_name,omitempty"`
}

LogicalLocation represents a logical code location (function, class, etc.).

type MisconfigDetails

type MisconfigDetails struct {
	PolicyID     string `json:"policy_id,omitempty"`     // CKV_AWS_1, AVD-AWS-0001, etc.
	ResourceType string `json:"resource_type,omitempty"` // aws_s3_bucket, google_compute_instance
	ResourceName string `json:"resource_name,omitempty"` // Resource name/identifier in IaC
	ResourcePath string `json:"resource_path,omitempty"` // Full path to resource in IaC file
	Expected     string `json:"expected,omitempty"`      // Expected configuration value
	Actual       string `json:"actual,omitempty"`        // Actual configuration value found
	Cause        string `json:"cause,omitempty"`         // Root cause description
}

MisconfigDetails contains details specific to misconfiguration findings.

type MisconfigFingerprintStrategy

type MisconfigFingerprintStrategy struct{}

MisconfigFingerprintStrategy generates fingerprints for IaC/misconfiguration findings. Focuses on: asset, policy ID, resource type, and resource path.

func (*MisconfigFingerprintStrategy) Generate

func (*MisconfigFingerprintStrategy) Name

type Rectangle

type Rectangle struct {
	Top    float64 `json:"top,omitempty"`
	Left   float64 `json:"left,omitempty"`
	Bottom float64 `json:"bottom,omitempty"`
	Right  float64 `json:"right,omitempty"`
}

Rectangle represents a rectangular area in an image.

type Reference

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

Reference represents a reference URL.

func NewReference

func NewReference(refType, url string) Reference

NewReference creates a new Reference.

func (Reference) Type

func (r Reference) Type() string

Type returns the reference type.

func (Reference) URL

func (r Reference) URL() string

URL returns the reference URL.

type RelatedCVE added in v0.1.3

type RelatedCVE struct {
	CVEID        string `json:"cve_id"`
	Title        string `json:"title"`
	Severity     string `json:"severity"`
	FindingCount int    `json:"finding_count"`
}

RelatedCVE represents a CVE that shares the same component as another CVE.

type RemediationType

type RemediationType string

RemediationType represents the type of remediation required.

const (
	RemediationTypePatch      RemediationType = "patch"         // Apply a patch
	RemediationTypeUpgrade    RemediationType = "upgrade"       // Upgrade to newer version
	RemediationTypeWorkaround RemediationType = "workaround"    // Apply a workaround
	RemediationTypeConfig     RemediationType = "config_change" // Configuration change
	RemediationTypeMitigate   RemediationType = "mitigate"      // Apply mitigation controls
	RemediationTypeAcceptRisk RemediationType = "accept_risk"   // Accept the risk
)

func AllRemediationTypes

func AllRemediationTypes() []RemediationType

AllRemediationTypes returns all valid remediation types.

func ParseRemediationType

func ParseRemediationType(s string) (RemediationType, error)

ParseRemediationType parses a string into a RemediationType.

func (RemediationType) IsValid

func (r RemediationType) IsValid() bool

IsValid checks if the remediation type is valid.

func (RemediationType) String

func (r RemediationType) String() string

String returns the string representation.

type ResolutionMethod added in v0.1.3

type ResolutionMethod string

ResolutionMethod represents how a finding was resolved.

const (
	ResolutionMethodLegacy           ResolutionMethod = "legacy"            // Resolved before fix_applied lifecycle existed
	ResolutionMethodScanVerified     ResolutionMethod = "scan_verified"     // Scanner confirmed vulnerability is gone
	ResolutionMethodSecurityReviewed ResolutionMethod = "security_reviewed" // Security team manually approved
	ResolutionMethodAdminDirect      ResolutionMethod = "admin_direct"      // Admin/Owner direct resolve (escape hatch)
)

func (ResolutionMethod) IsValid added in v0.1.3

func (r ResolutionMethod) IsValid() bool

IsValid checks if the resolution method is valid.

func (ResolutionMethod) String added in v0.1.3

func (r ResolutionMethod) String() string

String returns the string representation.

type SASTFingerprintStrategy

type SASTFingerprintStrategy struct{}

SASTFingerprintStrategy generates fingerprints for SAST findings. Focuses on: asset, rule, file path, and normalized snippet (resilient to line shifts).

func (*SASTFingerprintStrategy) Generate

func (s *SASTFingerprintStrategy) Generate(f *Finding) string

func (*SASTFingerprintStrategy) Name

func (s *SASTFingerprintStrategy) Name() string

type SCAFingerprintStrategy

type SCAFingerprintStrategy struct{}

SCAFingerprintStrategy generates fingerprints for SCA (dependency) findings. Focuses on: asset, package (PURL), and CVE.

func (*SCAFingerprintStrategy) Generate

func (s *SCAFingerprintStrategy) Generate(f *Finding) string

func (*SCAFingerprintStrategy) Name

func (s *SCAFingerprintStrategy) Name() string

type SLAStatus

type SLAStatus string

SLAStatus represents the SLA compliance status of a finding.

const (
	SLAStatusOnTrack       SLAStatus = "on_track"
	SLAStatusWarning       SLAStatus = "warning"
	SLAStatusOverdue       SLAStatus = "overdue"
	SLAStatusExceeded      SLAStatus = "exceeded"
	SLAStatusNotApplicable SLAStatus = "not_applicable"
)

func AllSLAStatuses

func AllSLAStatuses() []SLAStatus

AllSLAStatuses returns all valid SLA statuses.

func ParseSLAStatus

func ParseSLAStatus(s string) (SLAStatus, error)

ParseSLAStatus parses a string into an SLAStatus.

func (SLAStatus) IsAtRisk

func (s SLAStatus) IsAtRisk() bool

IsAtRisk checks if the SLA status indicates risk.

func (SLAStatus) IsOverdue

func (s SLAStatus) IsOverdue() bool

IsOverdue checks if the SLA has been missed.

func (SLAStatus) IsValid

func (s SLAStatus) IsValid() bool

IsValid checks if the SLA status is valid.

func (SLAStatus) String

func (s SLAStatus) String() string

String returns the string representation.

type SecretDetails

type SecretDetails struct {
	SecretType string     `json:"secret_type,omitempty"` // api_key, token, password, private_key, certificate
	Service    string     `json:"service,omitempty"`     // aws, github, stripe, slack, etc.
	Valid      *bool      `json:"valid,omitempty"`       // Is the secret currently valid
	Revoked    *bool      `json:"revoked,omitempty"`     // Has the secret been revoked
	Entropy    *float64   `json:"entropy,omitempty"`     // Shannon entropy of the secret
	ExpiresAt  *time.Time `json:"expires_at,omitempty"`  // When the secret expires
	Scopes     []string   `json:"scopes,omitempty"`      // Permissions/scopes the secret has
	MaskedVal  string     `json:"masked_val,omitempty"`  // Masked value for display (e.g., "sk_live_****XXXX")
}

SecretDetails contains details specific to secret/credential findings.

type SecretFingerprintStrategy

type SecretFingerprintStrategy struct{}

SecretFingerprintStrategy generates fingerprints for secret findings. Focuses on: asset, secret type, service, and masked value prefix.

func (*SecretFingerprintStrategy) Generate

func (s *SecretFingerprintStrategy) Generate(f *Finding) string

func (*SecretFingerprintStrategy) Name

type Severity

type Severity string

Severity represents the vulnerability severity level.

const (
	SeverityCritical Severity = "critical"
	SeverityHigh     Severity = "high"
	SeverityMedium   Severity = "medium"
	SeverityLow      Severity = "low"
	SeverityInfo     Severity = "info"
	SeverityNone     Severity = "none"
)

func AllSeverities

func AllSeverities() []Severity

AllSeverities returns all valid severities.

func ParseSeverity

func ParseSeverity(s string) (Severity, error)

ParseSeverity parses a string into a Severity.

func SeverityFromCVSS

func SeverityFromCVSS(score float64) Severity

SeverityFromCVSS returns a Severity based on CVSS score.

func (Severity) IsValid

func (s Severity) IsValid() bool

IsValid checks if the severity is valid.

func (Severity) Score

func (s Severity) Score() float64

Score returns a numeric score for the severity (0-10).

func (Severity) String

func (s Severity) String() string

String returns the string representation.

func (Severity) Weight

func (s Severity) Weight() float64

Weight returns a weight for risk calculation.

type SeverityCounts

type SeverityCounts struct {
	Critical int `json:"critical"`
	High     int `json:"high"`
	Medium   int `json:"medium"`
	Low      int `json:"low"`
	Info     int `json:"info"`
	Total    int `json:"total"`
}

SeverityCounts holds the count of findings by severity level. Used for quality gate evaluation.

type StackFrame

type StackFrame struct {
	Location   *FindingLocation `json:"location,omitempty"`
	Module     string           `json:"module,omitempty"`
	ThreadID   int              `json:"thread_id,omitempty"`
	Parameters []string         `json:"parameters,omitempty"`
}

StackFrame represents a single frame in a call stack (SARIF stackFrame).

type StackTrace

type StackTrace struct {
	Message string       `json:"message,omitempty"`
	Frames  []StackFrame `json:"frames,omitempty"`
}

StackTrace represents a call stack (SARIF stack).

type StatusCategory

type StatusCategory string

StatusCategory represents the category of a finding status.

const (
	StatusCategoryOpen       StatusCategory = "open"        // Needs action
	StatusCategoryInProgress StatusCategory = "in_progress" // Work underway
	StatusCategoryClosed     StatusCategory = "closed"      // No action needed
)

type Vulnerability

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

Vulnerability represents a global vulnerability (CVE).

func NewVulnerability

func NewVulnerability(
	cveID string,
	title string,
	severity Severity,
) (*Vulnerability, error)

NewVulnerability creates a new Vulnerability.

func Reconstitute

func Reconstitute(
	id shared.ID,
	cveID string,
	aliases []string,
	title string,
	description string,
	severity Severity,
	cvssScore *float64,
	cvssVector string,
	epssScore *float64,
	epssPercentile *float64,
	cisaKEV *CISAKEV,
	exploitAvailable bool,
	exploitMaturity ExploitMaturity,
	references []Reference,
	affectedVersions []AffectedVersion,
	fixedVersions []string,
	remediation string,
	publishedAt *time.Time,
	modifiedAt *time.Time,
	status VulnerabilityStatus,
	createdAt time.Time,
	updatedAt time.Time,
) *Vulnerability

Reconstitute recreates a Vulnerability from persistence.

func (*Vulnerability) AddAffectedVersion

func (v *Vulnerability) AddAffectedVersion(av AffectedVersion)

AddAffectedVersion adds an affected version.

func (*Vulnerability) AddAlias

func (v *Vulnerability) AddAlias(alias string)

AddAlias adds an alias.

func (*Vulnerability) AddReference

func (v *Vulnerability) AddReference(ref Reference)

AddReference adds a reference.

func (*Vulnerability) AffectedVersions

func (v *Vulnerability) AffectedVersions() []AffectedVersion

AffectedVersions returns a copy of the affected versions.

func (*Vulnerability) Aliases

func (v *Vulnerability) Aliases() []string

Aliases returns a copy of the aliases.

func (*Vulnerability) CISAKEV

func (v *Vulnerability) CISAKEV() *CISAKEV

CISAKEV returns the CISA KEV data.

func (*Vulnerability) CVEID

func (v *Vulnerability) CVEID() string

CVEID returns the CVE ID.

func (*Vulnerability) CVSSScore

func (v *Vulnerability) CVSSScore() *float64

CVSSScore returns the CVSS score.

func (*Vulnerability) CVSSVector

func (v *Vulnerability) CVSSVector() string

CVSSVector returns the CVSS vector.

func (*Vulnerability) CreatedAt

func (v *Vulnerability) CreatedAt() time.Time

CreatedAt returns the creation time.

func (*Vulnerability) Description

func (v *Vulnerability) Description() string

Description returns the description.

func (*Vulnerability) EPSSPercentile

func (v *Vulnerability) EPSSPercentile() *float64

EPSSPercentile returns the EPSS percentile.

func (*Vulnerability) EPSSScore

func (v *Vulnerability) EPSSScore() *float64

EPSSScore returns the EPSS score.

func (*Vulnerability) ExploitAvailable

func (v *Vulnerability) ExploitAvailable() bool

ExploitAvailable returns whether an exploit is available.

func (*Vulnerability) ExploitMaturity

func (v *Vulnerability) ExploitMaturity() ExploitMaturity

ExploitMaturity returns the exploit maturity.

func (*Vulnerability) FixedVersions

func (v *Vulnerability) FixedVersions() []string

FixedVersions returns a copy of the fixed versions.

func (*Vulnerability) HasExploit

func (v *Vulnerability) HasExploit() bool

HasExploit checks if an exploit exists.

func (*Vulnerability) ID

func (v *Vulnerability) ID() shared.ID

ID returns the vulnerability ID.

func (*Vulnerability) IsCritical

func (v *Vulnerability) IsCritical() bool

IsCritical checks if the vulnerability is critical.

func (*Vulnerability) IsHighOrCritical

func (v *Vulnerability) IsHighOrCritical() bool

IsHighOrCritical checks if the vulnerability is high or critical.

func (*Vulnerability) IsInCISAKEV

func (v *Vulnerability) IsInCISAKEV() bool

IsInCISAKEV checks if the vulnerability is in CISA KEV.

func (*Vulnerability) IsKEVPastDue

func (v *Vulnerability) IsKEVPastDue() bool

IsKEVPastDue checks if the CISA KEV due date has passed.

func (*Vulnerability) ModifiedAt

func (v *Vulnerability) ModifiedAt() *time.Time

ModifiedAt returns the modified date.

func (*Vulnerability) PublishedAt

func (v *Vulnerability) PublishedAt() *time.Time

PublishedAt returns the published date.

func (*Vulnerability) References

func (v *Vulnerability) References() []Reference

References returns a copy of the references.

func (*Vulnerability) Remediation

func (v *Vulnerability) Remediation() string

Remediation returns the remediation guidance.

func (*Vulnerability) RiskScore

func (v *Vulnerability) RiskScore() float64

RiskScore calculates a risk score based on various factors.

func (*Vulnerability) SetAffectedVersions

func (v *Vulnerability) SetAffectedVersions(versions []AffectedVersion)

SetAffectedVersions replaces all affected versions.

func (*Vulnerability) SetAliases

func (v *Vulnerability) SetAliases(aliases []string)

SetAliases replaces all aliases.

func (*Vulnerability) SetCISAKEV

func (v *Vulnerability) SetCISAKEV(kev *CISAKEV)

SetCISAKEV sets the CISA KEV data.

func (*Vulnerability) SetExploitAvailable

func (v *Vulnerability) SetExploitAvailable(available bool)

SetExploitAvailable sets whether an exploit is available.

func (*Vulnerability) SetExploitMaturity

func (v *Vulnerability) SetExploitMaturity(maturity ExploitMaturity)

SetExploitMaturity sets the exploit maturity.

func (*Vulnerability) SetFixedVersions

func (v *Vulnerability) SetFixedVersions(versions []string)

SetFixedVersions sets the fixed versions.

func (*Vulnerability) SetModifiedAt

func (v *Vulnerability) SetModifiedAt(t time.Time)

SetModifiedAt sets the modified date.

func (*Vulnerability) SetPublishedAt

func (v *Vulnerability) SetPublishedAt(t time.Time)

SetPublishedAt sets the published date.

func (*Vulnerability) SetReferences

func (v *Vulnerability) SetReferences(refs []Reference)

SetReferences replaces all references.

func (*Vulnerability) Severity

func (v *Vulnerability) Severity() Severity

Severity returns the severity.

func (*Vulnerability) Status

func (v *Vulnerability) Status() VulnerabilityStatus

Status returns the status.

func (*Vulnerability) Title

func (v *Vulnerability) Title() string

Title returns the title.

func (*Vulnerability) UpdateCVSS

func (v *Vulnerability) UpdateCVSS(score float64, vector string)

UpdateCVSS updates the CVSS score and vector.

func (*Vulnerability) UpdateDescription

func (v *Vulnerability) UpdateDescription(description string)

UpdateDescription updates the description.

func (*Vulnerability) UpdateEPSS

func (v *Vulnerability) UpdateEPSS(score, percentile float64)

UpdateEPSS updates the EPSS score and percentile.

func (*Vulnerability) UpdateRemediation

func (v *Vulnerability) UpdateRemediation(remediation string)

UpdateRemediation updates the remediation guidance.

func (*Vulnerability) UpdateSeverity

func (v *Vulnerability) UpdateSeverity(severity Severity) error

UpdateSeverity updates the severity.

func (*Vulnerability) UpdateStatus

func (v *Vulnerability) UpdateStatus(status VulnerabilityStatus) error

UpdateStatus updates the status.

func (*Vulnerability) UpdateTitle

func (v *Vulnerability) UpdateTitle(title string) error

UpdateTitle updates the title.

func (*Vulnerability) UpdatedAt

func (v *Vulnerability) UpdatedAt() time.Time

UpdatedAt returns the last update time.

type VulnerabilityFilter

type VulnerabilityFilter struct {
	CVEIDs           []string
	Severities       []Severity
	MinCVSS          *float64
	MaxCVSS          *float64
	MinEPSS          *float64
	ExploitAvailable *bool
	CISAKEVOnly      *bool
	Statuses         []VulnerabilityStatus
	Search           *string // Full-text search across CVE ID and description
}

VulnerabilityFilter defines criteria for filtering vulnerabilities.

func NewVulnerabilityFilter

func NewVulnerabilityFilter() VulnerabilityFilter

NewVulnerabilityFilter creates a new empty filter.

func (VulnerabilityFilter) IsEmpty

func (f VulnerabilityFilter) IsEmpty() bool

IsEmpty checks if no filters are applied.

func (VulnerabilityFilter) WithCISAKEVOnly

func (f VulnerabilityFilter) WithCISAKEVOnly(only bool) VulnerabilityFilter

WithCISAKEVOnly sets the CISA KEV only filter.

func (VulnerabilityFilter) WithCVEIDs

func (f VulnerabilityFilter) WithCVEIDs(cveIDs ...string) VulnerabilityFilter

WithCVEIDs sets the CVE IDs filter.

func (VulnerabilityFilter) WithExploitAvailable

func (f VulnerabilityFilter) WithExploitAvailable(available bool) VulnerabilityFilter

WithExploitAvailable sets the exploit available filter.

func (VulnerabilityFilter) WithMaxCVSS

func (f VulnerabilityFilter) WithMaxCVSS(score float64) VulnerabilityFilter

WithMaxCVSS sets the maximum CVSS filter.

func (VulnerabilityFilter) WithMinCVSS

func (f VulnerabilityFilter) WithMinCVSS(score float64) VulnerabilityFilter

WithMinCVSS sets the minimum CVSS filter.

func (VulnerabilityFilter) WithMinEPSS

func (f VulnerabilityFilter) WithMinEPSS(score float64) VulnerabilityFilter

WithMinEPSS sets the minimum EPSS filter.

func (VulnerabilityFilter) WithSearch

func (f VulnerabilityFilter) WithSearch(search string) VulnerabilityFilter

WithSearch sets the full-text search filter.

func (VulnerabilityFilter) WithSeverities

func (f VulnerabilityFilter) WithSeverities(severities ...Severity) VulnerabilityFilter

WithSeverities sets the severities filter.

func (VulnerabilityFilter) WithStatuses

func (f VulnerabilityFilter) WithStatuses(statuses ...VulnerabilityStatus) VulnerabilityFilter

WithStatuses sets the statuses filter.

type VulnerabilityListOptions

type VulnerabilityListOptions struct {
	Sort *pagination.SortOption
}

VulnerabilityListOptions contains options for listing vulnerabilities (sorting).

func NewVulnerabilityListOptions

func NewVulnerabilityListOptions() VulnerabilityListOptions

NewVulnerabilityListOptions creates empty list options.

func (VulnerabilityListOptions) WithSort

WithSort adds sorting options.

type VulnerabilityRepository

type VulnerabilityRepository interface {
	// Create persists a new vulnerability.
	Create(ctx context.Context, vuln *Vulnerability) error

	// GetByID retrieves a vulnerability by ID.
	GetByID(ctx context.Context, id shared.ID) (*Vulnerability, error)

	// GetByCVE retrieves a vulnerability by CVE ID.
	GetByCVE(ctx context.Context, cveID string) (*Vulnerability, error)

	// Update updates an existing vulnerability.
	Update(ctx context.Context, vuln *Vulnerability) error

	// Delete removes a vulnerability by ID.
	Delete(ctx context.Context, id shared.ID) error

	// List retrieves vulnerabilities matching the filter with pagination and sorting.
	List(ctx context.Context, filter VulnerabilityFilter, opts VulnerabilityListOptions, page pagination.Pagination) (pagination.Result[*Vulnerability], error)

	// Count returns the count of vulnerabilities matching the filter.
	Count(ctx context.Context, filter VulnerabilityFilter) (int64, error)

	// UpsertByCVE creates or updates a vulnerability by CVE ID.
	UpsertByCVE(ctx context.Context, vuln *Vulnerability) error

	// ExistsByCVE checks if a vulnerability with the given CVE ID exists.
	ExistsByCVE(ctx context.Context, cveID string) (bool, error)
}

VulnerabilityRepository defines the interface for vulnerability persistence.

type VulnerabilityStatus

type VulnerabilityStatus string

VulnerabilityStatus represents the status of a vulnerability.

const (
	VulnerabilityStatusOpen        VulnerabilityStatus = "open"
	VulnerabilityStatusPatched     VulnerabilityStatus = "patched"
	VulnerabilityStatusMitigated   VulnerabilityStatus = "mitigated"
	VulnerabilityStatusNotAffected VulnerabilityStatus = "not_affected"
)

func (VulnerabilityStatus) IsValid

func (v VulnerabilityStatus) IsValid() bool

IsValid checks if the vulnerability status is valid.

func (VulnerabilityStatus) String

func (v VulnerabilityStatus) String() string

String returns the string representation.

type Web3Details

type Web3Details struct {
	Chain             string `json:"chain,omitempty"`              // ethereum, polygon, bsc, arbitrum, solana
	ChainID           int64  `json:"chain_id,omitempty"`           // EVM chain ID: 1, 137, 56
	ContractAddress   string `json:"contract_address,omitempty"`   // 0x-prefixed address (42 chars for EVM)
	SWCID             string `json:"swc_id,omitempty"`             // SWC-101, SWC-107, etc.
	FunctionSignature string `json:"function_signature,omitempty"` // transfer(address,uint256)
	FunctionSelector  string `json:"function_selector,omitempty"`  // 4-byte selector: 0xa9059cbb
	TxHash            string `json:"tx_hash,omitempty"`            // Transaction hash if specific tx
	BlockNumber       int64  `json:"block_number,omitempty"`       // Block number if specific block
}

Web3Details contains details specific to Web3/blockchain findings.

type Web3FingerprintStrategy

type Web3FingerprintStrategy struct{}

Web3FingerprintStrategy generates fingerprints for blockchain/smart contract findings. Focuses on: chain, contract address, SWC ID, and function selector.

func (*Web3FingerprintStrategy) Generate

func (s *Web3FingerprintStrategy) Generate(f *Finding) string

func (*Web3FingerprintStrategy) Name

func (s *Web3FingerprintStrategy) Name() string

Jump to

Keyboard shortcuts

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