Documentation
¶
Overview ¶
Package controller implements K8s-style reconciliation loop controllers for self-healing background operations.
Controllers periodically reconcile the desired state of the system with its actual state. Each controller runs in its own goroutine and handles a specific aspect of the system: - AgentHealthController: Marks stale agents as offline, cleans up expired leases - JobRecoveryController: Recovers stuck jobs and re-queues them - QueuePriorityController: Recalculates queue priorities for fair scheduling - TokenCleanupController: Cleans up expired bootstrap tokens - AuditRetentionController: Manages audit log retention
Design principles: - Each controller is independent and can fail without affecting others - Controllers are idempotent - running multiple times has the same effect - Controllers use optimistic locking to handle concurrent modifications - All state changes are logged for debugging and monitoring
Index ¶
- type AgentHealthController
- type AgentHealthControllerConfig
- type ApprovalExpirationController
- type ApprovalExpirationControllerConfig
- type AssetLifecycleController
- type AssetLifecycleControllerConfig
- type AuditChainVerifyController
- type AuditChainVerifyControllerConfig
- type AuditRetentionController
- type AuditRetentionControllerConfig
- type CTEMIDRefreshController
- type CertMonitorController
- type CertMonitorControllerConfig
- type ControlChangePublisher
- func (p *ControlChangePublisher) PublishAssetReclassify(ctx context.Context, tenantID shared.ID, assetIDs []shared.ID, ...)
- func (p *ControlChangePublisher) PublishChange(ctx context.Context, tenantID shared.ID, assetIDs []shared.ID, reason string)
- func (p *ControlChangePublisher) PublishTenantChange(ctx context.Context, tenantID shared.ID, kind ReclassifyReasonKind, ...)
- type ControlTestSchedulerConfig
- type ControlTestSchedulerController
- type Controller
- type CoverageScheduler
- func (c *CoverageScheduler) ActiveIPs(ctx context.Context, tenantID shared.ID) (int, error)
- func (c *CoverageScheduler) Interval() time.Duration
- func (c *CoverageScheduler) ListActiveCoverage(ctx context.Context) ([]scancoverage.CoverageConfig, error)
- func (c *CoverageScheduler) ListCandidates(ctx context.Context, tenantID shared.ID, limit int) ([]scancoverage.Candidate, error)
- func (c *CoverageScheduler) MarkDispatched(ctx context.Context, rec scancoverage.DispatchRecord) error
- func (c *CoverageScheduler) Name() string
- func (c *CoverageScheduler) Reconcile(ctx context.Context) (int, error)
- type CoverageSchedulerConfig
- type DataExpirationController
- type DataExpirationControllerConfig
- type DefectDojoSyncController
- type DomainReverifyController
- type DomainReverifyControllerConfig
- type GraphEnrichmentController
- type GraphEnrichmentControllerConfig
- type IngestJobProcessor
- type IngestJobQueue
- type IngestWorkerController
- type IngestWorkerControllerConfig
- type IntegrationSyncStore
- type JobRecoveryController
- type JobRecoveryControllerConfig
- type Manager
- type ManagerConfig
- type Metrics
- type ModuleGuard
- type NoopMetrics
- func (m *NoopMetrics) IncrementReconcileErrors(controller string)
- func (m *NoopMetrics) RecordReconcile(controller string, itemsProcessed int, duration time.Duration, err error)
- func (m *NoopMetrics) SetControllerRunning(controller string, running bool)
- func (m *NoopMetrics) SetLastReconcileTime(controller string, t time.Time)
- type OwnerResolutionController
- type PriorityAuditRetentionConfig
- type PriorityAuditRetentionController
- type PriorityAuditRetentionStore
- type PriorityReclassifyConfig
- type PriorityReclassifyController
- type PriorityReclassifySweepConfig
- type PriorityReclassifySweepController
- type PrometheusMetrics
- func (m *PrometheusMetrics) IncrementReconcileErrors(controller string)
- func (m *PrometheusMetrics) RecordReconcile(controller string, itemsProcessed int, duration time.Duration, err error)
- func (m *PrometheusMetrics) SetControllerRunning(controller string, running bool)
- func (m *PrometheusMetrics) SetLastReconcileTime(controller string, t time.Time)
- type QueuePriorityController
- type QueuePriorityControllerConfig
- type Reclassifier
- type ReclassifyQueue
- type ReclassifyReasonKind
- type ReclassifyRequest
- type ReconcileTimeouter
- type RemediationProgressController
- type ReportEmailer
- type ReportScheduleStore
- type ReportScheduler
- type ReportSchedulerConfig
- type ReportStatsSource
- type RetryDispatcher
- type RiskSnapshotController
- type RoleSyncController
- type RoleSyncControllerConfig
- type SCMSyncController
- type SCMSyncer
- type SLABreachEvent
- type SLABreachPublisher
- type SLABreachTxPublisher
- type SLAEscalationController
- func (c *SLAEscalationController) Interval() time.Duration
- func (c *SLAEscalationController) Name() string
- func (c *SLAEscalationController) Reconcile(ctx context.Context) (int, error)
- func (c *SLAEscalationController) SetBreachPublisher(p SLABreachPublisher)
- func (c *SLAEscalationController) SetWarningPublisher(p SLAWarningPublisher)
- type SLAWarningEvent
- type SLAWarningPublisher
- type ScanRetryController
- type ScanRetryControllerConfig
- type ScanTimeoutController
- type ScanTimeoutControllerConfig
- type ScopeReconciliationController
- type ScopeReconciliationControllerConfig
- type TenantNamer
- type TenantSyncer
- type ThreatIntelRefreshController
- type ThreatModelRefreshController
- type ThreatModelRefreshControllerConfig
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type AgentHealthController ¶
type AgentHealthController struct {
// contains filtered or unexported fields
}
AgentHealthController periodically checks agent health and marks stale agents as offline. This is a K8s-style controller that reconciles the desired state (agents with recent heartbeats are online, agents without recent heartbeats are offline) with the actual state.
func NewAgentHealthController ¶
func NewAgentHealthController( agentRepo agent.Repository, auditService *auditapp.AuditService, config *AgentHealthControllerConfig, ) *AgentHealthController
NewAgentHealthController creates a new AgentHealthController.
auditService is optional (nil-safe): when provided, each agent that transitions to offline is recorded as an agent.disconnected event in the tamper-evident audit_logs so the Agent detail UI can show lifecycle history.
func (*AgentHealthController) Interval ¶
func (c *AgentHealthController) Interval() time.Duration
Interval returns the reconciliation interval.
func (*AgentHealthController) Name ¶
func (c *AgentHealthController) Name() string
Name returns the controller name.
type AgentHealthControllerConfig ¶
type AgentHealthControllerConfig struct {
// Interval is how often to run the health check.
// Default: 30 seconds.
Interval time.Duration
// StaleTimeout is how long since last heartbeat before marking an agent as offline.
// Default: 90 seconds (1.5x the typical heartbeat interval of 60s).
StaleTimeout time.Duration
// Logger for logging.
Logger *logger.Logger
}
AgentHealthControllerConfig configures the AgentHealthController.
type ApprovalExpirationController ¶ added in v0.1.2
type ApprovalExpirationController struct {
// contains filtered or unexported fields
}
ApprovalExpirationController auto-reopens findings whose risk acceptances have expired. It scans for approved approvals with an expires_at in the past, marks them as expired, and transitions the associated findings back to "confirmed" status.
func NewApprovalExpirationController ¶ added in v0.1.2
func NewApprovalExpirationController( approvalRepo vulnerability.ApprovalRepository, findingRepo vulnerability.FindingRepository, config *ApprovalExpirationControllerConfig, ) *ApprovalExpirationController
NewApprovalExpirationController creates a new ApprovalExpirationController.
func (*ApprovalExpirationController) Interval ¶ added in v0.1.2
func (c *ApprovalExpirationController) Interval() time.Duration
Interval returns the reconciliation interval.
func (*ApprovalExpirationController) Name ¶ added in v0.1.2
func (c *ApprovalExpirationController) Name() string
Name returns the controller name.
type ApprovalExpirationControllerConfig ¶ added in v0.1.2
type ApprovalExpirationControllerConfig struct {
// Interval is how often to run the expiration check.
// Default: 1 hour.
Interval time.Duration
// BatchSize is the maximum number of expired approvals to process per reconciliation.
// Default: 100.
BatchSize int
// Logger for logging.
Logger *logger.Logger
}
ApprovalExpirationControllerConfig configures the ApprovalExpirationController.
type AssetLifecycleController ¶ added in v0.2.1
type AssetLifecycleController struct {
// contains filtered or unexported fields
}
AssetLifecycleController fans the lifecycle worker out across tenants. Each tenant is handled serially to keep the implementation predictable — the worker's SQL is cheap (indexed scan) and a tenant with millions of assets is still sub-second. If we ever need parallelism we can add a tunable here without changing the controller's external interface.
func NewAssetLifecycleController ¶ added in v0.2.1
func NewAssetLifecycleController( worker *asset.AssetLifecycleWorker, tenantRepo tenant.Repository, config *AssetLifecycleControllerConfig, ) *AssetLifecycleController
NewAssetLifecycleController constructs the controller.
func (*AssetLifecycleController) Interval ¶ added in v0.2.1
func (c *AssetLifecycleController) Interval() time.Duration
Interval implements controller.Controller.
func (*AssetLifecycleController) Name ¶ added in v0.2.1
func (c *AssetLifecycleController) Name() string
Name implements controller.Controller.
func (*AssetLifecycleController) Reconcile ¶ added in v0.2.1
func (c *AssetLifecycleController) Reconcile(ctx context.Context) (int, error)
Reconcile iterates every tenant and invokes the worker against those that have opted in. Returns the total number of assets transitioned across all tenants so the reconciler metrics line up with actual work done.
Errors on individual tenants are logged but not returned — one broken tenant should not halt the pass for every other tenant. Unrecoverable failures (e.g. tenant repo lookup) do return an error so the controller runner can retry on the next tick.
type AssetLifecycleControllerConfig ¶ added in v0.2.1
type AssetLifecycleControllerConfig struct {
// Interval is how often to run. Default: 24h. Lifecycle is
// inherently slow-moving (asset thresholds are measured in days)
// so sub-daily cron frequency would only add DB churn without
// changing outcomes.
Interval time.Duration
// Logger for structured log output. Defaults to NewNop when nil.
Logger *logger.Logger
}
AssetLifecycleControllerConfig configures the daily stale-detection pass. The controller itself holds no per-tenant state; it drives the worker against every tenant on the cron cadence.
type AuditChainVerifyController ¶ added in v0.2.0
type AuditChainVerifyController struct {
// contains filtered or unexported fields
}
AuditChainVerifyController periodically walks audit_log_chain for every active tenant and surfaces breaks. The audit hash chain (migration 000154) is tamper-evident — hashes of prior rows feed into each new row — but the guarantee is only useful if someone actually runs VerifyChain. An admin endpoint exists (GET /api/v1/audit-logs/verify, audit_handler.go) but that is a pull path; a malicious insider who deletes rows at 02:00 UTC can sit undetected until someone hits that endpoint.
This controller closes the gap by running VerifyChain on a timer. On any break it:
- Logs at ERROR level with the tenant, chain_position, and reason so the SIEM can alert on the keyword "audit chain break".
- Exposes a metric via the Manager's metrics sink so alerting systems can threshold on sustained drift.
The FK on audit_log_chain.audit_log_id → audit_logs.id is ON DELETE RESTRICT (see 000154_audit_hash_chain.up.sql), so DB- level deletion is already blocked. This controller handles the out-of-band tamper cases: direct UPDATE of audit_logs fields, TRUNCATE, restore-from-different-backup, etc.
func NewAuditChainVerifyController ¶ added in v0.2.0
func NewAuditChainVerifyController( auditSvc *audit.AuditService, tenantRepo tenantdom.Repository, cfg *AuditChainVerifyControllerConfig, ) *AuditChainVerifyController
NewAuditChainVerifyController wires the controller. tenantRepo must expose ListActiveTenantIDs (verified at Reconcile time via a type assertion — we don't want a new domain method just to thread this through).
func (*AuditChainVerifyController) Interval ¶ added in v0.2.0
func (c *AuditChainVerifyController) Interval() time.Duration
Interval returns the reconciliation interval.
func (*AuditChainVerifyController) Name ¶ added in v0.2.0
func (c *AuditChainVerifyController) Name() string
Name returns the controller name.
func (*AuditChainVerifyController) Reconcile ¶ added in v0.2.0
func (c *AuditChainVerifyController) Reconcile(ctx context.Context) (int, error)
Reconcile walks every active tenant's chain once and returns the total number of tenants processed. Breaks are surfaced via the logger; the return int is the "work unit" counter the controller Manager uses for rate / health telemetry, not the break count.
type AuditChainVerifyControllerConfig ¶ added in v0.2.0
type AuditChainVerifyControllerConfig struct {
// Interval is how often to walk every active tenant's audit chain.
// Default: 1 hour. A malicious insider has at most (Interval + the
// duration of this run) before detection, so tune down if your
// compliance regime demands tighter MTTD for tamper events.
Interval time.Duration
// PerTenantLimit is the maximum chain entries walked per tenant per
// run. Matches the AuditService cap (10_000). Memory-bound; raise
// only after benchmarking.
PerTenantLimit int
Logger *logger.Logger
}
AuditChainVerifyControllerConfig configures AuditChainVerifyController.
type AuditRetentionController ¶
type AuditRetentionController struct {
// contains filtered or unexported fields
}
AuditRetentionController manages audit log retention. This is a compliance-critical controller that: 1. Deletes audit logs older than the retention period 2. Logs deletion activities for meta-audit purposes
The retention period should be configured based on compliance requirements: - GDPR: Typically 2-7 years depending on data type - SOC 2: At least 1 year - PCI DSS: At least 1 year - HIPAA: 6 years
IMPORTANT: Ensure proper backup before running this controller. Deleted audit logs cannot be recovered.
func NewAuditRetentionController ¶
func NewAuditRetentionController( auditRepo admin.AuditLogRepository, config *AuditRetentionControllerConfig, ) *AuditRetentionController
NewAuditRetentionController creates a new AuditRetentionController.
func (*AuditRetentionController) Interval ¶
func (c *AuditRetentionController) Interval() time.Duration
Interval returns the reconciliation interval.
func (*AuditRetentionController) Name ¶
func (c *AuditRetentionController) Name() string
Name returns the controller name.
type AuditRetentionControllerConfig ¶
type AuditRetentionControllerConfig struct {
// Interval is how often to run the retention check.
// Default: 24 hours (once a day).
Interval time.Duration
// RetentionDays is how long to keep audit logs.
// Logs older than this will be deleted.
// Default: 365 days (1 year).
RetentionDays int
// BatchSize is the maximum number of logs to delete in one batch.
// This prevents long-running transactions.
// Default: 10000.
BatchSize int
// DryRun if true, only counts logs that would be deleted without actually deleting.
// Useful for testing retention policies.
// Default: false.
DryRun bool
// Logger for logging.
Logger *logger.Logger
}
AuditRetentionControllerConfig configures the AuditRetentionController.
type CTEMIDRefreshController ¶ added in v0.6.0
type CTEMIDRefreshController struct {
// contains filtered or unexported fields
}
CTEMIDRefreshController periodically mirrors the CTEM-ID catalog from its external JSON feed into local reference storage, mirroring the threat-intel (EPSS/KEV) daily refresh. It is fail-open: a feed outage is logged and the reconcile returns success so the controller manager does not treat a transient upstream failure as a controller error.
func NewCTEMIDRefreshController ¶ added in v0.6.0
func NewCTEMIDRefreshController(service *ctemidapp.Service, log *logger.Logger) *CTEMIDRefreshController
NewCTEMIDRefreshController creates the controller.
func (*CTEMIDRefreshController) Interval ¶ added in v0.6.0
func (c *CTEMIDRefreshController) Interval() time.Duration
Interval returns 24 hours — daily refresh, matching threat-intel.
func (*CTEMIDRefreshController) Name ¶ added in v0.6.0
func (c *CTEMIDRefreshController) Name() string
Name returns the controller name.
type CertMonitorController ¶ added in v0.7.0
type CertMonitorController struct {
// contains filtered or unexported fields
}
CertMonitorController periodically runs the CT discovery sweep for every active tenant. For each tenant it queries crt.sh for that tenant's domain assets and emits ExposureEvents (subdomain_discovered + certificate_expiring).
A background controller (not the ingest hot path) is used because the sweep makes bounded, rate-limited outbound calls to a public feed and must not slow ingest. Each tenant is handled serially; a failure on one tenant is logged and skipped (fail-open) so it never halts the others. Only an unrecoverable tenant-list failure is returned so the runner retries next tick.
func NewCertMonitorController ¶ added in v0.7.0
func NewCertMonitorController( service *certmonitorapp.Service, tenantRepo tenant.Repository, config *CertMonitorControllerConfig, ) *CertMonitorController
NewCertMonitorController constructs the controller.
func (*CertMonitorController) Interval ¶ added in v0.7.0
func (c *CertMonitorController) Interval() time.Duration
Interval implements controller.Controller.
func (*CertMonitorController) Name ¶ added in v0.7.0
func (c *CertMonitorController) Name() string
Name implements controller.Controller.
func (*CertMonitorController) Reconcile ¶ added in v0.7.0
func (c *CertMonitorController) Reconcile(ctx context.Context) (int, error)
Reconcile runs the CT sweep for every active tenant. Returns the number of tenants that emitted at least one exposure. Per-tenant errors are logged and skipped; only a tenant-list failure is returned.
type CertMonitorControllerConfig ¶ added in v0.7.0
type CertMonitorControllerConfig struct {
// Interval is how often the sweep runs across all tenants. Default: 24h.
// CT data changes slowly (certs are issued/renewed on the order of days), so
// a daily cadence mirrors the threat-intel / CTEM-ID feed refreshes.
Interval time.Duration
// Logger for structured output. Defaults to NewNop when nil.
Logger *logger.Logger
// ModuleGuard, when set, skips tenants that have disabled the
// attack-surface module — cert-monitor is an external-discovery connector,
// so a tenant that turned attack-surface off should not have crt.sh queried
// on its behalf. Optional; nil means "never skip" (fully backward compatible).
ModuleGuard ModuleGuard
}
CertMonitorControllerConfig configures the periodic Certificate-Transparency discovery sweep.
type ControlChangePublisher ¶ added in v0.2.0
type ControlChangePublisher struct {
// contains filtered or unexported fields
}
ControlChangePublisher enqueues reclassify requests scoped to the assets a changed control protects.
func NewControlChangePublisher ¶ added in v0.2.0
func NewControlChangePublisher(q ReclassifyQueue, log *logger.Logger) *ControlChangePublisher
NewControlChangePublisher wires the queue.
func (*ControlChangePublisher) PublishAssetReclassify ¶ added in v0.6.0
func (p *ControlChangePublisher) PublishAssetReclassify( ctx context.Context, tenantID shared.ID, assetIDs []shared.ID, kind ReclassifyReasonKind, reason string, )
PublishAssetReclassify enqueues an asset-scoped reclassify request under an explicit reason kind. Generalizes PublishChange (which is always ReasonControlChange) so other producers — e.g. AI triage completion (ReasonAITriage) — drive the same asset-scoped sweep. Errors are logged, never returned: a failed enqueue must not roll back the write that triggered it.
func (*ControlChangePublisher) PublishChange ¶ added in v0.2.0
func (p *ControlChangePublisher) PublishChange( ctx context.Context, tenantID shared.ID, assetIDs []shared.ID, reason string, )
PublishChange enqueues a control-change reclassify request. Errors are logged but NOT returned — a failed enqueue must not roll back the control write that triggered it.
func (*ControlChangePublisher) PublishTenantChange ¶ added in v0.6.0
func (p *ControlChangePublisher) PublishTenantChange( ctx context.Context, tenantID shared.ID, kind ReclassifyReasonKind, reason string, )
PublishTenantChange enqueues a WHOLE-TENANT reclassify sweep (no asset scope), used when a change affects every finding in the tenant rather than a known set of assets — e.g. a priority override rule was created, updated, or deleted. The reclassifier treats an empty AssetIDs as "page the tenant's open findings and reclassify each". Errors are logged, never returned — a failed enqueue must not roll back the mutation that triggered it.
type ControlTestSchedulerConfig ¶ added in v0.1.7
type ControlTestSchedulerConfig struct {
// Interval is how often the scheduler runs (default: 24 hours).
Interval time.Duration
// StaleDays is the number of days without a test before a control test
// is considered overdue and reset to "untested" (default: 30).
StaleDays int
// BatchSize is the maximum number of overdue tests to process per cycle (default: 500).
BatchSize int
// Logger is passed by the controller manager.
Logger *logger.Logger
// ModuleGuard, when set, lets the sweep skip tenants that have not
// subscribed to the control-testing module. Optional.
ModuleGuard ModuleGuard
}
ControlTestSchedulerConfig configures the controller.
type ControlTestSchedulerController ¶ added in v0.1.7
type ControlTestSchedulerController struct {
// contains filtered or unexported fields
}
ControlTestSchedulerController automatically marks control tests as overdue when they have not been run within the configured stale window.
Design:
- Runs every 24 hours (daily sweep).
- Any control test not tested for >StaleDays days is reset to "untested" so it surfaces in the Detection Coverage dashboard.
- Never blocks other operations — failures are logged and skipped.
func NewControlTestSchedulerController ¶ added in v0.1.7
func NewControlTestSchedulerController( repo simulation.ControlTestRepository, cfg *ControlTestSchedulerConfig, ) *ControlTestSchedulerController
NewControlTestSchedulerController creates a new controller.
func (*ControlTestSchedulerController) Interval ¶ added in v0.1.7
func (c *ControlTestSchedulerController) Interval() time.Duration
Interval implements Controller.
func (*ControlTestSchedulerController) Name ¶ added in v0.1.7
func (c *ControlTestSchedulerController) Name() string
Name implements Controller.
type Controller ¶
type Controller interface {
// Name returns the unique name of this controller.
Name() string
// Interval returns how often this controller should run.
Interval() time.Duration
// Reconcile performs the reconciliation logic.
// It should be idempotent - running multiple times should have the same effect.
// Returns the number of items processed and any error encountered.
Reconcile(ctx context.Context) (int, error)
}
Controller defines the interface for a reconciliation loop controller. Controllers are responsible for maintaining a specific aspect of system state.
type CoverageScheduler ¶ added in v0.3.0
type CoverageScheduler struct {
// contains filtered or unexported fields
}
CoverageScheduler is the live controller for RFC-007 license-aware rolling scan coverage. Each tick it walks every tenant's coverage-enabled Tenable integration, sizes a batch against the engine's license headroom, dispatches it to a runner, and advances the rotation cursor.
The pure rotation logic lives in internal/app/scancoverage (planner + scheduler); this controller is the composition root that binds it to real repositories. It implements scancoverage.CoverageSource itself (the integration-listing half) and delegates the candidate/cursor half to the coverage repository.
SCOPE: today the controller only drives UNLIMITED engines (Nessus Pro). Capped engines (Tenable.sc) are skipped with a log line until active-IP accounting + reclaim-ACK ship (Phase 3.5) — dispatching them without that accounting could exceed the license, which we refuse to risk.
func NewCoverageScheduler ¶ added in v0.3.0
func NewCoverageScheduler( integrations integrationLister, coverage coverageRepo, dispatcher scancoverage.BatchDispatcher, config *CoverageSchedulerConfig, ) *CoverageScheduler
NewCoverageScheduler builds a CoverageScheduler.
func (*CoverageScheduler) ActiveIPs ¶ added in v0.3.0
ActiveIPs delegates to the coverage repository.
func (*CoverageScheduler) Interval ¶ added in v0.3.0
func (c *CoverageScheduler) Interval() time.Duration
func (*CoverageScheduler) ListActiveCoverage ¶ added in v0.3.0
func (c *CoverageScheduler) ListActiveCoverage(ctx context.Context) ([]scancoverage.CoverageConfig, error)
ListActiveCoverage returns every tenant's coverage-enabled, unlimited-engine Tenable integration as a CoverageConfig. Capped engines are skipped (see the type doc). It pages through integrations cross-tenant.
func (*CoverageScheduler) ListCandidates ¶ added in v0.3.0
func (c *CoverageScheduler) ListCandidates(ctx context.Context, tenantID shared.ID, limit int) ([]scancoverage.Candidate, error)
ListCandidates delegates to the coverage repository.
func (*CoverageScheduler) MarkDispatched ¶ added in v0.3.0
func (c *CoverageScheduler) MarkDispatched(ctx context.Context, rec scancoverage.DispatchRecord) error
MarkDispatched delegates to the coverage repository.
func (*CoverageScheduler) Name ¶ added in v0.3.0
func (c *CoverageScheduler) Name() string
type CoverageSchedulerConfig ¶ added in v0.3.0
type CoverageSchedulerConfig struct {
// Interval is how often a rotation pass runs. Default: 5 minutes.
Interval time.Duration
// CandidateLimit caps candidates loaded per tenant per cycle. Default: 5000.
CandidateLimit int
// IntegrationPageSize is the page size when listing integrations. Default: 100.
IntegrationPageSize int
Logger *logger.Logger
}
CoverageSchedulerConfig configures the CoverageScheduler.
type DataExpirationController ¶ added in v0.1.2
type DataExpirationController struct {
// contains filtered or unexported fields
}
DataExpirationController handles periodic expiration of stale data:
- Suppression rules past their expires_at
- Scope exclusions past their expires_at
- Audit logs older than the retention period
Without this controller, expired suppression rules and scope exclusions remain in 'active'/'approved' status indefinitely, and audit logs accumulate without bounds.
func NewDataExpirationController ¶ added in v0.1.2
func NewDataExpirationController( suppressionRepo suppression.Repository, exclusionRepo scope.ExclusionRepository, auditRepo audit.Repository, config *DataExpirationControllerConfig, ) *DataExpirationController
NewDataExpirationController creates a new DataExpirationController.
func (*DataExpirationController) Interval ¶ added in v0.1.2
func (c *DataExpirationController) Interval() time.Duration
Interval returns the reconciliation interval.
func (*DataExpirationController) Name ¶ added in v0.1.2
func (c *DataExpirationController) Name() string
Name returns the controller name.
type DataExpirationControllerConfig ¶ added in v0.1.2
type DataExpirationControllerConfig struct {
// Interval is how often to run the expiration check.
// Default: 1 hour.
Interval time.Duration
// AuditRetentionDays is how long to keep audit logs.
// Logs older than this will be deleted.
// Default: 365 days (1 year).
AuditRetentionDays int
// Logger for logging.
Logger *logger.Logger
}
DataExpirationControllerConfig configures the DataExpirationController.
type DefectDojoSyncController ¶ added in v0.4.0
type DefectDojoSyncController struct {
// contains filtered or unexported fields
}
DefectDojoSyncController periodically pulls connected DefectDojo integrations that are due (RFC-013 Phase 2c), making the co-existence sync hands-off. Each integration syncs under its own tenant; success/failure advances next_sync_at so a failing one retries next interval instead of hammering.
func NewDefectDojoSyncController ¶ added in v0.4.0
func NewDefectDojoSyncController(store IntegrationSyncStore, syncer TenantSyncer, log *logger.Logger) *DefectDojoSyncController
NewDefectDojoSyncController wires the controller. Default cadence 5m, batch 20.
func (*DefectDojoSyncController) Interval ¶ added in v0.4.0
func (c *DefectDojoSyncController) Interval() time.Duration
Interval implements Controller.
func (*DefectDojoSyncController) Name ¶ added in v0.4.0
func (c *DefectDojoSyncController) Name() string
Name implements Controller.
type DomainReverifyController ¶ added in v0.4.0
type DomainReverifyController struct {
// contains filtered or unexported fields
}
DomainReverifyController periodically re-verifies domains that were previously proven via DNS TXT. If a domain's TXT record has since disappeared (a lapsed or hijacked domain), it is downgraded to failed so it loses SSO JIT authority (fail-closed).
func NewDomainReverifyController ¶ added in v0.4.0
func NewDomainReverifyController( service *domainverify.Service, config *DomainReverifyControllerConfig, ) *DomainReverifyController
NewDomainReverifyController creates a new DomainReverifyController.
func (*DomainReverifyController) Interval ¶ added in v0.4.0
func (c *DomainReverifyController) Interval() time.Duration
Interval returns the reconciliation interval.
func (*DomainReverifyController) Name ¶ added in v0.4.0
func (c *DomainReverifyController) Name() string
Name returns the controller name.
type DomainReverifyControllerConfig ¶ added in v0.4.0
type DomainReverifyControllerConfig struct {
// Interval is how often the re-verify sweep runs. Default: 12h.
Interval time.Duration
// Staleness is how long since the last check before a verified domain is
// re-verified. Default: 24h.
Staleness time.Duration
// BatchSize caps rows processed per sweep. Default: 100.
BatchSize int
// Logger for logging.
Logger *logger.Logger
}
DomainReverifyControllerConfig configures the DomainReverifyController.
type GraphEnrichmentController ¶ added in v0.4.0
type GraphEnrichmentController struct {
// contains filtered or unexported fields
}
GraphEnrichmentController periodically infers high-confidence asset-graph edges (Exposes host→service, RunsOn application→host) from data scanners already ingest, so the attack-path / exposure-chain / reachability engines have edges beyond DNS to traverse over historical data.
A background controller (rather than the ingest hot path) is used because enrichment reasons over the WHOLE tenant graph — it must also enrich assets ingested before this feature existed, and it must not slow ingest. The pass is idempotent and each tenant is handled serially; a failure on one tenant never halts the others.
func NewGraphEnrichmentController ¶ added in v0.4.0
func NewGraphEnrichmentController( enricher graphEnricher, tenantRepo tenant.Repository, config *GraphEnrichmentControllerConfig, ) *GraphEnrichmentController
NewGraphEnrichmentController constructs the controller.
func (*GraphEnrichmentController) Interval ¶ added in v0.4.0
func (c *GraphEnrichmentController) Interval() time.Duration
Interval implements controller.Controller.
func (*GraphEnrichmentController) Name ¶ added in v0.4.0
func (c *GraphEnrichmentController) Name() string
Name implements controller.Controller.
func (*GraphEnrichmentController) Reconcile ¶ added in v0.4.0
func (c *GraphEnrichmentController) Reconcile(ctx context.Context) (int, error)
Reconcile enriches the asset graph for every active tenant. Returns the total number of edges auto-created across all tenants. Per-tenant errors are logged and skipped; only an unrecoverable tenant-list failure is returned so the runner retries next tick.
type GraphEnrichmentControllerConfig ¶ added in v0.4.0
type GraphEnrichmentControllerConfig struct {
// Interval is how often to run. Default: 1h. Enrichment is derived from
// slow-moving inventory data, so a sub-hourly cadence would only add DB
// churn without changing outcomes. The pass is idempotent (edges use
// ON CONFLICT DO NOTHING), so re-running is cheap and safe.
Interval time.Duration
// Logger for structured output. Defaults to NewNop when nil.
Logger *logger.Logger
// ModuleGuard, when set, skips tenants that have disabled the
// attack-surface module — graph enrichment feeds the exposure-chain /
// attack-path engines, so a tenant that turned attack-surface off need not
// pay for edge inference. Existing edges are untouched (idempotent inserts);
// only NEW inference is skipped. Optional; nil means "never skip".
ModuleGuard ModuleGuard
}
GraphEnrichmentControllerConfig configures the periodic asset-graph enrichment pass.
type IngestJobProcessor ¶ added in v0.3.0
type IngestJobProcessor interface {
Process(ctx context.Context, job *ingestjob.Job) ([]byte, error)
}
IngestJobProcessor processes a claimed job (parse payload + ingest) and returns the result counts to persist on completion.
type IngestJobQueue ¶ added in v0.3.0
type IngestJobQueue interface {
ClaimBatch(ctx context.Context, workerID string, limit int) ([]*ingestjob.Job, error)
Complete(ctx context.Context, id ingestjob.ID, result []byte) error
Fail(ctx context.Context, id ingestjob.ID, errMsg string, availableAt time.Time, dead bool) error
ReleaseStale(ctx context.Context, olderThan time.Duration) (int, error)
CountPending(ctx context.Context) (int, error)
}
IngestJobQueue is the slice of the ingest-job repository the worker needs.
type IngestWorkerController ¶ added in v0.3.0
type IngestWorkerController struct {
// contains filtered or unexported fields
}
IngestWorkerController drains the ingest_jobs queue: it reclaims stale jobs, claims pending ones (bounded), and runs each through the ingest pipeline, marking them completed or failed (with backoff / dead). Bounded concurrency (one job at a time per replica, BatchSize/MaxPerTick caps) is the core backpressure that protects the DB pool under heavy ingest load.
func NewIngestWorkerController ¶ added in v0.3.0
func NewIngestWorkerController(queue IngestJobQueue, processor IngestJobProcessor, cfg *IngestWorkerControllerConfig) *IngestWorkerController
NewIngestWorkerController constructs the controller, applying defaults.
func (*IngestWorkerController) Interval ¶ added in v0.3.0
func (c *IngestWorkerController) Interval() time.Duration
Interval implements controller.Controller.
func (*IngestWorkerController) Name ¶ added in v0.3.0
func (c *IngestWorkerController) Name() string
Name implements controller.Controller.
func (*IngestWorkerController) Reconcile ¶ added in v0.3.0
func (c *IngestWorkerController) Reconcile(ctx context.Context) (int, error)
Reconcile reclaims stale jobs then drains pending jobs up to MaxPerTick.
func (*IngestWorkerController) ReconcileTimeout ¶ added in v0.4.0
func (c *IngestWorkerController) ReconcileTimeout() time.Duration
ReconcileTimeout implements controller.ReconcileTimeouter. The short poll Interval is only how often we LOOK for work; a drain cycle then runs a claimed batch (up to MaxPerTick jobs) through the full ingest pipeline — parsing a report and persisting its findings — which routinely takes far longer than the interval. Bounding the reconcile at the interval would cancel every non-trivial batch mid-flight ("context deadline exceeded") and leave jobs to be reclaimed as stale. Grant the batch the lease window it already holds exclusively.
type IngestWorkerControllerConfig ¶ added in v0.3.0
type IngestWorkerControllerConfig struct {
// Interval between drain cycles. Default: 2s.
Interval time.Duration
// BatchSize is how many jobs to claim per ClaimBatch. Default: 5.
BatchSize int
// MaxPerTick caps how many jobs one Reconcile drains so a huge backlog
// doesn't monopolize the goroutine forever. Default: 50.
MaxPerTick int
// LeaseTimeout: processing jobs whose lock is older than this are reclaimed
// (worker crash recovery). Default: 5m.
LeaseTimeout time.Duration
// WorkerID identifies this replica's worker in locked_by. Default: "ingest-worker".
WorkerID string
Logger *logger.Logger
}
IngestWorkerControllerConfig configures the async-ingest worker (RFC-005).
type IntegrationSyncStore ¶ added in v0.4.0
type IntegrationSyncStore interface {
ListDueForSync(ctx context.Context, provider integration.Provider, now time.Time, limit int) ([]*integration.Integration, error)
Update(ctx context.Context, i *integration.Integration) error
}
IntegrationSyncStore is the narrow store the scheduler needs: find due integrations and persist their sync tracking. Satisfied by *postgres.IntegrationRepository.
type JobRecoveryController ¶
type JobRecoveryController struct {
// contains filtered or unexported fields
}
JobRecoveryController recovers stuck jobs and re-queues them. This is a K8s-style controller that ensures jobs don't get lost if an agent goes offline or fails to complete them.
The controller performs two main tasks:
- Recover stuck jobs: Return jobs to the queue if they've been assigned but haven't progressed (agent went offline or crashed) — both platform jobs and tenant commands
- Clean up: Mark orphaned jobs as failed if they exceed retry limit
Expiry is NOT this controller's job — see the note in Reconcile; app/command.ExpirationChecker owns it, because expiry has to notify the owning pipeline run and a raw UPDATE here cannot.
func NewJobRecoveryController ¶
func NewJobRecoveryController( commandRepo command.Repository, config *JobRecoveryControllerConfig, ) *JobRecoveryController
NewJobRecoveryController creates a new JobRecoveryController.
func (*JobRecoveryController) Interval ¶
func (c *JobRecoveryController) Interval() time.Duration
Interval returns the reconciliation interval.
func (*JobRecoveryController) Name ¶
func (c *JobRecoveryController) Name() string
Name returns the controller name.
type JobRecoveryControllerConfig ¶
type JobRecoveryControllerConfig struct {
// Interval is how often to run the job recovery check.
// Default: 60 seconds.
Interval time.Duration
// StuckThresholdMinutes is how long a job can be in acknowledged/running state
// without progress before being considered stuck.
// Default: 30 minutes.
StuckThresholdMinutes int
// TenantStuckThresholdMinutes is how long a tenant command can be assigned
// to an agent without being picked up before being reassigned.
// Default: 10 minutes (shorter than platform jobs as tenant agents poll more frequently).
TenantStuckThresholdMinutes int
// MaxRetries is the maximum number of retry attempts for a job.
// After this many retries, the job will be marked as failed.
// Default: 3.
MaxRetries int
// Logger for logging.
Logger *logger.Logger
}
JobRecoveryControllerConfig configures the JobRecoveryController.
type Manager ¶
type Manager struct {
// contains filtered or unexported fields
}
Manager manages multiple controllers, running them in parallel goroutines.
func NewManager ¶
func NewManager(cfg *ManagerConfig) *Manager
NewManager creates a new controller manager.
func (*Manager) ControllerCount ¶
ControllerCount returns the number of registered controllers.
func (*Manager) ControllerNames ¶
ControllerNames returns the names of all registered controllers.
func (*Manager) Register ¶
func (m *Manager) Register(c Controller)
Register adds a controller to the manager.
type ManagerConfig ¶
type ManagerConfig struct {
// Metrics collector (optional)
Metrics Metrics
// Logger (required)
Logger *logger.Logger
}
ManagerConfig configures the controller manager.
type Metrics ¶
type Metrics interface {
// RecordReconcile records a reconciliation run.
RecordReconcile(controller string, itemsProcessed int, duration time.Duration, err error)
// SetControllerRunning sets whether a controller is running.
SetControllerRunning(controller string, running bool)
// IncrementReconcileErrors increments the error counter.
IncrementReconcileErrors(controller string)
// SetLastReconcileTime sets the last reconcile timestamp.
SetLastReconcileTime(controller string, t time.Time)
}
Metrics defines the interface for controller metrics collection.
type ModuleGuard ¶ added in v0.6.0
type ModuleGuard interface {
TenantDisabledModules(ctx context.Context, tenantID string) map[string]bool
}
ModuleGuard answers "which modules has this tenant disabled" so a per-tenant controller loop can cheaply skip work for a module the tenant did not subscribe to. Satisfied by *app.ModuleService (its TenantDisabledModules).
Fail-open by construction: the underlying service returns an empty set when a tenant has no bundle subscription, so a guard never skips work for existing tenants — the compute guard is a strict no-op unless a tenant has explicitly subsetted its modules.
type NoopMetrics ¶
type NoopMetrics struct{}
NoopMetrics is a no-op implementation of Metrics for testing.
func (*NoopMetrics) IncrementReconcileErrors ¶
func (m *NoopMetrics) IncrementReconcileErrors(controller string)
IncrementReconcileErrors does nothing.
func (*NoopMetrics) RecordReconcile ¶
func (m *NoopMetrics) RecordReconcile(controller string, itemsProcessed int, duration time.Duration, err error)
RecordReconcile does nothing.
func (*NoopMetrics) SetControllerRunning ¶
func (m *NoopMetrics) SetControllerRunning(controller string, running bool)
SetControllerRunning does nothing.
func (*NoopMetrics) SetLastReconcileTime ¶
func (m *NoopMetrics) SetLastReconcileTime(controller string, t time.Time)
SetLastReconcileTime does nothing.
type OwnerResolutionController ¶ added in v0.2.0
type OwnerResolutionController struct {
// contains filtered or unexported fields
}
OwnerResolutionController periodically resolves asset ownership by matching owner_ref (email/username text) to actual user accounts.
When a scanner ingests an asset, it may set owner_ref (e.g., "alice@example.com") but cannot know the internal user UUID. This controller finds those assets and populates owner_id from the users table.
Runs every 30 minutes.
func NewOwnerResolutionController ¶ added in v0.2.0
func NewOwnerResolutionController(db *sql.DB, log *logger.Logger) *OwnerResolutionController
NewOwnerResolutionController creates a new controller.
func (*OwnerResolutionController) Interval ¶ added in v0.2.0
func (c *OwnerResolutionController) Interval() time.Duration
Interval returns 30 minutes.
func (*OwnerResolutionController) Name ¶ added in v0.2.0
func (c *OwnerResolutionController) Name() string
Name returns the controller name.
type PriorityAuditRetentionConfig ¶ added in v0.2.0
type PriorityAuditRetentionConfig struct {
// Interval between runs (default 24h).
Interval time.Duration
// RetentionDays — rows older than this are deleted (default 180).
RetentionDays int
// DryRun skips deletion and only reports count.
DryRun bool
// Logger for logging.
Logger *logger.Logger
}
PriorityAuditRetentionConfig configures the controller.
type PriorityAuditRetentionController ¶ added in v0.2.0
type PriorityAuditRetentionController struct {
// contains filtered or unexported fields
}
PriorityAuditRetentionController implements the background controller contract (Name / Interval / Reconcile).
func NewPriorityAuditRetentionController ¶ added in v0.2.0
func NewPriorityAuditRetentionController( repo PriorityAuditRetentionStore, config *PriorityAuditRetentionConfig, ) *PriorityAuditRetentionController
NewPriorityAuditRetentionController constructs the controller with sensible defaults for any zero-valued config fields.
func (*PriorityAuditRetentionController) Interval ¶ added in v0.2.0
func (c *PriorityAuditRetentionController) Interval() time.Duration
Interval returns the reconciliation interval.
func (*PriorityAuditRetentionController) Name ¶ added in v0.2.0
func (c *PriorityAuditRetentionController) Name() string
Name returns the controller name.
type PriorityAuditRetentionStore ¶ added in v0.2.0
type PriorityAuditRetentionStore interface {
CountOlderThan(ctx context.Context, before time.Time) (int64, error)
DeleteOlderThan(ctx context.Context, before time.Time) (int64, error)
}
PriorityAuditRetentionStore is the subset of PriorityAuditRepository that this controller needs. Defined locally so we don't depend on the app layer.
type PriorityReclassifyConfig ¶ added in v0.2.0
type PriorityReclassifyConfig struct {
// Interval between sweep ticks. Default 5m.
Interval time.Duration
// BatchSize is the max number of requests drained per tick.
// Default 64.
BatchSize int
// MaxRetries bounds how many times a failed request is re-enqueued
// before it is dropped (with a warning). Default 3.
MaxRetries int
// Logger (optional; defaults to no-op).
Logger *logger.Logger
}
PriorityReclassifyConfig configures the sweep controller.
type PriorityReclassifyController ¶ added in v0.2.0
type PriorityReclassifyController struct {
// contains filtered or unexported fields
}
PriorityReclassifyController drains the queue and dispatches each request to the Reclassifier.
func NewPriorityReclassifyController ¶ added in v0.2.0
func NewPriorityReclassifyController( queue ReclassifyQueue, reclassifier Reclassifier, cfg *PriorityReclassifyConfig, ) *PriorityReclassifyController
NewPriorityReclassifyController wires the controller.
func (*PriorityReclassifyController) Interval ¶ added in v0.2.0
func (c *PriorityReclassifyController) Interval() time.Duration
Interval returns the sweep interval.
func (*PriorityReclassifyController) Name ¶ added in v0.2.0
func (c *PriorityReclassifyController) Name() string
Name returns the controller name.
func (*PriorityReclassifyController) Reconcile ¶ added in v0.2.0
func (c *PriorityReclassifyController) Reconcile(ctx context.Context) (int, error)
Reconcile drains up to BatchSize requests from the queue and applies each. Returns the total number of findings re-examined across all drained requests (for metrics).
type PriorityReclassifySweepConfig ¶ added in v0.6.0
type PriorityReclassifySweepConfig struct {
// Interval between sweeps. Default 12h. Backfill + drift correction, so a
// low frequency is deliberate.
Interval time.Duration
// Logger (optional; defaults to no-op).
Logger *logger.Logger
}
PriorityReclassifySweepConfig configures the periodic sweep producer.
type PriorityReclassifySweepController ¶ added in v0.6.0
type PriorityReclassifySweepController struct {
// contains filtered or unexported fields
}
PriorityReclassifySweepController is the periodic *producer* half of the priority-reclassification pipeline. PriorityReclassifyController is the consumer — it drains the queue but nothing periodically fills it, so findings that no discrete producer event touches (never-classified rows with priority_class IS NULL, or slow daily EPSS drift) would never be reclassified.
This controller closes that gap: on an interval it lists every active tenant and enqueues ONE whole-tenant ReclassifyRequest per tenant (empty AssetIDs → the Reclassifier expands it to the tenant's open findings' distinct assets). The consumer then does the work at its own cadence.
Producer and consumer are deliberately separate controllers: the producer only enqueues (cheap, fast) and the consumer drains in bounded batches, so a slow reclassify never blocks enqueue and vice-versa.
Interval is intentionally low-frequency (default 12h): this is drift correction + backfill, not real-time. Real-time transitions already flow through the discrete producers (control-change, KEV/EPSS refresh). A high frequency would re-classify the whole corpus constantly for no benefit.
func NewPriorityReclassifySweepController ¶ added in v0.6.0
func NewPriorityReclassifySweepController( queue ReclassifyQueue, tenantRepo tenant.Repository, cfg *PriorityReclassifySweepConfig, ) *PriorityReclassifySweepController
NewPriorityReclassifySweepController wires the producer. A nil queue makes Reconcile a no-op (the whole pipeline is optional in some deployments).
func (*PriorityReclassifySweepController) Interval ¶ added in v0.6.0
func (c *PriorityReclassifySweepController) Interval() time.Duration
Interval returns the sweep interval.
func (*PriorityReclassifySweepController) Name ¶ added in v0.6.0
func (c *PriorityReclassifySweepController) Name() string
Name returns the controller name.
func (*PriorityReclassifySweepController) Reconcile ¶ added in v0.6.0
func (c *PriorityReclassifySweepController) Reconcile(ctx context.Context) (int, error)
Reconcile enqueues one whole-tenant ReclassifyRequest per active tenant. Returns the number of tenants enqueued. Best-effort: a failed enqueue for one tenant is logged and does not stop the rest. Only an unrecoverable tenant-list failure is returned (so the runner retries next tick).
type PrometheusMetrics ¶
type PrometheusMetrics struct {
// contains filtered or unexported fields
}
PrometheusMetrics implements the Metrics interface using Prometheus.
func NewPrometheusMetrics ¶
func NewPrometheusMetrics(namespace string) *PrometheusMetrics
NewPrometheusMetrics creates a new PrometheusMetrics.
func (*PrometheusMetrics) IncrementReconcileErrors ¶
func (m *PrometheusMetrics) IncrementReconcileErrors(controller string)
IncrementReconcileErrors increments the error counter.
func (*PrometheusMetrics) RecordReconcile ¶
func (m *PrometheusMetrics) RecordReconcile(controller string, itemsProcessed int, duration time.Duration, err error)
RecordReconcile records a reconciliation run.
func (*PrometheusMetrics) SetControllerRunning ¶
func (m *PrometheusMetrics) SetControllerRunning(controller string, running bool)
SetControllerRunning sets whether a controller is running.
func (*PrometheusMetrics) SetLastReconcileTime ¶
func (m *PrometheusMetrics) SetLastReconcileTime(controller string, t time.Time)
SetLastReconcileTime sets the last reconcile timestamp.
type QueuePriorityController ¶
type QueuePriorityController struct {
// contains filtered or unexported fields
}
QueuePriorityController periodically recalculates queue priorities for platform jobs. This ensures fair scheduling across tenants by adjusting priorities based on: - Tenant's plan tier (higher tiers get base priority boost) - Job age (older jobs get priority bonus to prevent starvation) - Tenant's current queue depth (tenants with fewer jobs get slight boost)
The priority calculation is done in the database for efficiency: new_priority = plan_base_priority + (wait_time_minutes * age_bonus_per_minute)
This is a soft-priority system - higher priority jobs are processed first, but no tenant can completely starve others.
func NewQueuePriorityController ¶
func NewQueuePriorityController( commandRepo command.Repository, config *QueuePriorityControllerConfig, ) *QueuePriorityController
NewQueuePriorityController creates a new QueuePriorityController.
func (*QueuePriorityController) Interval ¶
func (c *QueuePriorityController) Interval() time.Duration
Interval returns the reconciliation interval.
func (*QueuePriorityController) Name ¶
func (c *QueuePriorityController) Name() string
Name returns the controller name.
type QueuePriorityControllerConfig ¶
type QueuePriorityControllerConfig struct {
// Interval is how often to recalculate queue priorities.
// Default: 60 seconds.
Interval time.Duration
// Logger for logging.
Logger *logger.Logger
}
QueuePriorityControllerConfig configures the QueuePriorityController.
type Reclassifier ¶ added in v0.2.0
type Reclassifier interface {
// ReclassifyForRequest processes a single request. Returns the
// number of findings re-examined (not necessarily changed — a
// sweep that re-confirms the same class is still "work done").
ReclassifyForRequest(ctx context.Context, req ReclassifyRequest) (int, error)
}
Reclassifier applies one request: it loads the matching open findings and invokes the PriorityClassificationService on them. Kept as a narrow interface so the controller has no knowledge of the app-layer service or its repo dependencies.
type ReclassifyQueue ¶ added in v0.2.0
type ReclassifyQueue interface {
// Enqueue adds a reclassify request. MUST be safe for concurrent use.
Enqueue(ctx context.Context, req ReclassifyRequest) error
// DequeueBatch pops up to `max` requests. An empty slice (no error)
// means "nothing to do this tick". Implementations should return
// quickly (non-blocking).
DequeueBatch(ctx context.Context, max int) ([]ReclassifyRequest, error)
}
ReclassifyQueue is the minimal contract for the in/out queue. Implementations may be Redis lists, Postgres advisory-locked rows, or an in-memory channel for tests.
type ReclassifyReasonKind ¶ added in v0.2.0
type ReclassifyReasonKind string
ReclassifyReasonKind enumerates why a sweep was enqueued.
const ( ReasonEPSSRefresh ReclassifyReasonKind = "epss_refresh" ReasonKEVRefresh ReclassifyReasonKind = "kev_refresh" ReasonRuleChanged ReclassifyReasonKind = "rule_changed" ReasonControlChange ReclassifyReasonKind = "control_change" ReasonAssetChange ReclassifyReasonKind = "asset_change" ReasonManual ReclassifyReasonKind = "manual" // ReasonAITriage is enqueued when an AI triage COMPLETES for a finding, so a // high-confidence "likely false positive" verdict can de-escalate that // finding's priority without waiting for the next periodic sweep. ReasonAITriage ReclassifyReasonKind = "ai_triage" // ReasonPeriodicSweep is enqueued by PriorityReclassifySweepController on a // timer — one whole-tenant request per active tenant — to backfill // never-classified findings and correct slow drift (daily EPSS movement) // that no discrete producer event covers. ReasonPeriodicSweep ReclassifyReasonKind = "periodic_sweep" )
type ReclassifyRequest ¶ added in v0.2.0
type ReclassifyRequest struct {
TenantID shared.ID
Reason ReclassifyReasonKind
CVEIDs []string
AssetIDs []shared.ID
RuleID *shared.ID
EnqueueAt time.Time
// Attempts counts how many times this request has been dispatched and
// failed. Used to bound re-enqueue retries so a poison request can't loop
// forever. Zero on first enqueue.
Attempts int
}
ReclassifyRequest describes one unit of sweep work.
Scope dimensions (all optional; nil/empty = broadest match within tenant):
- CVEIDs — only findings matching these CVEs (typical EPSS/KEV path).
- AssetIDs — only findings on these assets (typical control/asset path).
- RuleID — evaluated by the running service against each finding.
Batching is the caller's responsibility — a giant EPSS refresh should split into per-tenant requests; the controller treats each request atomically.
type ReconcileTimeouter ¶ added in v0.4.0
ReconcileTimeouter is an optional Controller extension. By default a reconcile is bounded by the controller's tick Interval, which suits pollers whose per-run work is trivial. A controller whose single run can legitimately take much longer than the interval — e.g. the ingest worker polls every few seconds but must run a claimed batch through the full ingest pipeline — implements this to request a larger per-run timeout. A non-positive value falls back to the interval. Controllers that don't implement it are unaffected.
type RemediationProgressController ¶ added in v0.3.0
type RemediationProgressController struct {
// contains filtered or unexported fields
}
RemediationProgressController periodically refreshes finding counts for every non-terminal remediation campaign and auto-completes any whose findings are all resolved. Without it, campaign progress would only update when a campaign is fetched individually — list views and auto-complete would lag reality.
func NewRemediationProgressController ¶ added in v0.3.0
func NewRemediationProgressController(svc campaignProgressReconciler, interval time.Duration, log *logger.Logger) *RemediationProgressController
NewRemediationProgressController creates the controller. A non-positive interval falls back to 30 minutes.
func (*RemediationProgressController) Interval ¶ added in v0.3.0
func (c *RemediationProgressController) Interval() time.Duration
Interval returns how often the reconcile runs.
func (*RemediationProgressController) Name ¶ added in v0.3.0
func (c *RemediationProgressController) Name() string
Name returns the controller name.
type ReportEmailer ¶ added in v0.3.0
type ReportEmailer interface {
SendReport(ctx context.Context, tenantID string, to []string, subject, htmlBody string) error
IsConfigured() bool
}
ReportEmailer delivers a rendered HTML report to recipients.
type ReportScheduleStore ¶ added in v0.3.0
type ReportScheduleStore interface {
ListDue(ctx context.Context, now time.Time) ([]*reportschedule.ReportSchedule, error)
Update(ctx context.Context, s *reportschedule.ReportSchedule) error
}
ReportScheduleStore is the persistence surface the scheduler needs.
type ReportScheduler ¶ added in v0.3.0
type ReportScheduler struct {
// contains filtered or unexported fields
}
ReportScheduler runs due report schedules: render → deliver → record next run. This is the controller that was missing — schedules could be created but never executed because nothing invoked ListDue().
func NewReportScheduler ¶ added in v0.3.0
func NewReportScheduler(store ReportScheduleStore, stats ReportStatsSource, emailer ReportEmailer, tenants TenantNamer, moduleGuard ModuleGuard, cfg ReportSchedulerConfig, log *logger.Logger) *ReportScheduler
NewReportScheduler builds the controller. moduleGuard is optional (nil = never skip); when set, schedules for tenants without the reports module are skipped.
func (*ReportScheduler) Interval ¶ added in v0.3.0
func (c *ReportScheduler) Interval() time.Duration
func (*ReportScheduler) Name ¶ added in v0.3.0
func (c *ReportScheduler) Name() string
func (*ReportScheduler) Reconcile ¶ added in v0.3.0
func (c *ReportScheduler) Reconcile(ctx context.Context) (int, error)
Reconcile renders and delivers every due schedule, then records the run + next fire time. Idempotent at the run level: next_run_at advances past now, so a schedule is not re-picked until its next slot. One failing schedule never aborts the others.
type ReportSchedulerConfig ¶ added in v0.3.0
ReportSchedulerConfig configures the controller.
type ReportStatsSource ¶ added in v0.3.0
type ReportStatsSource interface {
GetStats(ctx context.Context, tenantID shared.ID, dataScopeUserID *shared.ID, filter vulnerability.FindingStatsFilter) (*vulnerability.FindingStats, error)
// CountWindow returns new (created) vs resolved finding counts over the
// trailing `days` window — the digest's trend line.
CountWindow(ctx context.Context, tenantID shared.ID, days int) (newCount, resolvedCount int64, err error)
}
ReportStatsSource provides the finding aggregates a summary report renders.
type RetryDispatcher ¶ added in v0.1.5
type RetryDispatcher interface {
RetryScanRun(ctx context.Context, tenantID, scanID shared.ID, retryAttempt int) error
}
RetryDispatcher is the dependency the ScanRetryController uses to actually re-trigger a failed scan run. The scan service implements this.
type RiskSnapshotController ¶ added in v0.2.0
type RiskSnapshotController struct {
// contains filtered or unexported fields
}
RiskSnapshotController computes daily risk snapshots for all tenants. Runs every 6 hours, but only inserts one row per tenant per day (UPSERT).
RFC-005 Gap 4: Risk Trend / Outcome Metrics.
func NewRiskSnapshotController ¶ added in v0.2.0
func NewRiskSnapshotController(db *sql.DB, log *logger.Logger) *RiskSnapshotController
NewRiskSnapshotController creates a new controller.
func (*RiskSnapshotController) Interval ¶ added in v0.2.0
func (c *RiskSnapshotController) Interval() time.Duration
Interval returns 6 hours (computes at most once per day per tenant via UPSERT).
func (*RiskSnapshotController) Name ¶ added in v0.2.0
func (c *RiskSnapshotController) Name() string
Name returns the controller name.
type RoleSyncController ¶ added in v0.1.2
type RoleSyncController struct {
// contains filtered or unexported fields
}
RoleSyncController ensures tenant_members and user_roles stay in sync.
The RBAC permission system reads from user_roles, while tenant_members stores the canonical membership. A trigger (sync_tenant_member_to_user_roles) handles new INSERT/UPDATE, but entries can become desynced after:
- Database restore from backup
- Migration rollback and re-apply
- Manual data manipulation
- Trigger being temporarily disabled
This controller detects missing user_roles entries and backfills them, preventing "Access Denied" errors for affected users.
func NewRoleSyncController ¶ added in v0.1.2
func NewRoleSyncController( db *sql.DB, config *RoleSyncControllerConfig, ) *RoleSyncController
NewRoleSyncController creates a new RoleSyncController.
func (*RoleSyncController) Interval ¶ added in v0.1.2
func (c *RoleSyncController) Interval() time.Duration
Interval returns the reconciliation interval.
func (*RoleSyncController) Name ¶ added in v0.1.2
func (c *RoleSyncController) Name() string
Name returns the controller name.
type RoleSyncControllerConfig ¶ added in v0.1.2
type RoleSyncControllerConfig struct {
// Interval is how often to run the sync check.
// Default: 1 hour.
Interval time.Duration
// Logger for logging.
Logger *logger.Logger
}
RoleSyncControllerConfig configures the RoleSyncController.
type SCMSyncController ¶ added in v0.3.0
type SCMSyncController struct {
// contains filtered or unexported fields
}
SCMSyncController periodically imports repositories and syncs branches for all connected SCM integrations. It reuses the on-demand import path, so it also refreshes branch defaults and flips a connection to "error" when its token has expired. Disabled unless SCM_SYNC_INTERVAL is set (interval > 0).
func NewSCMSyncController ¶ added in v0.3.0
func NewSCMSyncController(syncer SCMSyncer, interval time.Duration, log *logger.Logger) *SCMSyncController
NewSCMSyncController creates a new scheduled SCM sync controller.
func (*SCMSyncController) Interval ¶ added in v0.3.0
func (c *SCMSyncController) Interval() time.Duration
Interval returns the configured sync interval.
func (*SCMSyncController) Name ¶ added in v0.3.0
func (c *SCMSyncController) Name() string
Name returns the controller name.
type SCMSyncer ¶ added in v0.3.0
type SCMSyncer interface {
// SyncAllConnectedSCMIntegrations imports repositories + branches for every
// connected SCM integration across all tenants. Returns repos created+updated.
SyncAllConnectedSCMIntegrations(ctx context.Context) (int, error)
}
SCMSyncer is the integration-service surface the scheduled sync needs.
type SLABreachEvent ¶ added in v0.2.0
type SLABreachEvent struct {
TenantID shared.ID
FindingID shared.ID
SLADeadline time.Time
OverdueDuration time.Duration
At time.Time
}
SLABreachEvent is emitted once per finding on the transition into the `overdue` SLA state (a breach of its deadline). Downstream consumers (notification outbox, Jira commenter, PagerDuty router) subscribe via the publisher.
B4: closes the feedback edge where SLA status was previously computed but never acted on. Dedup via the SLA state transition itself — a second controller run won't re-emit because rows already in `overdue` state don't match the UPDATE WHERE clause.
type SLABreachPublisher ¶ added in v0.2.0
type SLABreachPublisher interface {
Publish(ctx context.Context, event SLABreachEvent) error
}
SLABreachPublisher delivers breach events to downstream consumers. Optional — nil publisher means "log only" (legacy behavior).
type SLABreachTxPublisher ¶ added in v0.3.0
type SLABreachTxPublisher interface {
PublishTx(ctx context.Context, tx *sql.Tx, event SLABreachEvent) error
}
SLABreachTxPublisher is an optional extension of SLABreachPublisher that enqueues a breach event inside a caller-supplied transaction. When the wired publisher implements it, the controller couples the `breached` state change and the notification enqueue in ONE transaction, so a crash/failure between them can't leave a finding permanently breached with its notification lost (the breach UPDATE's WHERE clause excludes already-breached rows, so a lost notification would never be retried).
type SLAEscalationController ¶ added in v0.2.0
type SLAEscalationController struct {
// contains filtered or unexported fields
}
SLAEscalationController periodically checks for overdue findings and updates their sla_status to 'overdue'. Runs every 15 minutes.
Note: This operates across all tenants intentionally — it's a system-level background job that marks overdue findings within their own rows. Each finding's tenant_id remains unchanged.
RFC-005 Gap 7 + B4: Automated SLA Escalation with publisher.
func NewSLAEscalationController ¶ added in v0.2.0
func NewSLAEscalationController(db *sql.DB, log *logger.Logger) *SLAEscalationController
NewSLAEscalationController creates a new SLA escalation controller.
func (*SLAEscalationController) Interval ¶ added in v0.2.0
func (c *SLAEscalationController) Interval() time.Duration
Interval returns 15 minutes.
func (*SLAEscalationController) Name ¶ added in v0.2.0
func (c *SLAEscalationController) Name() string
Name returns the controller name.
func (*SLAEscalationController) Reconcile ¶ added in v0.2.0
func (c *SLAEscalationController) Reconcile(ctx context.Context) (int, error)
Reconcile checks for overdue findings and marks them as breached.
B4: For every row newly-transitioned into `breached`, a SLABreachEvent is emitted via the publisher. Dedup is structural — the WHERE clause excludes rows already in `breached`, so a second run won't re-emit.
func (*SLAEscalationController) SetBreachPublisher ¶ added in v0.2.0
func (c *SLAEscalationController) SetBreachPublisher(p SLABreachPublisher)
SetBreachPublisher wires the breach-event publisher. Safe after construction; nil disables publishing.
func (*SLAEscalationController) SetWarningPublisher ¶
func (c *SLAEscalationController) SetWarningPublisher(p SLAWarningPublisher)
SetWarningPublisher wires the warning-event publisher. Safe after construction and before the controller starts; nil-safe.
type SLAWarningEvent ¶
type SLAWarningEvent struct {
TenantID shared.ID
FindingID shared.ID
SLADeadline time.Time
TimeRemaining time.Duration
At time.Time
}
SLAWarningEvent describes a finding that just entered the warning window.
type SLAWarningPublisher ¶
type SLAWarningPublisher interface {
PublishWarning(ctx context.Context, event SLAWarningEvent) error
}
SLAWarningPublisher delivers "approaching deadline" events. Optional — nil means log-only. Unlike breach, warnings are advisory (fire-and-forget); they don't need a transactional publisher because a lost warning is re-derivable (the finding is still in `warning` until it breaches, and re-notifying on the next tick would only duplicate — which the transition guard already prevents, since a row leaves `on_track` exactly once).
type ScanRetryController ¶ added in v0.1.5
type ScanRetryController struct {
// contains filtered or unexported fields
}
ScanRetryController periodically checks for failed pipeline runs that are eligible for automatic retry (based on the parent scan's max_retries + retry_backoff_seconds with exponential backoff) and dispatches retries through the RetryDispatcher.
func NewScanRetryController ¶ added in v0.1.5
func NewScanRetryController( runRepo retryRunRepository, dispatcher RetryDispatcher, config *ScanRetryControllerConfig, ) *ScanRetryController
NewScanRetryController creates a new ScanRetryController.
func (*ScanRetryController) Interval ¶ added in v0.1.5
func (c *ScanRetryController) Interval() time.Duration
func (*ScanRetryController) Name ¶ added in v0.1.5
func (c *ScanRetryController) Name() string
type ScanRetryControllerConfig ¶ added in v0.1.5
type ScanRetryControllerConfig struct {
// Interval is how often to check for retry candidates.
// Default: 60 seconds.
Interval time.Duration
// BatchSize is the maximum candidates processed per cycle.
// Default: 100.
BatchSize int
Logger *logger.Logger
}
ScanRetryControllerConfig configures the ScanRetryController.
type ScanTimeoutController ¶ added in v0.1.5
type ScanTimeoutController struct {
// contains filtered or unexported fields
}
ScanTimeoutController periodically marks pipeline_runs as timed out when they exceed their scan's configured timeout_seconds.
This complements JobRecoveryController (which marks stuck commands) by enforcing per-scan timeouts. A scan can specify its own timeout_seconds (default 1h, max 24h), and runs that exceed that are forcefully marked as timeout with an appropriate error message.
func NewScanTimeoutController ¶ added in v0.1.5
func NewScanTimeoutController( runRepo pipeline.RunRepository, config *ScanTimeoutControllerConfig, ) *ScanTimeoutController
NewScanTimeoutController creates a new ScanTimeoutController.
func (*ScanTimeoutController) Interval ¶ added in v0.1.5
func (c *ScanTimeoutController) Interval() time.Duration
Interval returns the reconciliation interval.
func (*ScanTimeoutController) Name ¶ added in v0.1.5
func (c *ScanTimeoutController) Name() string
Name returns the controller name.
type ScanTimeoutControllerConfig ¶ added in v0.1.5
type ScanTimeoutControllerConfig struct {
// Interval is how often to check for timed-out runs.
// Default: 60 seconds.
Interval time.Duration
// Logger for logging.
Logger *logger.Logger
}
ScanTimeoutControllerConfig configures the ScanTimeoutController.
type ScopeReconciliationController ¶ added in v0.1.2
type ScopeReconciliationController struct {
// contains filtered or unexported fields
}
ScopeReconciliationController periodically reconciles scope rule assignments as a safety net for the real-time event-driven hooks.
This controller: 1. Lists all tenants with active scope rules 2. For each tenant, lists all groups with active scope rules 3. Reconciles each group by re-evaluating matching assets
Design: This is a background safety net (K8s-style eventual consistency). The primary path is real-time hooks in AssetService and AssetGroupService.
func NewScopeReconciliationController ¶ added in v0.1.2
func NewScopeReconciliationController( acRepo accesscontrol.Repository, reconciler scopeGroupReconciler, config *ScopeReconciliationControllerConfig, ) *ScopeReconciliationController
NewScopeReconciliationController creates a new ScopeReconciliationController.
func (*ScopeReconciliationController) Interval ¶ added in v0.1.2
func (c *ScopeReconciliationController) Interval() time.Duration
Interval returns the reconciliation interval.
func (*ScopeReconciliationController) Name ¶ added in v0.1.2
func (c *ScopeReconciliationController) Name() string
Name returns the controller name.
type ScopeReconciliationControllerConfig ¶ added in v0.1.2
type ScopeReconciliationControllerConfig struct {
// Interval is how often to run the reconciliation.
// Default: 30 minutes.
Interval time.Duration
// Logger for logging.
Logger *logger.Logger
}
ScopeReconciliationControllerConfig configures the ScopeReconciliationController.
type TenantNamer ¶ added in v0.3.0
TenantNamer resolves a tenant's display name for the report header (optional).
type TenantSyncer ¶ added in v0.4.0
TenantSyncer runs a DefectDojo pull for one tenant. Returns error only (not the result) so the controller need not import app/defectdojo — cmd/server adapts *defectdojo.SyncService into this. Avoids a controller→app cycle.
type ThreatIntelRefreshController ¶ added in v0.1.7
type ThreatIntelRefreshController struct {
// contains filtered or unexported fields
}
ThreatIntelRefreshController periodically refreshes EPSS scores and KEV catalog. Runs every 24 hours. Fetches latest data from FIRST.org (EPSS) and CISA (KEV), then persists to database via ThreatIntelService.SyncAll(). After sync, auto-escalates findings whose CVEs appear in the KEV catalog and enqueues a priority reclassify for every tenant whose findings changed.
func NewThreatIntelRefreshController ¶ added in v0.1.7
func NewThreatIntelRefreshController(service *threat.IntelService, escalator threat.KEVEscalator, queue ReclassifyQueue, log *logger.Logger) *ThreatIntelRefreshController
NewThreatIntelRefreshController creates a new controller. queue may be nil (enqueue becomes a no-op).
func (*ThreatIntelRefreshController) Interval ¶ added in v0.1.7
func (c *ThreatIntelRefreshController) Interval() time.Duration
Interval returns 24 hours — daily refresh.
func (*ThreatIntelRefreshController) Name ¶ added in v0.1.7
func (c *ThreatIntelRefreshController) Name() string
Name returns the controller name.
type ThreatModelRefreshController ¶ added in v0.4.0
type ThreatModelRefreshController struct {
// contains filtered or unexported fields
}
ThreatModelRefreshController periodically regenerates each tenant's tenant-wide threat model so it reflects the latest exposure chains and asset-graph edges (e.g. edges the graph-enrichment controller just inferred). Without this, threat_model_threats only changes when a user manually triggers generation through the API, leaving the priority-classification threat-model oracle reading stale data.
A background controller (rather than the ingest hot path) is used because generation reasons over the whole tenant graph and must not slow ingest. The generator is idempotent (InputHash no-op detection) and each tenant is handled serially; a failure on one tenant never halts the others.
func NewThreatModelRefreshController ¶ added in v0.4.0
func NewThreatModelRefreshController( generator threatModelGenerator, tenantRepo tenant.Repository, config *ThreatModelRefreshControllerConfig, ) *ThreatModelRefreshController
NewThreatModelRefreshController constructs the controller.
func (*ThreatModelRefreshController) Interval ¶ added in v0.4.0
func (c *ThreatModelRefreshController) Interval() time.Duration
Interval implements controller.Controller.
func (*ThreatModelRefreshController) Name ¶ added in v0.4.0
func (c *ThreatModelRefreshController) Name() string
Name implements controller.Controller.
func (*ThreatModelRefreshController) Reconcile ¶ added in v0.4.0
func (c *ThreatModelRefreshController) Reconcile(ctx context.Context) (int, error)
Reconcile regenerates the tenant-wide threat model for every active tenant. Returns the number of tenants successfully (re)generated. Per-tenant errors are logged and skipped; only an unrecoverable tenant-list failure is returned so the runner retries next tick.
type ThreatModelRefreshControllerConfig ¶ added in v0.4.0
type ThreatModelRefreshControllerConfig struct {
// Interval is how often to run. Default: 2h. Threat models are derived
// from exposure chains, asset-graph edges, attacker profiles and live
// findings, which move slower than the hourly graph-enrichment pass that
// feeds them, so a 2h cadence is enough to keep threats current. The
// generator has built-in no-op detection (InputHash unchanged since the
// last generation short-circuits the write), so over-running is cheap.
Interval time.Duration
// Logger for structured output. Defaults to NewNop when nil.
Logger *logger.Logger
// ModuleGuard, when set, skips tenants that have disabled the threat-model
// module — no point regenerating a threat model a tenant turned off.
// Optional; nil means "never skip" (fully backward compatible).
ModuleGuard ModuleGuard
}
ThreatModelRefreshControllerConfig configures the periodic threat-model regeneration pass.
Source Files
¶
- agent_health.go
- approval_expiration.go
- asset_lifecycle.go
- audit_chain_verify.go
- audit_retention.go
- cert_monitor_refresh.go
- control_change_publisher.go
- control_test_scheduler.go
- controller.go
- coverage_scheduler.go
- ctemid_refresh.go
- data_expiration.go
- defectdojo_sync.go
- domain_reverify.go
- graph_enrichment.go
- ingest_worker.go
- job_recovery.go
- metrics.go
- module_guard.go
- owner_resolution.go
- priority_audit_retention.go
- priority_reclassify.go
- priority_reclassify_sweep.go
- queue_priority.go
- remediation_progress.go
- report_scheduler.go
- risk_snapshot.go
- role_sync.go
- scan_retry.go
- scan_timeout.go
- scm_sync.go
- scope_reconciliation.go
- sla_escalation.go
- threat_intel_refresh.go
- threat_model_refresh.go