finding

package
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: Sep 30, 2026 License: GPL-3.0 Imports: 35 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package finding implements the application service for the finding bounded context — orchestrates pkg/domain/finding entities and cross-cutting concerns (audit, notifications, RBAC).

Index

Constants

View Source
const (
	DefaultDryRunCap        = 1000
	DefaultDryRunSampleSize = 25
)

Default caps for a priority-rule dry run. Evaluation is bounded to the most recent open findings so a large tenant can't turn a preview into an unbounded scan; the sample returned to the UI is bounded separately.

View Source
const AITriageFPThreshold = 0.8

AITriageFPThreshold is the false-positive-likelihood at or above which a COMPLETED AI triage verdict is treated as a high-confidence "likely false positive" and is allowed to DE-ESCALATE a finding's priority by one bounded level. Below it, the AI signal has no effect (fail-safe). It is derived from the real aitriage.TriageResult.FalsePositiveLikelihood field (0-1) — the only confidence signal the triage entity persists.

View Source
const MaxImportFindings = 5000

MaxImportFindings caps how many findings a single import may create. The 50MB upload limit alone allows a file with a very large number of tiny issues/rows, each becoming a synchronous DB insert — a connection-pool exhaustion DoS. Reject oversized imports up front.

Variables

View Source
var ErrBulkBudgetExceeded = errors.New("bulk operation budget exceeded for this hour")

ErrBulkBudgetExceeded is returned when the rolling-hour budget is exhausted for the tenant.

View Source
var ErrBulkNegativeSize = errors.New("bulk request size must be positive")

ErrBulkNegativeSize defends against callers passing a computed size that went negative (overflow bugs, bad filters).

View Source
var ErrBulkTooLarge = errors.New("bulk request exceeds size ceiling; requires operator approval")

ErrBulkTooLarge is returned when a single request exceeds the per-request ceiling without operator approval.

View Source
var ErrPriorityFloodSuppressed = errors.New("tenant priority flood budget exceeded; downstream fan-out suppressed")

ErrPriorityFloodSuppressed is returned by ShouldFanOut when the tenant has already consumed its rolling budget. Classification is NOT reverted; only downstream side effects are skipped.

Functions

This section is empty.

Types

type AIFalsePositiveVerdict added in v0.6.0

type AIFalsePositiveVerdict struct {
	Likely     bool
	Likelihood float64
}

AIFalsePositiveVerdict is the minimal, SAFE AI-triage signal the priority classifier consumes. Likely is true only for a high-confidence false-positive verdict (FalsePositiveLikelihood >= AITriageFPThreshold on a completed triage); Likelihood carries the raw 0-1 value for the audit reason. The zero value (Likely == false) means "no verdict / low confidence" → no effect.

type AITriageVerdictLookup added in v0.6.0

type AITriageVerdictLookup interface {
	GetFalsePositiveVerdicts(ctx context.Context, tenantID shared.ID, findingIDs []shared.ID) (map[shared.ID]AIFalsePositiveVerdict, error)
}

AITriageVerdictLookup batch-loads the latest AI-triage false-positive verdict per finding, tenant-scoped, in ONE query — so the batch classify path stays free of N+1. It returns entries only for findings that carry a high-confidence verdict; a nil lookup, an error, or a missing/low-confidence verdict all yield "no verdict", which (because AI may only lower priority, and only on a high-confidence verdict) means no effect.

type AddCommentInput

type AddCommentInput struct {
	TenantID  string `validate:"required,uuid"`
	FindingID string `validate:"required,uuid"`
	AuthorID  string `validate:"required,uuid"`
	Content   string `validate:"required,min=1,max=10000"`
}

AddCommentInput represents the input for adding a comment.

type AddEvidenceInput added in v0.4.0

type AddEvidenceInput struct {
	FindingID   string
	TenantID    string
	UserID      string
	Description string
	Type        string
	URL         string
}

AddEvidenceInput is the input for attaching a note-type evidence to a finding.

type AddStatusChangeCommentInput

type AddStatusChangeCommentInput struct {
	TenantID  string `validate:"required,uuid"`
	FindingID string `validate:"required,uuid"`
	AuthorID  string `validate:"required,uuid"`
	Content   string `validate:"max=10000"`
	OldStatus string `validate:"required,finding_status"`
	NewStatus string `validate:"required,finding_status"`
}

AddStatusChangeCommentInput represents the input for adding a status change comment.

type ApproveStatusInput

type ApproveStatusInput struct {
	TenantID   string `json:"tenant_id" validate:"required,uuid"`
	ApprovalID string `json:"approval_id" validate:"required,uuid"`
	ApprovedBy string `json:"approved_by" validate:"required,uuid"`
}

ApproveStatusInput represents the input for approving a status change.

type AssetBusinessContext added in v0.6.0

type AssetBusinessContext = asset.BusinessContext

AssetBusinessContext is the business-unit / business-service criticality that can RAISE an asset's effective criticality above its own. It aliases the shared domain type so this package and internal/app/asset resolve effective criticality through the SAME rule (asset.EffectiveCriticality) without a dependency cycle. Kept as a local name so the BusinessContextLookup interface and its postgres adapter read in finding terms.

type AssetOwnerLookup added in v0.6.0

type AssetOwnerLookup interface {
	// HasOwnerByAssetIDs returns, keyed by asset ID, true for each asset that has
	// at least one assigned owner. Assets with no owner may be absent from the
	// map (a missing key is read as "no owner"). Tenant-scoped in ONE query.
	HasOwnerByAssetIDs(ctx context.Context, tenantID shared.ID, assetIDs []shared.ID) (map[shared.ID]bool, error)
}

AssetOwnerLookup reports, per asset, whether the asset has an assigned owner (a user or group in asset_owners). It is tenant-scoped and batch-first so the classification hot path (EnrichAndClassifyBatch + the reclassify sweep) never issues a per-finding query — mirroring BusinessContextLookup.

It backs the CTEM "ownership unknown defaults to P2 minimum" rule: a finding on an unowned asset is floored at P2 (see vulnerability.applyOwnershipFloor). Optional — a nil lookup leaves classification unchanged (never a floor), so a deployment without the lookup wired behaves exactly as before.

type AutoAssignToOwnersResult

type AutoAssignToOwnersResult struct {
	Assigned   int            `json:"assigned"`
	ByOwner    map[string]int `json:"by_owner"`
	Unassigned int            `json:"unassigned"`
}

AutoAssignToOwnersResult is the result of auto-assign operation.

type AutoValidator added in v0.4.0

type AutoValidator interface {
	ValidateFinding(ctx context.Context, tenantID, findingID shared.ID) (shared.ID, error)
}

AutoValidator dispatches a CTEM Stage-4 safe-check re-check for a finding and returns the command ID it was queued under. Implemented by *validation.RunService. When wired, marking findings fix_applied auto-queues a proof-of-fix re-check so a "fixed" claim is verified rather than trusted.

type BulkAssignInput

type BulkAssignInput struct {
	FindingIDs []string
	UserID     string
	AssignerID string
}

BulkAssignInput represents input for bulk assignment.

type BulkFixAppliedInput

type BulkFixAppliedInput struct {
	Filter             vulnerability.FindingFilter
	IncludeRelatedCVEs bool
	Note               string // REQUIRED
	Reference          string // optional (commit hash, patch ID)
}

BulkFixAppliedInput is the input for bulk fix-applied operation.

type BulkFixAppliedResult

type BulkFixAppliedResult struct {
	Updated           int            `json:"updated"`
	Skipped           int            `json:"skipped"` // not permitted / invalid transition (expected)
	Failed            int            `json:"failed"`  // persistence error — retry-worthy, distinct from Skipped
	ByCVE             map[string]int `json:"by_cve,omitempty"`
	AssetsAffected    int            `json:"assets_affected"`
	ValidationsQueued int            `json:"validations_queued"` // proof-of-fix safe-check re-checks auto-dispatched
}

BulkFixAppliedResult is the result of bulk fix-applied operation.

type BulkGuard

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

BulkGuard is the single service used by all bulk handlers before executing. Usage:

if err := guard.CheckBulk(tenantID, len(findingIDs), operatorApproved); err != nil {
    return apierror.BadRequest(err.Error()).WriteJSON(w)
}

func NewBulkGuard

func NewBulkGuard(cfg BulkGuardConfig) *BulkGuard

NewBulkGuard constructs a guard with defaults applied.

func (*BulkGuard) CheckBulk

func (g *BulkGuard) CheckBulk(ctx context.Context, tenantID shared.ID, size int, operatorApproved bool) error

CheckBulk enforces both guards for a single request. On success, records the usage so subsequent calls see it. On rejection, usage is NOT recorded (the operation didn't happen).

The operator-approved flag bypasses SizeCeiling but NOT the hourly budget — even an approved operator cannot blast the tenant.

func (*BulkGuard) UsageThisHour

func (g *BulkGuard) UsageThisHour(tenantID shared.ID) int

UsageThisHour returns the number of rows consumed in the rolling hour window for `tenantID`. Exposed for the maturity dashboard.

type BulkGuardConfig

type BulkGuardConfig struct {
	// SizeCeiling is the max number of rows a single bulk request
	// can touch without operator approval. Default 500.
	SizeCeiling int
	// HourlyBudget is the max rows per tenant per hour. Default 10_000.
	HourlyBudget int
	// Now is injectable for deterministic tests.
	Now func() time.Time
}

BulkGuardConfig tunes the two thresholds. Zero values take the documented defaults.

type BulkUpdateResult

type BulkUpdateResult struct {
	Updated int
	Failed  int
	Errors  []string
}

BulkUpdateResult represents the result of a bulk operation.

type BulkUpdateStatusInput

type BulkUpdateStatusInput struct {
	FindingIDs          []string
	Status              string
	Resolution          string
	ActorID             string // User performing the bulk update
	HasVerifyPermission bool   // True if user has findings:verify (direct-resolve guard, mirrors single path)
}

BulkUpdateStatusInput represents input for bulk status update.

type BurpIssue

type BurpIssue struct {
	XMLName           xml.Name `xml:"issue"`
	SerialNumber      string   `xml:"serialNumber"`
	Type              string   `xml:"type"`
	Name              string   `xml:"name"`
	Host              string   `xml:"host"`
	Path              string   `xml:"path"`
	Location          string   `xml:"location"`
	Severity          string   `xml:"severity"`
	Confidence        string   `xml:"confidence"`
	IssueBackground   string   `xml:"issueBackground"`
	RemediationBG     string   `xml:"remediationBackground"`
	IssueDetail       string   `xml:"issueDetail"`
	RemediationDetail string   `xml:"remediationDetail"`
	RequestResponse   []struct {
		Request  string `xml:"request"`
		Response string `xml:"response"`
	} `xml:"requestresponse"`
}

BurpIssue represents a single issue in Burp Suite XML export.

type BurpIssues

type BurpIssues struct {
	XMLName xml.Name    `xml:"issues"`
	Issues  []BurpIssue `xml:"issue"`
}

BurpIssues is the root XML element.

type BusinessContextLookup added in v0.6.0

type BusinessContextLookup interface {
	// GetForAssets returns the business context for the given assets, keyed by
	// asset ID. Assets with no BU / service membership may be absent from the
	// map (treated as the zero AssetBusinessContext).
	GetForAssets(ctx context.Context, tenantID shared.ID, assetIDs []shared.ID) (map[shared.ID]AssetBusinessContext, error)
}

BusinessContextLookup resolves, per asset, the business-unit and business-service criticality used to compute effective (business-aligned) criticality. It is tenant-scoped and batch-first so the classification hot path (EnrichAndClassifyBatch + the reclassify sweep) never issues a per-finding query. Optional — a nil lookup leaves classification on each asset's OWN criticality (never a downgrade).

type CachedCategory

type CachedCategory struct {
	ID           string `json:"id"`
	Code         string `json:"code"`
	Name         string `json:"name"`
	Description  string `json:"description,omitempty"`
	Icon         string `json:"icon,omitempty"`
	DisplayOrder int    `json:"display_order"`
}

CachedCategory represents a category in the cache.

type CachedFindingSource

type CachedFindingSource struct {
	ID           string `json:"id"`
	Code         string `json:"code"`
	Name         string `json:"name"`
	Description  string `json:"description,omitempty"`
	CategoryID   string `json:"category_id,omitempty"`
	CategoryCode string `json:"category_code,omitempty"`
	CategoryName string `json:"category_name,omitempty"`
	Icon         string `json:"icon,omitempty"`
	Color        string `json:"color,omitempty"`
	DisplayOrder int    `json:"display_order"`
	IsSystem     bool   `json:"is_system"`
}

CachedFindingSource represents a finding source in the cache.

type CachedFindingSources

type CachedFindingSources struct {
	Sources    []*CachedFindingSource `json:"sources"`
	Categories []*CachedCategory      `json:"categories"`
	ByCode     map[string]int         `json:"by_code"`     // code -> index in Sources for O(1) lookup
	ByCategory map[string][]int       `json:"by_category"` // category_code -> indices in Sources
	CachedAt   time.Time              `json:"cached_at"`
}

CachedFindingSources represents the cached finding source data.

type CancelApprovalInput

type CancelApprovalInput struct {
	TenantID   string `json:"tenant_id" validate:"required,uuid"`
	ApprovalID string `json:"approval_id" validate:"required,uuid"`
	CanceledBy string `json:"canceled_by" validate:"required,uuid"`
}

CancelApprovalInput represents the input for cancelling a status change request.

type ClassifyFindingInput

type ClassifyFindingInput struct {
	CVEID      string
	CVSSScore  *float64
	CVSSVector string
	CWEIDs     []string
	OWASPIDs   []string
}

ClassifyFindingInput represents input for classification.

type CompensatingControlLookup

type CompensatingControlLookup interface {
	// GetEffectiveForAssets returns max reduction_factor per asset with active+effective controls.
	// Returns map[assetID]reductionFactor (0.0-1.0).
	GetEffectiveForAssets(ctx context.Context, tenantID shared.ID, assetIDs []shared.ID) (map[shared.ID]float64, error)
}

CompensatingControlLookup provides lookups for effective controls on assets/findings.

type CreateFindingInput

type CreateFindingInput struct {
	TenantID        string `validate:"required,uuid"`
	AssetID         string `validate:"required,uuid"`
	BranchID        string `validate:"omitempty,uuid"`
	VulnerabilityID string `validate:"omitempty,uuid"`
	ComponentID     string `validate:"omitempty,uuid"`
	Source          string `validate:"required,finding_source"`
	ToolName        string `validate:"required,max=100"`
	ToolVersion     string `validate:"max=50"`
	RuleID          string `validate:"max=255"`
	FilePath        string `validate:"max=500"`
	StartLine       int    `validate:"min=0"`
	EndLine         int    `validate:"min=0"`
	StartColumn     int    `validate:"min=0"`
	EndColumn       int    `validate:"min=0"`
	Snippet         string `validate:"max=5000"`
	Message         string `validate:"required,max=2000"`
	Severity        string `validate:"required,severity"`
	ScanID          string `validate:"max=100"`
}

CreateFindingInput represents the input for creating a finding.

type CreateVulnerabilityInput

type CreateVulnerabilityInput struct {
	CVEID            string   `validate:"required,cve_id"`
	Title            string   `validate:"required,min=1,max=500"`
	Description      string   `validate:"max=10000"`
	Severity         string   `validate:"required,severity"`
	CVSSScore        *float64 `validate:"omitempty,min=0,max=10"`
	CVSSVector       string   `validate:"max=100"`
	EPSSScore        *float64 `validate:"omitempty,min=0,max=1"`
	EPSSPercentile   *float64 `validate:"omitempty,min=0,max=100"` // 0-100; a 0-1 fraction is also accepted and rescaled (vulnerability.NormalizeEPSSPercentile)
	ExploitAvailable bool
	ExploitMaturity  string   `validate:"omitempty,exploit_maturity"`
	FixedVersions    []string `validate:"max=50,dive,max=100"`
	Remediation      string   `validate:"max=5000"`
}

CreateVulnerabilityInput represents the input for creating a vulnerability.

type DataScopePolicy

type DataScopePolicy interface {
	RestrictedDataScope(ctx context.Context, tenantID string) bool
}

DataScopePolicy reports whether a tenant enforces restricted (fail-closed) data scope. A nil policy (or a false result) preserves the default fail-open behavior. Implemented at the composition root over the tenant settings.

type DryRunResult added in v0.6.0

type DryRunResult struct {
	Evaluated    int            // findings actually evaluated (asset-backed, non-override)
	Matched      int            // how many the draft rule matched
	Capped       bool           // true when more open findings exist than were evaluated
	Cap          int            // the evaluation cap applied
	Sample       []DryRunSample // a bounded preview of matched findings
	Distribution map[string]int // would-be priority-class histogram (P0..P3)
}

DryRunResult is the outcome of evaluating a DRAFT priority rule against the tenant's open findings with the REAL classification engine. It is purely informational — nothing is mutated or persisted.

type DryRunSample added in v0.6.0

type DryRunSample struct {
	FindingID    string
	Title        string
	Severity     string
	CurrentClass string
	WouldBeClass string
}

DryRunSample previews a single matched finding in a dry-run result.

type EPSSData

type EPSSData struct {
	Score      float64 // probability, 0-1
	Percentile float64 // rank, canonical 0-100 (epss_scores.percentile)
}

EPSSData holds EPSS score for a CVE.

type EPSSRepository

type EPSSRepository interface {
	GetByCVEIDs(ctx context.Context, cveIDs []string) (map[string]EPSSData, error)
}

EPSSRepository provides EPSS score lookups.

type EvidenceStore added in v0.4.0

type EvidenceStore interface {
	Upload(ctx context.Context, input integration.UploadInput) (*attachmentdom.Attachment, error)
	ListByContext(ctx context.Context, tenantID shared.ID, contextType, contextID string) ([]*attachmentdom.Attachment, error)
	Download(ctx context.Context, tenantID, attachmentID string) (io.ReadCloser, string, string, error)
	Delete(ctx context.Context, tenantID, attachmentID string) error
}

EvidenceStore is the subset of the attachment service the finding-evidence endpoints depend on. Implemented by *integration.AttachmentService. Declared as an interface so the service is unit-testable without real file storage.

type FindingActionsService

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

FindingActionsService handles the closed-loop finding lifecycle: in_progress → fix_applied → resolved (verified by scan or security).

func NewFindingActionsService

func NewFindingActionsService(
	findingRepo vulnerability.FindingRepository,
	accessCtrlRepo accesscontrol.Repository,
	groupRepo group.Repository,
	assetRepo asset.Repository,
	activityService *activity.FindingActivityService,
	db *sql.DB,
	logger *logger.Logger,
) *FindingActionsService

NewFindingActionsService creates a new FindingActionsService.

func (*FindingActionsService) AutoAssignToOwners

func (s *FindingActionsService) AutoAssignToOwners(
	ctx context.Context, tenantID string, assignerID string, filter vulnerability.FindingFilter,
) (*AutoAssignToOwnersResult, error)

AutoAssignToOwners assigns findings to their asset owners. Only assigns findings that don't already have an assignee.

func (*FindingActionsService) BulkFixApplied

func (s *FindingActionsService) BulkFixApplied(
	ctx context.Context, tenantID string, userID string, input BulkFixAppliedInput,
) (*BulkFixAppliedResult, error)

BulkFixApplied marks findings as fix_applied. Authorization: user must be assignee, group member, or asset owner for each finding.

func (*FindingActionsService) BulkRejectByFilter

func (s *FindingActionsService) BulkRejectByFilter(
	ctx context.Context, tenantID string, userID string, input RejectByFilterInput,
) (int64, error)

BulkRejectByFilter reopens all fix_applied findings matching a filter.

func (*FindingActionsService) BulkRejectFix

func (s *FindingActionsService) BulkRejectFix(
	ctx context.Context, tenantID string, userID string, findingIDs []string, reason string,
) (*BulkUpdateResult, error)

BulkRejectFix reopens fix_applied findings (fix was incorrect).

func (*FindingActionsService) BulkVerify

func (s *FindingActionsService) BulkVerify(
	ctx context.Context, tenantID string, userID string, findingIDs []string, note string,
) (*BulkUpdateResult, error)

BulkVerify resolves fix_applied findings (manual security review).

func (*FindingActionsService) BulkVerifyByFilter

func (s *FindingActionsService) BulkVerifyByFilter(
	ctx context.Context, tenantID string, userID string, input VerifyByFilterInput,
) (int64, error)

BulkVerifyByFilter resolves all fix_applied findings matching a filter. Used by Pending Review tab to approve entire groups at once.

func (*FindingActionsService) GetRelatedCVEs

func (s *FindingActionsService) GetRelatedCVEs(
	ctx context.Context, tenantID string, cveID string, filter vulnerability.FindingFilter,
) ([]vulnerability.RelatedCVE, error)

GetRelatedCVEs finds CVEs that share the same component as the given CVE.

func (*FindingActionsService) ListFindingGroups

ListFindingGroups returns findings grouped by a dimension.

func (*FindingActionsService) RequestVerificationScan

func (s *FindingActionsService) RequestVerificationScan(
	ctx context.Context, tenantID, userID string, input RequestVerificationScanInput,
) (*RequestVerificationScanResult, error)

RequestVerificationScan triggers a targeted quick scan on the asset associated with a finding. The finding must be in fix_applied status (dev has marked it as fixed; awaiting scan verification). The scan result is expected to either confirm the fix (→ resolved) or reveal the vuln still exists (→ back to in_progress) via the normal ingest pipeline.

func (*FindingActionsService) SetAutoValidator added in v0.4.0

func (s *FindingActionsService) SetAutoValidator(v AutoValidator)

SetAutoValidator wires the proof-of-fix auto-validator. When set, a successful fix_applied transition auto-queues a safe-check re-check per finding (bounded, best-effort). Optional: nil → no auto-validation (prior behavior).

func (*FindingActionsService) SetVerificationScanTrigger

func (s *FindingActionsService) SetVerificationScanTrigger(trigger VerificationScanTrigger)

SetVerificationScanTrigger wires the scan trigger (called after both services are initialized).

type FindingCommentService

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

FindingCommentService handles finding comment operations.

func NewFindingCommentService

func NewFindingCommentService(
	commentRepo vulnerability.FindingCommentRepository,
	findingRepo vulnerability.FindingRepository,
	log *logger.Logger,
) *FindingCommentService

NewFindingCommentService creates a new FindingCommentService.

func (*FindingCommentService) AddComment

AddComment adds a new comment to a finding.

func (*FindingCommentService) AddStatusChangeComment

AddStatusChangeComment adds a comment recording a status change.

func (*FindingCommentService) CountFindingComments

func (s *FindingCommentService) CountFindingComments(ctx context.Context, findingID string) (int, error)

CountFindingComments counts comments for a finding.

func (*FindingCommentService) DeleteComment

func (s *FindingCommentService) DeleteComment(ctx context.Context, tenantID, commentID, authorID string) error

DeleteComment deletes a comment. tenantID is required so the storage-layer WHERE clause rejects cross-tenant IDs (IDOR defense).

func (*FindingCommentService) GetComment

func (s *FindingCommentService) GetComment(ctx context.Context, commentID string) (*vulnerability.FindingComment, error)

GetComment retrieves a comment by ID.

func (*FindingCommentService) ListFindingComments

func (s *FindingCommentService) ListFindingComments(ctx context.Context, findingID string) ([]*vulnerability.FindingComment, error)

ListFindingComments retrieves all comments for a finding.

func (*FindingCommentService) UpdateComment

func (s *FindingCommentService) UpdateComment(ctx context.Context, tenantID, commentID, authorID string, input UpdateCommentInput) (*vulnerability.FindingComment, error)

UpdateComment updates an existing comment. tenantID scopes the lookup — user in tenant A cannot resolve a comment id from tenant B even if they guess the UUID.

type FindingEvidence added in v0.4.0

type FindingEvidence struct {
	ID          string    `json:"id"`
	Kind        string    `json:"kind"` // "note" | "file"
	Description string    `json:"description,omitempty"`
	Type        string    `json:"type,omitempty"`
	URL         string    `json:"url,omitempty"`
	Filename    string    `json:"filename,omitempty"`
	ContentType string    `json:"content_type,omitempty"`
	Size        int64     `json:"size,omitempty"`
	DownloadURL string    `json:"download_url,omitempty"`
	CreatedAt   time.Time `json:"created_at"`
	UploadedBy  string    `json:"uploaded_by,omitempty"`
	// UploadedByName is the resolved display name (or email) of the uploader.
	// Best-effort enrichment — left empty when the user cannot be resolved; the
	// UploadedBy UUID is always present for compatibility.
	UploadedByName string `json:"uploaded_by_name,omitempty"`
}

FindingEvidence is the API-facing view of a piece of evidence attached to a finding. A "note" carries a description/type/url; a "file" carries the attachment metadata and a download URL.

type FindingImportService

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

FindingImportService handles importing findings from external scanner formats.

func NewFindingImportService

func NewFindingImportService(repo vulnerability.FindingRepository, log *logger.Logger) *FindingImportService

NewFindingImportService creates a new import service.

func (*FindingImportService) ImportBurpXML

func (s *FindingImportService) ImportBurpXML(ctx context.Context, tenantID, campaignID string, reader io.Reader) (*ImportResult, error)

ImportBurpXML parses Burp Suite XML and creates findings.

func (*FindingImportService) ImportCSV

func (s *FindingImportService) ImportCSV(ctx context.Context, tenantID, campaignID string, reader io.Reader) (*ImportResult, error)

ImportCSV parses CSV with headers and creates findings. Expected headers: title, severity, description, affected_assets, steps_to_reproduce, poc_code, business_impact, remediation

type FindingLifecycleScheduler

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

FindingLifecycleScheduler manages background tasks for finding lifecycle. This includes expiring findings on feature branches that have been inactive.

func NewFindingLifecycleScheduler

func NewFindingLifecycleScheduler(
	findingRepo vulnerability.FindingRepository,
	tenantLister TenantLister,
	cfg FindingLifecycleSchedulerConfig,
	log *logger.Logger,
) *FindingLifecycleScheduler

NewFindingLifecycleScheduler creates a new scheduler.

func (*FindingLifecycleScheduler) Start

func (s *FindingLifecycleScheduler) Start()

Start starts the scheduler.

func (*FindingLifecycleScheduler) Stop

func (s *FindingLifecycleScheduler) Stop()

Stop stops the scheduler gracefully. Safe to call even if Start() was never called (e.g. when Enabled=false).

type FindingLifecycleSchedulerConfig

type FindingLifecycleSchedulerConfig struct {
	// CheckInterval is how often to run lifecycle tasks (default: 1 hour)
	CheckInterval time.Duration

	// DefaultExpiryDays is the default number of days after which
	// feature branch findings are expired if not seen (default: 30)
	// Individual branches can override this via retention_days setting.
	DefaultExpiryDays int

	// Enabled controls whether the scheduler runs (default: true)
	Enabled bool
}

FindingLifecycleSchedulerConfig holds configuration for the scheduler.

func DefaultFindingLifecycleSchedulerConfig

func DefaultFindingLifecycleSchedulerConfig() FindingLifecycleSchedulerConfig

DefaultFindingLifecycleSchedulerConfig returns default configuration.

type FindingNotifier

type FindingNotifier interface {
	// NotifyNewFinding sends a notification for a new finding.
	// This should be called asynchronously to not block finding creation.
	NotifyNewFinding(tenantID, title, body, severity, url string)
}

FindingNotifier is an interface for sending finding notifications asynchronously. Deprecated: Use outbox.Service with transactional outbox pattern instead.

type FindingSourceCacheService

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

FindingSourceCacheService provides cached access to finding sources. Finding sources are system-level configuration that rarely changes, making them ideal candidates for aggressive caching.

Cache structure: - Key: "finding_sources:all" → CachedFindingSources (all sources with categories) - Key: "finding_sources:code:{code}" → single source (optional, for high-frequency lookups)

Cache invalidation: - Manual via InvalidateAll() when sources are modified (rare) - TTL-based expiration (24 hours)

This cache is GLOBAL (not per-tenant) because finding sources are system configuration.

func NewFindingSourceCacheService

func NewFindingSourceCacheService(
	redisClient *redis.Client,
	repo findingsource.Repository,
	log *logger.Logger,
) (*FindingSourceCacheService, error)

NewFindingSourceCacheService creates a new finding source cache service.

func (*FindingSourceCacheService) GetAll

GetAll returns all active finding sources with their categories (cached). This is the primary method for UI dropdowns and validation.

func (*FindingSourceCacheService) GetByCategory

func (s *FindingSourceCacheService) GetByCategory(ctx context.Context, categoryCode string) ([]*CachedFindingSource, error)

GetByCategory returns finding sources filtered by category code (from cache).

func (*FindingSourceCacheService) GetByCode

GetByCode returns a finding source by code (from cache). Returns nil if not found.

func (*FindingSourceCacheService) GetCategories

func (s *FindingSourceCacheService) GetCategories(ctx context.Context) ([]*CachedCategory, error)

GetCategories returns all active categories (from cache).

func (*FindingSourceCacheService) InvalidateAll

func (s *FindingSourceCacheService) InvalidateAll(ctx context.Context) error

InvalidateAll removes all cached finding source data. Call this when finding sources are modified (rare operation).

func (*FindingSourceCacheService) IsValidCode

func (s *FindingSourceCacheService) IsValidCode(ctx context.Context, code string) (bool, error)

IsValidCode checks if a code is a valid active finding source (from cache).

func (*FindingSourceCacheService) Refresh

Refresh forces a cache refresh by invalidating and reloading.

func (*FindingSourceCacheService) WarmCache

func (s *FindingSourceCacheService) WarmCache(ctx context.Context) error

WarmCache preloads the cache on startup. Call this during application initialization.

type FindingSourceService

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

FindingSourceService handles finding source-related business operations. Finding sources are read-only system configuration created via DB seed or by system admin.

func NewFindingSourceService

func NewFindingSourceService(repo findingsource.Repository, categoryRepo findingsource.CategoryRepository, log *logger.Logger) *FindingSourceService

NewFindingSourceService creates a new FindingSourceService.

func (*FindingSourceService) GetCategory

func (s *FindingSourceService) GetCategory(ctx context.Context, categoryID string) (*findingsource.Category, error)

GetCategory retrieves a category by ID.

func (*FindingSourceService) GetCategoryByCode

func (s *FindingSourceService) GetCategoryByCode(ctx context.Context, code string) (*findingsource.Category, error)

GetCategoryByCode retrieves a category by code.

func (*FindingSourceService) GetFindingSource

func (s *FindingSourceService) GetFindingSource(ctx context.Context, findingSourceID string) (*findingsource.FindingSource, error)

GetFindingSource retrieves a finding source by ID.

func (*FindingSourceService) GetFindingSourceByCode

func (s *FindingSourceService) GetFindingSourceByCode(ctx context.Context, code string) (*findingsource.FindingSource, error)

GetFindingSourceByCode retrieves a finding source by code.

func (*FindingSourceService) IsValidSourceCode

func (s *FindingSourceService) IsValidSourceCode(ctx context.Context, code string) (bool, error)

IsValidSourceCode checks if the code is a valid active finding source.

func (*FindingSourceService) ListActiveCategories

func (s *FindingSourceService) ListActiveCategories(ctx context.Context) ([]*findingsource.Category, error)

ListActiveCategories lists all active categories.

func (*FindingSourceService) ListActiveFindingSources

func (s *FindingSourceService) ListActiveFindingSources(ctx context.Context) ([]*findingsource.FindingSource, error)

ListActiveFindingSources lists all active finding sources.

func (*FindingSourceService) ListActiveFindingSourcesByCategory

func (s *FindingSourceService) ListActiveFindingSourcesByCategory(ctx context.Context, categoryID string) ([]*findingsource.FindingSource, error)

ListActiveFindingSourcesByCategory lists active finding sources by category.

func (*FindingSourceService) ListActiveFindingSourcesWithCategory

func (s *FindingSourceService) ListActiveFindingSourcesWithCategory(ctx context.Context) ([]*findingsource.FindingSourceWithCategory, error)

ListActiveFindingSourcesWithCategory lists all active finding sources with their categories.

func (*FindingSourceService) ListCategories

ListCategories lists categories with pagination.

func (*FindingSourceService) ListFindingSources

ListFindingSources lists finding sources with filtering and pagination.

func (*FindingSourceService) ListFindingSourcesWithCategory

ListFindingSourcesWithCategory lists finding sources with their categories.

type GetFindingStatsInput

type GetFindingStatsInput struct {
	TenantID     string
	ActingUserID string
	IsAdmin      bool
	// AssetID — when non-empty, restrict the stats to findings on this
	// specific asset. Used by /findings?assetId=… so the severity cards
	// match the filtered table.
	AssetID string
	// Sources — when non-empty, restrict the stats to findings with one of
	// these sources. Same validation as ListFindingsInput.Sources, so the
	// Exposures type pages can ask for the counts of exactly the rows their
	// table lists.
	Sources []string `validate:"max=25,dive,finding_source"`
}

GetFindingStatsInput represents input for getting finding stats with data scope.

type ImportResult

type ImportResult struct {
	Total    int      `json:"total"`
	Created  int      `json:"created"`
	Skipped  int      `json:"skipped"`
	Errors   int      `json:"errors"`
	Messages []string `json:"messages,omitempty"`
}

ImportResult contains the result of an import operation.

type KEVData

type KEVData struct {
	DueDate    *time.Time
	Ransomware string
}

KEVData holds KEV catalog info for a CVE.

type KEVRepository

type KEVRepository interface {
	GetByCVEIDs(ctx context.Context, cveIDs []string) (map[string]KEVData, error)
}

KEVRepository provides KEV catalog lookups.

type ListActiveCVEsInput added in v0.3.0

type ListActiveCVEsInput struct {
	TenantID         string
	IncludeResolved  bool
	SeverityIn       []string
	KEVOnly          bool
	MinCVSS          *float64
	MinEPSS          *float64
	ExploitAvailable *bool
	Page             int
	PerPage          int
}

ListActiveCVEsInput captures the query options for ListActiveCVEs.

type ListFindingsInput

type ListFindingsInput struct {
	TenantID        string   `validate:"required,uuid"`
	AssetID         string   `validate:"omitempty,uuid"`
	BranchID        string   `validate:"omitempty,uuid"`
	BranchStatus    string   `validate:"omitempty,oneof=all open fixed"`
	ComponentID     string   `validate:"omitempty,uuid"`
	VulnerabilityID string   `validate:"omitempty,uuid"`
	Severities      []string `validate:"max=5,dive,severity"`
	Statuses        []string `validate:"max=10,dive,finding_status"`
	ExcludeStatuses []string `validate:"max=10,dive,finding_status"`
	// max=25, not the max=5 its siblings use. Severity has five possible values
	// in total, so a cap of five means "any subset". Source has twenty-one, and
	// the UI filters by source *category* — selecting one group submits every
	// code in it. A cap of five would silently reject a group that grew past
	// five members, and the filter would come back with a validation error the
	// user cannot act on.
	Sources []string `validate:"max=25,dive,finding_source"`
	// SLAStatuses filters by SLA lifecycle status (comma-separated). The SLA
	// breach board sends sla_status=overdue,exceeded. Five possible values, so a
	// cap of five means "any subset"; unknown values are rejected by validation.
	SLAStatuses []string `validate:"max=5,dive,oneof=on_track warning overdue exceeded not_applicable"`
	// CTEM prioritization filters (RFC-017).
	PriorityClasses []string `validate:"max=4,dive,oneof=P0 P1 P2 P3"`
	IsInKEV         *bool
	EPSSMin         *float64 `validate:"omitempty,min=0,max=1"`
	IsReachable     *bool
	// FindingIDs restricts to a specific set of findings (e.g. a remediation
	// task's linked findings).
	FindingIDs []string `validate:"max=500,dive,uuid"`
	ToolName   string   `validate:"max=100"`
	RuleID     string   `validate:"max=255"`
	ScanID     string   `validate:"max=100"`
	FilePath   string   `validate:"max=500"`
	Search     string   `validate:"max=255"` // Full-text search across title, description, and file path
	Sort       string   `validate:"max=100"` // Sort field (e.g., "-severity", "created_at")
	Page       int      `validate:"min=0"`
	PerPage    int      `validate:"min=0,max=100"`

	// Layer 2: Data Scope
	ActingUserID string // From JWT context
	IsAdmin      bool   // True for owner/admin (bypasses data scope)

	// AssignedToMe restricts the list to findings "related to" the acting user —
	// assignee, asset owner, or member of an assigned group. Backs the
	// "Assigned to me" / My Work view. Applies to admins too (independent of the
	// data-scope narrowing above), and is a no-op without ActingUserID.
	AssignedToMe bool
}

ListFindingsInput represents the input for listing findings.

type ListVulnerabilitiesInput

type ListVulnerabilitiesInput struct {
	CVEIDs           []string `validate:"max=50,dive,max=20"`
	Severities       []string `validate:"max=5,dive,severity"`
	MinCVSS          *float64 `validate:"omitempty,min=0,max=10"`
	MaxCVSS          *float64 `validate:"omitempty,min=0,max=10"`
	MinEPSS          *float64 `validate:"omitempty,min=0,max=1"`
	ExploitAvailable *bool
	CISAKEVOnly      *bool
	Statuses         []string `validate:"max=5,dive,vulnerability_status"`
	Search           string   `validate:"max=255"` // Full-text search across CVE ID and description
	Sort             string   `validate:"max=100"` // Sort field (e.g., "-cvss_score", "cve_id")
	Page             int      `validate:"min=0"`
	PerPage          int      `validate:"min=0,max=100"`
}

ListVulnerabilitiesInput represents the input for listing vulnerabilities.

type OutboxEnqueuer added in v0.4.0

type OutboxEnqueuer interface {
	Enqueue(ctx context.Context, params outbox.EnqueueParams) error
}

OutboxEnqueuer is the slice of outbox.Service this publisher needs. Declared here (consumer side) so tests can substitute a fake without standing up the whole notification stack.

type OutboxPriorityChangePublisher added in v0.4.0

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

OutboxPriorityChangePublisher is the production PriorityChangePublisher: it turns a priority ESCALATION into a notification-outbox entry, which the outbox scheduler then fans out to the tenant's connected Slack/Teams/ Telegram/email/webhook integrations.

Why escalations only. PriorityChangeEvent is deliberately broader than what is worth paging a human about — it also fires on first classification (PreviousClass == nil) and on de-escalations:

  • First classification fires once per newly-ingested finding. Those are already announced by the "new_finding" notification, so publishing them here would double-notify every finding of every ingest batch.
  • A de-escalation (P0 -> P2, e.g. a compensating control was applied) is good news and does not need to interrupt anyone.

The escalation is the case the operator cannot afford to miss: a finding they already triaged as low-urgency silently became P0 because its CVE was added to KEV or its asset landed on a validated attack path.

Delivery severity is derived from the NEW class (P0 -> critical ... P3 -> low) so the tenant's existing per-integration severity filter keeps working without a new knob: an integration set to "critical only" receives P0 escalations and nothing else.

func NewOutboxPriorityChangePublisher added in v0.4.0

func NewOutboxPriorityChangePublisher(o OutboxEnqueuer, log *logger.Logger) *OutboxPriorityChangePublisher

NewOutboxPriorityChangePublisher wires the publisher to the notification outbox. A nil enqueuer yields a publisher whose Publish is a no-op, so the composition root can wire it unconditionally.

func (*OutboxPriorityChangePublisher) Publish added in v0.4.0

Publish implements PriorityChangePublisher.

type OwnershipFloorPolicy added in v0.6.0

type OwnershipFloorPolicy interface {
	// FloorUnownedAtP2 returns true when the tenant enabled the floor. Any error
	// or missing setting resolves to false (off) so a lookup failure never starts
	// silently re-prioritizing findings.
	FloorUnownedAtP2(ctx context.Context, tenantID shared.ID) bool
}

OwnershipFloorPolicy reports whether a tenant has opted into the CTEM "ownership unknown defaults to P2 minimum" floor. It is the toggle that keeps the floor from being a blanket, forced behavior change: the floor (and the owner-presence lookup that feeds it) runs ONLY for tenants that turned it on. Optional — a nil policy is read as "off" for every tenant (fail-safe: no floor, no owner lookup, no cost).

type PriorityAuditEntry

type PriorityAuditEntry struct {
	TenantID      shared.ID
	FindingID     shared.ID
	PreviousClass *vulnerability.PriorityClass
	NewClass      vulnerability.PriorityClass
	Reason        string
	Source        string // "auto", "rule", "manual"
	RuleID        *shared.ID
	ActorID       *shared.ID
}

PriorityAuditEntry represents a priority change log entry.

type PriorityAuditRepository

type PriorityAuditRepository interface {
	LogChange(ctx context.Context, entry PriorityAuditEntry) error
}

PriorityAuditRepository records priority changes.

type PriorityChangeEvent

type PriorityChangeEvent struct {
	TenantID      shared.ID
	FindingID     shared.ID
	PreviousClass *vulnerability.PriorityClass // nil for first classification
	NewClass      vulnerability.PriorityClass
	Reason        string
	Source        string // "auto" | "rule" | "sweep" | "manual"
	RuleID        *shared.ID
	At            time.Time
}

PriorityChangeEvent is emitted whenever a finding's priority class transitions to a new value. Downstream consumers (notification service, assignment-rule service, dashboard live feed) subscribe via the outbox.

(F3, B1, B2): emission is the mechanism that wires the reclassification sweep to the rest of the system. Without this event, a priority change is a silent dashboard update — an operator can miss that a P3 just became P0.

type PriorityChangePublisher

type PriorityChangePublisher interface {
	Publish(ctx context.Context, event PriorityChangeEvent) error
}

PriorityChangePublisher delivers priority-change events to downstream consumers, typically by inserting into the notification outbox. Optional — when nil, classification still runs but no event is fired.

type PriorityClassificationService

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

PriorityClassificationService orchestrates finding priority classification. It enriches findings with EPSS/KEV data, evaluates override rules, and applies the default CTEM classification logic.

func NewPriorityClassificationService

func NewPriorityClassificationService(
	findingRepo vulnerability.FindingRepository,
	assetRepo asset.Repository,
	epssRepo EPSSRepository,
	kevRepo KEVRepository,
	ruleRepo PriorityRuleRepository,
	auditRepo PriorityAuditRepository,
	log *logger.Logger,
) *PriorityClassificationService

NewPriorityClassificationService creates a new service.

func (*PriorityClassificationService) ClassifyFinding

func (s *PriorityClassificationService) ClassifyFinding(
	ctx context.Context,
	tenantID shared.ID,
	finding *vulnerability.Finding,
	assetEntity *asset.Asset,
) error

ClassifyFinding computes priority for a single finding.

(O1 invariant): emits ctem_stage_* metrics so dashboards and alert rules have real numbers for the Prioritization stage. Skipped on manual overrides — those bypass the stage entirely.

func (*PriorityClassificationService) DryRunRule added in v0.6.0

func (s *PriorityClassificationService) DryRunRule(
	ctx context.Context,
	tenantID shared.ID,
	draft *vulnerability.PriorityOverrideRule,
	cap int,
	sampleSize int,
) (DryRunResult, error)

DryRunRule evaluates a DRAFT (possibly unsaved) priority override rule against the tenant's OPEN findings (new/confirmed/in_progress/fix_applied) using the SAME enrichment + engine the classifier uses, and returns exact match counts, a would-be class distribution, and a bounded sample of matched findings.

It is strictly READ-ONLY: findings are enriched in memory via enrichAndContextualize (never persisted) and no rule is stored. Evaluation is capped at the `cap` most-recent open findings (a non-positive cap falls back to DefaultDryRunCap); when the tenant has more open findings than the cap, the result's Capped flag is set. sampleSize (non-positive → DefaultDryRunSampleSize) bounds the returned sample.

func (*PriorityClassificationService) EnrichAndClassifyBatch

func (s *PriorityClassificationService) EnrichAndClassifyBatch(
	ctx context.Context,
	tenantID shared.ID,
	findings []*vulnerability.Finding,
	assets map[shared.ID]*asset.Asset,
) error

EnrichAndClassifyBatch enriches findings with EPSS/KEV and classifies priority. Used after ingest to process a batch of new/updated findings.

func (*PriorityClassificationService) ExplainFinding added in v0.3.0

func (s *PriorityClassificationService) ExplainFinding(ctx context.Context, tenantID, findingID shared.ID) (*PriorityExplanation, error)

ExplainFinding computes the priority explanation for a single finding without mutating it. It loads the finding and its asset, applies compensating-control reduction, evaluates tenant override rules, and reports the resulting class alongside every contributing factor.

func (*PriorityClassificationService) SetAITriageVerdictLookup added in v0.6.0

func (s *PriorityClassificationService) SetAITriageVerdictLookup(l AITriageVerdictLookup)

SetAITriageVerdictLookup wires the AI-triage false-positive lookup used to de-escalate a finding whose latest completed triage flagged it as a high-confidence false positive. Optional — nil keeps classification unchanged (no AI signal → never a downgrade).

func (*PriorityClassificationService) SetAssetOwnerLookup added in v0.6.0

func (s *PriorityClassificationService) SetAssetOwnerLookup(l AssetOwnerLookup)

SetAssetOwnerLookup wires the asset-owner-presence lookup used to floor unowned findings at P2. Optional — nil keeps classification unchanged (no floor). Safe to call after construction.

func (*PriorityClassificationService) SetBusinessContextLookup added in v0.6.0

func (s *PriorityClassificationService) SetBusinessContextLookup(lookup BusinessContextLookup)

SetBusinessContextLookup wires the business-unit / business-service criticality lookup used to raise an asset's effective criticality. Safe to call after construction; nil keeps classification on the asset's own criticality.

func (*PriorityClassificationService) SetChangePublisher

func (s *PriorityClassificationService) SetChangePublisher(p PriorityChangePublisher)

SetChangePublisher wires the priority-change event publisher. Safe to call after construction; nil disables publishing.

func (*PriorityClassificationService) SetControlLookup

func (s *PriorityClassificationService) SetControlLookup(lookup CompensatingControlLookup)

SetControlLookup wires the compensating control lookup for priority calculation.

func (*PriorityClassificationService) SetOwnershipFloorPolicy added in v0.6.0

func (s *PriorityClassificationService) SetOwnershipFloorPolicy(p OwnershipFloorPolicy)

SetOwnershipFloorPolicy wires the per-tenant toggle for the CTEM ownership floor. Optional — nil keeps the floor off for every tenant (the conservative default). Safe to call after construction.

func (*PriorityClassificationService) SetPriorityFloodGuard

func (s *PriorityClassificationService) SetPriorityFloodGuard(g *PriorityFloodGuard)

SetPriorityFloodGuard wires the anti-flap budget used to suppress downstream fan-out on top-class bursts from noisy scanners. Nil disables the guard. Safe to call after construction.

func (*PriorityClassificationService) SetReachabilityOracle added in v0.4.0

func (s *PriorityClassificationService) SetReachabilityOracle(o ReachabilityOracle)

SetReachabilityOracle wires attack-path reachability into classification. Optional — nil keeps the asset-exposure-only fallback.

func (*PriorityClassificationService) SetThreatModelOracle added in v0.4.0

func (s *PriorityClassificationService) SetThreatModelOracle(o ThreatModelOracle)

SetThreatModelOracle wires the threat-model engine's output into classification. Optional — nil keeps classification unchanged.

type PriorityExplanation added in v0.3.0

type PriorityExplanation struct {
	FindingID string `json:"finding_id"`
	// Decision
	Class    string  `json:"priority_class"`
	Reason   string  `json:"reason"`
	Source   string  `json:"source"` // "auto" | "rule"
	RuleName *string `json:"rule_name,omitempty"`

	// Factors that fed the decision (so an operator can audit/tune).
	Factors PriorityFactors `json:"factors"`

	// ScoreBreakdown is the transparent CTEM composite score (ctem.org
	// prioritization model) computed from the same factors: the four 0–5
	// sub-scores and the final PriorityScore = (Impact + Likelihood + Exposure) ×
	// (1 − ControlReduction). It EXPLAINS the class above without changing it —
	// the P0–P3 cascade stays authoritative.
	ScoreBreakdown vulnerability.PriorityScoreBreakdown `json:"score_breakdown"`
}

PriorityExplanation is a read-only, human-auditable breakdown of WHY a finding holds its priority class — the factors that fed the classifier and the decision it reached. It mirrors what ClassifyFinding would compute but persists nothing and emits no events.

type PriorityFactors added in v0.3.0

type PriorityFactors struct {
	Severity             string   `json:"severity"`
	CVEID                string   `json:"cve_id,omitempty"`
	EPSSScore            *float64 `json:"epss_score,omitempty"`
	EPSSPercentile       *float64 `json:"epss_percentile,omitempty"`
	IsInKEV              bool     `json:"is_in_kev"`
	IsReachable          bool     `json:"is_reachable"`
	IsInternetAccessible bool     `json:"is_internet_accessible"`
	IsNetworkAccessible  bool     `json:"is_network_accessible"`
	OnOpenThreatPath     bool     `json:"on_open_threat_path"`
	ReachableFromCount   int      `json:"reachable_from_count"`
	AssetCriticality     string   `json:"asset_criticality,omitempty"`
	AssetExposure        string   `json:"asset_exposure,omitempty"`
	AssetIsCrownJewel    bool     `json:"asset_is_crown_jewel"`
	AssetUnowned         bool     `json:"asset_unowned"`
	IsProtected          bool     `json:"is_protected"`
	ControlReductionPct  float64  `json:"control_reduction_pct"`

	// CIA business-impact rating from the asset's critical-asset register. Score
	// is the 0–5 impact contribution (MAX leg); Detail names the highest leg
	// (e.g. "confidentiality=high"). Both zero/empty when no rating is set.
	CIAImpactScore  float64 `json:"cia_impact_score"`
	CIAImpactDetail string  `json:"cia_impact_detail,omitempty"`

	// Derived gates (computed exactly as ClassifyPriority does).
	Reachable     bool `json:"reachable"`
	CriticalAsset bool `json:"critical_asset"`
}

PriorityFactors are the inputs to the classifier, plus the two derived booleans the rules actually gate on (reachable, critical_asset), so the explanation is self-contained.

type PriorityFloodConfig

type PriorityFloodConfig struct {
	// ProtectedClass is the priority class whose downstream fan-out
	// is capped. Defaults to vulnerability.PriorityP0 — the highest
	// class is the one that actually moves SLA clocks and pages
	// humans, so flooding there is the acute failure mode.
	ProtectedClass vulnerability.PriorityClass
	// MaxPerHour is the ceiling of newly-classified findings at the
	// protected class per tenant per rolling hour at which we start
	// suppressing downstream side effects. Default 50 — chosen
	// because a single tenant realistically cannot action more than
	// ~50 of the top class per hour.
	MaxPerHour int
	// Now is injectable for deterministic tests.
	Now func() time.Time
}

PriorityFloodConfig tunes the guard. Zero values take documented defaults.

type PriorityFloodGuard

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

PriorityFloodGuard is per-process in-memory. A future iteration moves it to Redis for cross-replica dedup; as long as there is ONE background worker doing classification (the sweep controller), in-memory is sufficient.

func NewPriorityFloodGuard

func NewPriorityFloodGuard(cfg PriorityFloodConfig) *PriorityFloodGuard

NewPriorityFloodGuard constructs the guard with defaults.

func (*PriorityFloodGuard) CurrentUsage

func (g *PriorityFloodGuard) CurrentUsage(tenantID shared.ID) int

CurrentUsage exposes the rolling-hour count for dashboards.

func (*PriorityFloodGuard) Refund

func (g *PriorityFloodGuard) Refund(tenantID shared.ID)

Refund returns a slot to the tenant's budget. Used when the caller's fan-out fails and will retry — otherwise a delivery failure would permanently burn the slot.

func (*PriorityFloodGuard) ShouldFanOut

func (g *PriorityFloodGuard) ShouldFanOut(
	ctx context.Context,
	tenantID shared.ID,
	class vulnerability.PriorityClass,
) (bool, error)

ShouldFanOut reports whether the downstream side effects (Jira, outbox, fast-lane queue) should run for a newly-classified finding at the guard's protected class.

Returns (true, nil) under budget — record AND fire. Returns (false, ErrPriorityFloodSuppressed) over budget — record only.

A classification that is NOT the protected class short-circuits immediately and the budget is not charged.

type PriorityRuleRepository

type PriorityRuleRepository interface {
	ListActiveByTenant(ctx context.Context, tenantID shared.ID) ([]*vulnerability.PriorityOverrideRule, error)
}

PriorityRuleRepository provides override rule lookups.

type ReachabilityOracle added in v0.4.0

type ReachabilityOracle interface {
	ReachableFromPublic(ctx context.Context, tenantID shared.ID) (map[string]bool, error)
}

ReachabilityOracle returns, for a tenant, the set of asset IDs that sit on a validated attack path from a public entry point to a KEV/crown-jewel target (entry points + hops + targets of the exposure-chain graph). Implemented over the attack-surface service with a short TTL cache so per-finding classification stays cheap.

type RejectApprovalInput

type RejectApprovalInput struct {
	TenantID   string `json:"tenant_id" validate:"required,uuid"`
	ApprovalID string `json:"approval_id" validate:"required,uuid"`
	RejectedBy string `json:"rejected_by" validate:"required,uuid"`
	Reason     string `json:"reason" validate:"required,min=1,max=2000"`
}

RejectApprovalInput represents the input for rejecting a status change.

type RejectByFilterInput

type RejectByFilterInput struct {
	Filter vulnerability.FindingFilter
	Reason string
}

RejectByFilterInput is the input for bulk reject by filter.

type RequestApprovalInput

type RequestApprovalInput struct {
	TenantID        string  `json:"tenant_id" validate:"required,uuid"`
	FindingID       string  `json:"finding_id" validate:"required,uuid"`
	RequestedStatus string  `json:"requested_status" validate:"required"`
	Justification   string  `json:"justification" validate:"required,min=1,max=2000"`
	RequestedBy     string  `json:"requested_by" validate:"required,uuid"`
	ExpiresAt       *string `json:"expires_at"`
}

RequestApprovalInput represents the input for requesting a status approval.

type RequestVerificationScanInput

type RequestVerificationScanInput struct {
	FindingID   string
	ScannerName string // required if WorkflowID is empty
	WorkflowID  string // required if ScannerName is empty
}

RequestVerificationScanInput is the input for requesting a verification scan.

type RequestVerificationScanResult

type RequestVerificationScanResult struct {
	FindingID     string `json:"finding_id"`
	AssetID       string `json:"asset_id"`
	AssetName     string `json:"asset_name"`
	PipelineRunID string `json:"pipeline_run_id"`
	ScanID        string `json:"scan_id"`
}

RequestVerificationScanResult is the result of requesting a verification scan.

type SLAApplier added in v0.6.0

type SLAApplier interface {
	ApplyBatch(ctx context.Context, tenantID shared.ID, findings []*vulnerability.Finding) error
}

SLAApplier computes and attaches an SLA deadline to each finding using its priority class (severity fallback). Mirrors the ingest path's applier so a manually-created finding gets the same treatment. Implemented by *sla.Applier.

type SourceAnalytics added in v0.4.0

type SourceAnalytics struct {
	Sources         []vulnerability.SourceStat `json:"sources"`
	Total           int                        `json:"total"`
	OpenTotal       int                        `json:"open_total"`
	DefectDojoTotal int                        `json:"defectdojo_total"`
	NativeTotal     int                        `json:"native_total"`
	// DefectDojoDependencyRatio is defectdojo findings / total, 0..1. As native
	// parsers cover more tools this trends to 0 — the signal that DefectDojo can
	// be phased out (RFC-013 Phase 3).
	DefectDojoDependencyRatio float64 `json:"defectdojo_dependency_ratio"`
}

SourceAnalytics is the per-source finding breakdown plus the headline metrics: Tool Insights (which scanner contributes what) and the DefectDojo-dependency ratio — RFC-013's measure-to-phase-out guardrail.

type SourceAnalyticsService added in v0.4.0

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

SourceAnalyticsService computes the source breakdown + dependency metrics.

func NewSourceAnalyticsService added in v0.4.0

func NewSourceAnalyticsService(reader SourceBreakdownReader, log *logger.Logger) *SourceAnalyticsService

NewSourceAnalyticsService wires the analytics service.

func (*SourceAnalyticsService) GetSourceAnalytics added in v0.4.0

func (s *SourceAnalyticsService) GetSourceAnalytics(ctx context.Context, tenantID string) (*SourceAnalytics, error)

GetSourceAnalytics returns the tenant's finding source breakdown + metrics.

type SourceBreakdownReader added in v0.4.0

type SourceBreakdownReader interface {
	SourceBreakdown(ctx context.Context, tenantID shared.ID) ([]vulnerability.SourceStat, error)
}

SourceBreakdownReader is the narrow read surface the analytics service needs. Satisfied by *postgres.FindingRepository — kept narrow so it isn't forced onto every FindingRepository implementation/mock.

type TenantLister

type TenantLister interface {
	// ListActiveTenantIDs returns all active tenant IDs for batch processing.
	ListActiveTenantIDs(ctx context.Context) ([]shared.ID, error)
}

TenantLister provides a list of active tenant IDs.

type TenantOwnershipFloorPolicy added in v0.6.0

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

TenantOwnershipFloorPolicy reads the FloorUnownedAtP2 toggle from a tenant's risk-scoring settings. Mirrors asset.TenantScoringConfigProvider: one tenant lookup, and any error is treated as "off" (never a silent re-prioritization).

func NewTenantOwnershipFloorPolicy added in v0.6.0

func NewTenantOwnershipFloorPolicy(tenantRepo tenantdom.Repository) *TenantOwnershipFloorPolicy

NewTenantOwnershipFloorPolicy builds the tenant-settings-backed floor policy.

func (*TenantOwnershipFloorPolicy) FloorUnownedAtP2 added in v0.6.0

func (p *TenantOwnershipFloorPolicy) FloorUnownedAtP2(ctx context.Context, tenantID shared.ID) bool

FloorUnownedAtP2 returns the tenant's toggle; false on any error or when the tenant / setting is absent.

type ThreatModelOracle added in v0.4.0

type ThreatModelOracle interface {
	OnOpenThreatPath(ctx context.Context, tenantID shared.ID) (map[string]bool, error)
}

ThreatModelOracle returns, for a tenant, the set of asset IDs that sit on an OPEN, high-score threat in the tenant's latest generated threat model — the entry points, hops, and targets of unmitigated modeled attack chains. Mirrors ReachabilityOracle: implemented over the threat-model store with a short TTL cache so per-finding classification stays cheap (one tenant-scoped, indexed query per cache miss — no N+1).

type UpdateCommentInput

type UpdateCommentInput struct {
	Content string `validate:"required,min=1,max=10000"`
}

UpdateCommentInput represents the input for updating a comment.

type UpdateFindingStatusInput

type UpdateFindingStatusInput struct {
	Status              string `validate:"required,finding_status"`
	Resolution          string `validate:"max=1000"`
	ActorID             string // Authenticated user ID from middleware (required for audit trail and resolved_by)
	HasVerifyPermission bool   // True if user has findings:verify permission (for direct resolve guard)
}

UpdateFindingStatusInput represents the input for updating a finding's status.

type UpdateRemediationInput added in v0.6.0

type UpdateRemediationInput struct {
	// PreferredFix is the recommended way to remediate.
	PreferredFix *string
	// AlternativeFixes are other acceptable remediations (repeatable rows).
	AlternativeFixes *[]string
	// VerificationMethod states how a claimed fix will be checked.
	VerificationMethod *string
	// SuccessCriteria is the definition of done for the fix.
	SuccessCriteria *string
}

UpdateRemediationInput carries the operator-entered, engineering-grade remediation guidance for a finding (CTEM Mobilization stage). Pointer fields distinguish "not provided" (leave unchanged) from an explicit empty value (clear). Fields ride the findings.remediation JSONB column — no migration. See https://ctem.org/docs/stages/ctem-mobilization.

type UpdateVulnerabilityInput

type UpdateVulnerabilityInput struct {
	Title            *string  `validate:"omitempty,min=1,max=500"`
	Description      *string  `validate:"omitempty,max=10000"`
	Severity         *string  `validate:"omitempty,severity"`
	CVSSScore        *float64 `validate:"omitempty,min=0,max=10"`
	CVSSVector       *string  `validate:"omitempty,max=100"`
	EPSSScore        *float64 `validate:"omitempty,min=0,max=1"`
	EPSSPercentile   *float64 `validate:"omitempty,min=0,max=100"` // 0-100; a 0-1 fraction is also accepted and rescaled (vulnerability.NormalizeEPSSPercentile)
	ExploitAvailable *bool
	ExploitMaturity  *string  `validate:"omitempty,exploit_maturity"`
	FixedVersions    []string `validate:"omitempty,max=50,dive,max=100"`
	Remediation      *string  `validate:"omitempty,max=5000"`
	Status           *string  `validate:"omitempty,vulnerability_status"`
}

UpdateVulnerabilityInput represents the input for updating a vulnerability.

type VerificationScanTrigger

type VerificationScanTrigger interface {
	// TriggerVerificationScan launches a quick scan on the given targets.
	// targets is a list of asset identifiers (names / hostnames / URLs).
	// Returns the pipeline run ID and scan ID on success.
	TriggerVerificationScan(ctx context.Context, tenantID, createdBy, scannerName, workflowID string, targets []string) (pipelineRunID, scanID string, err error)
}

VerificationScanTrigger is the interface for triggering targeted verification scans. Implemented by the scan.Service; kept as interface to avoid import cycles.

type VerifyByFilterInput

type VerifyByFilterInput struct {
	Filter vulnerability.FindingFilter
	Note   string
}

VerifyByFilterInput is the input for bulk verify by filter.

type VulnerabilityService

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

VulnerabilityService handles vulnerability-related business operations.

func NewVulnerabilityService

func NewVulnerabilityService(
	vulnRepo vulnerability.VulnerabilityRepository,
	findingRepo vulnerability.FindingRepository,
	log *logger.Logger,
) *VulnerabilityService

NewVulnerabilityService creates a new VulnerabilityService.

func (*VulnerabilityService) AddFindingComment

func (s *VulnerabilityService) AddFindingComment(ctx context.Context, tenantID, findingID, authorID, content string) (*vulnerability.FindingComment, error)

AddFindingComment adds a comment to a finding. tenantID is used for IDOR prevention and activity logging.

func (*VulnerabilityService) AddFindingEvidence added in v0.4.0

func (s *VulnerabilityService) AddFindingEvidence(ctx context.Context, input AddEvidenceInput) (*FindingEvidence, error)

AddFindingEvidence attaches a note-type evidence record to a generic finding.

Authorization: the finding is loaded tenant-scoped and pentest-managed findings are rejected (they carry evidence through the pentest module's campaign-role gate). This is a NEW, parallel, tenant-scoped path that does NOT touch the pentest CheckFindingAccess gate.

func (*VulnerabilityService) AddRemediationStep added in v0.4.0

func (s *VulnerabilityService) AddRemediationStep(ctx context.Context, findingID, tenantID, step string) ([]string, error)

AddRemediationStep appends a single remediation step to a generic finding, preserving any existing steps. Returns the updated step list.

Load-existing → append → persist the whole slice (never wipes prior steps).

func (*VulnerabilityService) ApproveStatus

ApproveStatus approves a pending status change request and applies the status change.

func (*VulnerabilityService) AssignFinding

func (s *VulnerabilityService) AssignFinding(ctx context.Context, findingID, tenantID, userID, assignerID string) (*vulnerability.Finding, error)

AssignFinding assigns a finding to a user.

func (*VulnerabilityService) BulkAssignFindings

func (s *VulnerabilityService) BulkAssignFindings(ctx context.Context, tenantID string, input BulkAssignInput) (*BulkUpdateResult, error)

BulkAssignFindings assigns multiple findings to a user.

func (*VulnerabilityService) BulkUpdateFindingStatus

func (s *VulnerabilityService) BulkUpdateFindingStatus(ctx context.Context, tenantID shared.ID, ids []shared.ID, status vulnerability.FindingStatus, resolution string, resolvedBy *shared.ID) error

BulkUpdateFindingStatus updates the status of multiple findings. Pentest findings are excluded — they must be managed via the pentest module.

func (*VulnerabilityService) BulkUpdateFindingsStatus

func (s *VulnerabilityService) BulkUpdateFindingsStatus(ctx context.Context, tenantID string, input BulkUpdateStatusInput) (*BulkUpdateResult, error)

BulkUpdateFindingsStatus updates the status of multiple findings. Optimized: batch-fetches all findings in 1 query, validates transitions in-memory, then batch-updates valid ones in 1 query. Reduces N+1 to 2 queries total.

func (*VulnerabilityService) CancelApproval

CancelApproval cancels a pending approval request. Only the requester can cancel.

func (*VulnerabilityService) ClassifyFinding

func (s *VulnerabilityService) ClassifyFinding(ctx context.Context, findingID, tenantID string, input ClassifyFindingInput) (*vulnerability.Finding, error)

ClassifyFinding sets classification data on a finding.

func (*VulnerabilityService) CountAssetFindings

func (s *VulnerabilityService) CountAssetFindings(
	ctx context.Context,
	tenantID string,
	assetID string,
) (int64, error)

CountAssetFindings counts findings for an asset. tenantID is used for IDOR prevention - ensures the findings belong to the caller's tenant.

func (*VulnerabilityService) CountOpenAssetFindings

func (s *VulnerabilityService) CountOpenAssetFindings(
	ctx context.Context,
	tenantID string,
	assetID string,
) (int64, error)

CountOpenAssetFindings counts open findings for an asset. tenantID is used for IDOR prevention - ensures the findings belong to the caller's tenant.

func (*VulnerabilityService) CreateFinding

CreateFinding creates a new finding.

func (*VulnerabilityService) CreateVulnerability

CreateVulnerability creates a new vulnerability.

func (*VulnerabilityService) DeleteAssetFindings

func (s *VulnerabilityService) DeleteAssetFindings(
	ctx context.Context,
	tenantID string,
	assetID string,
) error

DeleteAssetFindings deletes all findings for an asset. tenantID is used for IDOR prevention - ensures the findings belong to the caller's tenant.

func (*VulnerabilityService) DeleteFinding

func (s *VulnerabilityService) DeleteFinding(ctx context.Context, findingID string, tenantID string) error

DeleteFinding deletes a finding by ID. tenantID is used for IDOR prevention - ensures the finding belongs to the caller's tenant.

func (*VulnerabilityService) DeleteFindingComment

func (s *VulnerabilityService) DeleteFindingComment(ctx context.Context, tenantID, commentID, authorID string) error

DeleteFindingComment deletes a comment. tenantID scopes the lookup and the DELETE WHERE clause — closes the same IDOR vector as UpdateFindingComment.

func (*VulnerabilityService) DeleteFindingEvidence added in v0.4.0

func (s *VulnerabilityService) DeleteFindingEvidence(ctx context.Context, findingID, tenantID, noteID string) error

DeleteFindingEvidence removes a note-type evidence record from a generic (non-pentest) finding.

Authorization mirrors the add path: the finding is loaded tenant-scoped and pentest-managed findings are rejected. The note is then confirmed to belong to THIS finding's own attachment context (context_type=finding, context_id=findingID, tenant=f.TenantID) BEFORE any delete — an attachment id from a different finding or tenant is absent from that list and yields ErrNotFound, so we never delete by attachment id alone. Only note-type attachments (JSON payload with the evidence-note filename prefix) may be removed here; a plain file/pentest attachment sharing the context is refused.

func (*VulnerabilityService) DeleteVulnerability

func (s *VulnerabilityService) DeleteVulnerability(ctx context.Context, vulnID string) error

DeleteVulnerability deletes a vulnerability by ID.

func (*VulnerabilityService) GetActiveCVEStats added in v0.3.0

func (s *VulnerabilityService) GetActiveCVEStats(
	ctx context.Context,
	tenantID string,
	includeResolved bool,
) (*vulnerability.ActiveCVEStats, error)

GetActiveCVEStats returns aggregate counts (total, by-severity, KEV, exploit) for the tenant's active CVEs. Powers the stat-card row above the Active CVEs table.

func (*VulnerabilityService) GetFinding

func (s *VulnerabilityService) GetFinding(ctx context.Context, tenantID, findingID string) (*vulnerability.Finding, error)

GetFinding retrieves a finding by ID. tenantID is used for IDOR prevention - ensures the finding belongs to the caller's tenant.

func (*VulnerabilityService) GetFindingCountsByScanID

func (s *VulnerabilityService) GetFindingCountsByScanID(ctx context.Context, tenantID, scanID string) (vulnerability.SeverityCounts, error)

GetFindingCountsByScanID returns the count of findings by severity for a scan. Used for quality gate evaluation.

func (*VulnerabilityService) GetFindingStats

func (s *VulnerabilityService) GetFindingStats(ctx context.Context, tenantID string) (*vulnerability.FindingStats, error)

GetFindingStats retrieves aggregated statistics for findings of a tenant.

func (*VulnerabilityService) GetFindingStatsWithScope

func (s *VulnerabilityService) GetFindingStatsWithScope(ctx context.Context, input GetFindingStatsInput) (*vulnerability.FindingStats, error)

GetFindingStatsWithScope retrieves stats with optional data scope enforcement.

func (*VulnerabilityService) GetFindingWithScope

func (s *VulnerabilityService) GetFindingWithScope(ctx context.Context, tenantID, findingID, actingUserID string, isAdmin bool) (*vulnerability.Finding, error)

GetFindingWithScope retrieves a finding with optional data scope enforcement. Non-admin users with group assignments can only access findings for assets in their groups. Security: fail-closed — any error during scope check denies access. Returns ErrNotFound (not ErrForbidden) to prevent information disclosure.

func (*VulnerabilityService) GetVulnerability

func (s *VulnerabilityService) GetVulnerability(ctx context.Context, vulnID string) (*vulnerability.Vulnerability, error)

GetVulnerability retrieves a vulnerability by ID.

func (*VulnerabilityService) GetVulnerabilityByCVE

func (s *VulnerabilityService) GetVulnerabilityByCVE(ctx context.Context, cveID string) (*vulnerability.Vulnerability, error)

GetVulnerabilityByCVE retrieves a vulnerability by CVE ID.

func (*VulnerabilityService) ListActiveCVEs added in v0.3.0

ListActiveCVEs returns CVEs currently impacting tenant assets (Active CVEs view). Distinct from the global CVE catalog — scoped to findings within tenant.

func (*VulnerabilityService) ListAffectedAssets added in v0.3.0

func (s *VulnerabilityService) ListAffectedAssets(
	ctx context.Context,
	tenantID, vulnID string,
	includeResolved bool,
	page, perPage int,
) (pagination.Result[vulnerability.VulnerabilityAffectedAsset], error)

ListAffectedAssets returns the assets in the tenant affected by a CVE (blast-radius reverse lookup). Powers the "Affected Assets" panel on the vulnerability detail sheet.

includeResolved controls whether assets affected only by closed findings (resolved/false_positive/accepted) are included. Default is false (open only).

func (*VulnerabilityService) ListAffectedAssetsByCVE added in v0.3.0

func (s *VulnerabilityService) ListAffectedAssetsByCVE(
	ctx context.Context,
	tenantID, cveID string,
	includeResolved bool,
	page, perPage int,
) (pagination.Result[vulnerability.VulnerabilityAffectedAsset], error)

ListAffectedAssetsByCVE is a convenience wrapper that resolves CVE-2024-XXXX to the global Vulnerability ID then delegates.

func (*VulnerabilityService) ListAssetFindings

func (s *VulnerabilityService) ListAssetFindings(
	ctx context.Context,
	tenantID string,
	assetID string,
	sort string,
	page,
	perPage int,
) (pagination.Result[*vulnerability.Finding], error)

ListAssetFindings retrieves findings for a specific asset. tenantID is used for IDOR prevention - ensures the findings belong to the caller's tenant.

func (*VulnerabilityService) ListFindingApprovals

func (s *VulnerabilityService) ListFindingApprovals(ctx context.Context, tenantID, findingID string) ([]*vulnerability.Approval, error)

ListFindingApprovals lists all approvals for a finding.

func (*VulnerabilityService) ListFindingComments

func (s *VulnerabilityService) ListFindingComments(ctx context.Context, tenantID, findingID, actingUserID string, isAdmin bool) ([]*vulnerability.FindingComment, error)

ListFindingComments retrieves all comments for a finding.

func (*VulnerabilityService) ListFindingEvidence added in v0.4.0

func (s *VulnerabilityService) ListFindingEvidence(ctx context.Context, findingID, tenantID string) ([]*FindingEvidence, error)

ListFindingEvidence returns all evidence attached to a generic finding, tenant-scoped. Note records are decoded from storage; any other attachment is surfaced as a downloadable file.

func (*VulnerabilityService) ListFindingIDs added in v0.4.0

func (s *VulnerabilityService) ListFindingIDs(ctx context.Context, filter vulnerability.FindingFilter, limit int) ([]shared.ID, error)

ListFindingIDs returns up to limit finding IDs matching the filter. Used by filter-driven bulk actions (e.g. resolving a remediation campaign's open findings). The filter carries the tenant scope; callers pass an open-status filter to target only actionable findings.

func (*VulnerabilityService) ListFindings

ListFindings retrieves findings with filtering and pagination.

func (*VulnerabilityService) ListPendingApprovals

func (s *VulnerabilityService) ListPendingApprovals(ctx context.Context, tenantID string, page, perPage int) (pagination.Result[*vulnerability.Approval], error)

ListPendingApprovals lists all pending approvals for a tenant.

func (*VulnerabilityService) ListVulnerabilities

ListVulnerabilities retrieves vulnerabilities with filtering and pagination.

func (*VulnerabilityService) RejectApproval

RejectApproval rejects a pending status change request.

func (*VulnerabilityService) RequestApproval

RequestApproval creates a new pending approval request for a status change.

func (*VulnerabilityService) SetAITriageService

func (s *VulnerabilityService) SetAITriageService(svc *aitriage.AITriageService)

SetAITriageService sets the AI triage service for auto-triage on finding creation.

func (*VulnerabilityService) SetAccessControlRepository

func (s *VulnerabilityService) SetAccessControlRepository(repo accesscontrol.Repository)

SetAccessControlRepository sets the access control repository for Layer 2 data scope checks.

func (*VulnerabilityService) SetActivityService

func (s *VulnerabilityService) SetActivityService(svc *activity.FindingActivityService)

SetActivityService sets the activity service for audit trail tracking. When set, the service will automatically record activities for finding changes.

func (*VulnerabilityService) SetApprovalRepository

func (s *VulnerabilityService) SetApprovalRepository(repo vulnerability.ApprovalRepository)

SetApprovalRepository sets the approval repository for status approval workflow.

func (*VulnerabilityService) SetAssetRepository added in v0.6.0

func (s *VulnerabilityService) SetAssetRepository(repo asset.Repository)

SetAssetRepository wires the asset repository used to load a finding's asset for priority classification context (exposure, criticality, crown-jewel). Nil-safe: without it, classification is skipped.

func (*VulnerabilityService) SetAssignmentEngine

func (s *VulnerabilityService) SetAssignmentEngine(engine *assignment.Engine)

SetAssignmentEngine sets the assignment engine for auto-routing findings to groups.

func (*VulnerabilityService) SetCommentRepository

func (s *VulnerabilityService) SetCommentRepository(repo vulnerability.FindingCommentRepository)

SetCommentRepository sets the comment repository for comment operations. This is optional and can be called after service creation.

func (*VulnerabilityService) SetDataFlowRepository

func (s *VulnerabilityService) SetDataFlowRepository(repo vulnerability.DataFlowRepository)

SetDataFlowRepository sets the data flow repository for loading data flow traces.

func (*VulnerabilityService) SetDataScopePolicy

func (s *VulnerabilityService) SetDataScopePolicy(p DataScopePolicy)

SetDataScopePolicy wires the per-tenant fail-open/closed policy. Nil-safe: leaving it unset keeps data scope fail-open everywhere.

func (*VulnerabilityService) SetEvidenceStore added in v0.4.0

func (s *VulnerabilityService) SetEvidenceStore(store EvidenceStore)

SetEvidenceStore wires the attachment-backed evidence store. Safe to call after construction; nil disables the finding-evidence endpoints.

func (*VulnerabilityService) SetFindingNotifier

func (s *VulnerabilityService) SetFindingNotifier(notifier FindingNotifier)

SetFindingNotifier sets the notifier for new findings. Deprecated: Use SetOutboxService for reliable transactional notifications.

func (*VulnerabilityService) SetFindingTags

func (s *VulnerabilityService) SetFindingTags(ctx context.Context, findingID, tenantID string, tags []string) (*vulnerability.Finding, error)

SetFindingTags sets tags on a finding.

func (*VulnerabilityService) SetJiraStatusSyncHook added in v0.3.0

func (s *VulnerabilityService) SetJiraStatusSyncHook(fn func(ctx context.Context, tenantID, findingID shared.ID))

SetJiraStatusSyncHook wires the outbound Jira status-sync trigger. Safe to call after construction; nil disables it. The hook should be cheap (enqueue-and-return) — the actual Jira call happens in a background worker.

func (*VulnerabilityService) SetOutboxService

func (s *VulnerabilityService) SetOutboxService(db *sql.DB, svc *outbox.Service)

SetOutboxService sets the notification service for transactional outbox pattern. When set, notifications are enqueued in the same transaction as finding creation, ensuring reliable delivery even if the server crashes.

func (*VulnerabilityService) SetPriorityClassifier added in v0.6.0

func (s *VulnerabilityService) SetPriorityClassifier(classifier *PriorityClassificationService)

SetPriorityClassifier wires the priority classification service (RFC-004) so findings created via the REST API get the same EPSS/KEV enrichment, priority_class, and is_reachable derivation that ingested findings receive. Nil-safe: nil leaves creation unclassified (previous behavior).

func (*VulnerabilityService) SetSLAApplier added in v0.6.0

func (s *VulnerabilityService) SetSLAApplier(applier SLAApplier)

SetSLAApplier wires the SLA-deadline applier. MUST be paired with the priority classifier — the P0..P3 class drives the deadline. Nil-safe: nil skips SLA.

func (*VulnerabilityService) SetUserNotificationService

func (s *VulnerabilityService) SetUserNotificationService(svc *integration.NotificationService)

SetUserNotificationService sets the in-app notification service for user-facing notifications.

func (*VulnerabilityService) SetUserRepository

func (s *VulnerabilityService) SetUserRepository(repo user.Repository)

SetUserRepository sets the user repository for user lookup (e.g., for activity recording).

func (*VulnerabilityService) SetWorkflowStatusDispatch added in v0.6.0

func (s *VulnerabilityService) SetWorkflowStatusDispatch(fn func(ctx context.Context, tenantID shared.ID, f *vulnerability.Finding, oldStatus, newStatus string))

SetWorkflowStatusDispatch wires the workflow event trigger fired after a finding status change. Safe to call after construction; nil disables it.

func (*VulnerabilityService) TriageFinding

func (s *VulnerabilityService) TriageFinding(ctx context.Context, findingID, tenantID, userID, reason string) (*vulnerability.Finding, error)

TriageFinding confirms a finding (triage = confirm the finding is real). This is a convenience method that transitions status from "new" to "confirmed". For other status changes, use UpdateFindingStatus.

func (*VulnerabilityService) UnassignFinding

func (s *VulnerabilityService) UnassignFinding(ctx context.Context, findingID, tenantID, actorID string) (*vulnerability.Finding, error)

UnassignFinding removes the assignment from a finding.

func (*VulnerabilityService) UpdateFindingComment

func (s *VulnerabilityService) UpdateFindingComment(ctx context.Context, tenantID, commentID, authorID, content string) (*vulnerability.FindingComment, error)

UpdateFindingComment updates a comment's content. tenantID scopes the lookup so a user in tenant A cannot resolve a commentID owned by tenant B — closes the IDOR vector where the author-ID short-circuit (authorID=="") would let an admin-path bypass the per-row owner check.

func (*VulnerabilityService) UpdateFindingRemediation added in v0.6.0

func (s *VulnerabilityService) UpdateFindingRemediation(ctx context.Context, findingID, tenantID string, input UpdateRemediationInput) (*vulnerability.Finding, error)

UpdateFindingRemediation applies the Mobilization guidance fields onto a finding's existing remediation object (creating one if absent) and persists it. Existing scanner-provided remediation data (recommendation, fix code, steps, references) is preserved — only the provided guidance fields change.

func (*VulnerabilityService) UpdateFindingSeverity

func (s *VulnerabilityService) UpdateFindingSeverity(ctx context.Context, findingID, tenantID, severityStr, actorID string) (*vulnerability.Finding, error)

UpdateFindingSeverity updates a finding's severity.

func (*VulnerabilityService) UpdateFindingStatus

func (s *VulnerabilityService) UpdateFindingStatus(ctx context.Context, findingID string, tenantID string, input UpdateFindingStatusInput) (*vulnerability.Finding, error)

UpdateFindingStatus updates a finding's status. tenantID is used for IDOR prevention - ensures the finding belongs to the caller's tenant.

func (*VulnerabilityService) UpdateVulnerability

UpdateVulnerability updates an existing vulnerability.

func (*VulnerabilityService) VerifyFinding

func (s *VulnerabilityService) VerifyFinding(ctx context.Context, findingID, tenantID, userID string) (*vulnerability.Finding, error)

VerifyFinding marks a resolved finding as verified.

Jump to

Keyboard shortcuts

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