scancoverage

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Jul 3, 2026 License: GPL-3.0 Imports: 12 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 scancoverage holds the pure, IO-free planning logic for license-aware rolling scan coverage (RFC-007): how big a batch may be under a scanner's license, and which assets to scan next.

It is deliberately decoupled from any scanner/transport so it can be unit tested in isolation and reused by both execution modes (direct + agent) and by the coverage scheduler. See docs/rfcs/RFC-007-license-aware-scan-coverage.md.

Index

Constants

View Source
const DefaultCoverageBatch = 256

DefaultCoverageBatch is the per-cycle batch size used when an integration does not specify one. It bounds scan duration/load for an unlimited engine and is the perf/time window, not a license limit.

View Source
const DefaultCoverageWindowDays = 30

DefaultCoverageWindowDays is the freshness window used when a caller does not specify one.

Variables

This section is empty.

Functions

func CountIPs

func CountIPs(target string) int

CountIPs returns how many license IPs a target consumes:

  • a CIDR consumes its full block size (2^hostbits), capped at MaxInt32;
  • a single IP or hostname consumes 1.

The full block (incl. network/broadcast) is counted because that is how active-IP licenses account for a scanned range.

func ValidateTenableIntegration

func ValidateTenableIntegration(cfg TenableConfig, hasCredentials bool, baseURL string) error

ValidateTenableIntegration enforces the correctness + security rules for a Tenable integration at create/update time.

  • agent mode MUST NOT store credentials in the control plane — they belong on the runner (RFC-007 §8 R3/R4: the control plane holds minimal authority over the scanner).
  • direct mode requires credentials + a base URL (the api calls Tenable).

Types

type BatchDispatcher

type BatchDispatcher interface {
	DispatchTenableScan(ctx context.Context, in DispatchTenableInput) (shared.ID, string, error)
}

BatchDispatcher dispatches one batch to a runner. *Dispatcher satisfies it.

type Candidate

type Candidate struct {
	AssetID string
	// Target is the IP / CIDR / hostname that will be scanned. Used to count
	// how many license IPs it consumes.
	Target string
	// Criticality: critical|high|medium|low|none (case-insensitive).
	Criticality string
	// LastScannedAt is nil for never-scanned assets (which sort first).
	LastScannedAt *time.Time
}

Candidate is an asset eligible for the next coverage batch.

func SelectBatch

func SelectBatch(candidates []Candidate, maxIPs int) (selected []Candidate, ips int)

SelectBatch picks the next batch from candidates, ordered by (criticality DESC, LastScannedAt ASC, nulls first) and greedily filled until adding the next candidate would exceed maxIPs. It returns the selected candidates and the total IP count they consume.

If maxIPs > 0 the first (highest-priority) candidate is always taken even when it alone exceeds maxIPs — otherwise a single oversized CIDR at the front would stall the rotation forever. Callers should surface that over-budget case. maxIPs <= 0 selects nothing.

type CommandCreator

type CommandCreator interface {
	Create(ctx context.Context, cmd *command.Command) error
}

CommandCreator persists agent commands. It is the subset of command.Repository the dispatcher needs (kept narrow for testability).

type CoverageConfig

type CoverageConfig struct {
	TenantID shared.ID
	// AgentID optionally pins a specific runner (C3); nil → capability routing.
	AgentID *shared.ID
	// Engine is "nessus_pro" (unlimited) or "tenable_sc" (active-IP cap).
	Engine string
	// Policy is the license rule used to size the batch.
	Policy LicensePolicy
	// DefaultBatch is the performance/time-window batch size; for an unlimited
	// engine it is the whole headroom, for a capped engine it bounds a single
	// cycle so one tenant cannot consume the entire cap at once.
	DefaultBatch int
	// TemplateUUID optionally overrides the runner's default Nessus template.
	TemplateUUID string
}

CoverageConfig is one tenant's active rolling-coverage configuration.

type CoverageSource

type CoverageSource interface {
	// ListActiveCoverage returns every tenant with an active Tenable coverage
	// integration configured for rolling coverage.
	ListActiveCoverage(ctx context.Context) ([]CoverageConfig, error)
	// ListCandidates returns assets eligible for the next batch for a tenant
	// (already filtered to in-scope, scannable assets). Order is irrelevant — the
	// planner re-sorts by criticality + staleness.
	ListCandidates(ctx context.Context, tenantID shared.ID, limit int) ([]Candidate, error)
	// ActiveIPs returns how many IPs the scheduler currently believes are live on
	// the engine for this tenant (active-IP-cap engines only; return 0 for
	// unlimited). This is the un-reclaimed count: it is what gates the next batch
	// — a capped engine will not get a new batch until a prior one has been aged
	// out / reclaimed by the runner and the count has dropped (RFC-007 §3.2).
	ActiveIPs(ctx context.Context, tenantID shared.ID) (int, error)
}

CoverageSource yields the work the scheduler acts on. The live implementation reads integrations + the asset estate; tests use a fake.

type CoverageStats

type CoverageStats struct {
	// WindowDays is the freshness window the stats were computed against.
	WindowDays int `json:"window_days"`
	// TotalScannable is the count of active, network-scannable assets.
	TotalScannable int `json:"total_scannable"`
	// NeverScanned have no coverage cursor row yet.
	NeverScanned int `json:"never_scanned"`
	// CoveredInWindow were dispatched within WindowDays.
	CoveredInWindow int `json:"covered_in_window"`
	// Stale were dispatched, but longer ago than WindowDays.
	Stale int `json:"stale"`
	// CriticalNeverScanned is the headline risk: critical assets never covered.
	CriticalNeverScanned int `json:"critical_never_scanned"`
	// CriticalUncovered are critical assets either never scanned or stale.
	CriticalUncovered int `json:"critical_uncovered"`
	// OldestDispatchedAt is the least-recently covered asset's timestamp (nil if
	// nothing has been dispatched yet).
	OldestDispatchedAt *time.Time `json:"oldest_dispatched_at,omitempty"`
	// CoveragePercent = CoveredInWindow / TotalScannable * 100 (0 when none).
	CoveragePercent float64 `json:"coverage_percent"`
}

CoverageStats is a point-in-time summary of how well a tenant's scannable estate is covered by rolling scans (RFC-007 Phase 4 observability). It turns "we ran scans" into a verifiable coverage figure — the freshness/utilisation view the use case needs (and that Tenable.sc reporting provides).

type CoverageStatsReader

type CoverageStatsReader interface {
	CoverageStats(ctx context.Context, tenantID shared.ID, windowDays int) (*CoverageStats, error)
}

CoverageStatsReader reads coverage observability stats for a tenant. *postgres.ScanCoverageRepository implements it.

type CursorStore

type CursorStore interface {
	MarkDispatched(ctx context.Context, rec DispatchRecord) error
}

CursorStore persists the effect of a dispatch: it advances LastScannedAt for the batch's assets (so they sort last next cycle) and, for capped engines, adds the batch to the active-IP set the runner will later reclaim.

type DispatchRecord

type DispatchRecord struct {
	TenantID  shared.ID
	AssetIDs  []string
	SessionID string
	CommandID shared.ID
	// IPCount is the license IPs this batch consumes (for active-IP accounting).
	IPCount int
}

DispatchRecord is what the scheduler hands back to the store after a batch has been dispatched, so the cursor advances and active-IP accounting updates.

type DispatchTenableInput

type DispatchTenableInput struct {
	TenantID shared.ID
	// Targets are the IPs/CIDRs/hostnames in this batch.
	Targets []string
	// SessionID scopes auto-resolve to this batch (tool + session + assets).
	// Generated if empty.
	SessionID string
	// AgentID optionally pins a specific runner (C3). Nil → any tenable-capable
	// agent picks it up via capability routing.
	AgentID *shared.ID
	// Engine is informational ("nessus_pro" | "tenable_sc"); the runner uses its
	// local engine config.
	Engine string
	// TemplateUUID optionally overrides the runner's default Nessus template.
	TemplateUUID string
}

DispatchTenableInput describes one Tenable coverage batch to dispatch to a runner. The runner is an OpenCTEM agent with capability `infra` + tool `tenable` (RFC-007 §3.10); it holds the appliance credentials locally and the control plane never does.

type Dispatcher

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

Dispatcher creates Tenable scan commands routed to a tenable-capable runner.

func NewDispatcher

func NewDispatcher(commands CommandCreator) *Dispatcher

NewDispatcher builds a Dispatcher.

func (*Dispatcher) DispatchTenableScan

func (d *Dispatcher) DispatchTenableScan(ctx context.Context, in DispatchTenableInput) (cmdID shared.ID, sessionID string, err error)

DispatchTenableScan enqueues a scan command for a Tenable runner and returns the command ID and the (possibly generated) scan session id.

The command is a generic scan command whose payload carries scanner="tenable" (the discriminator the agent routes on), the target batch, the coverage session id, and the required capability. The runner picks it up via poll, scans its LOCAL appliance, and pushes CTIS back.

type Engine

type Engine string

Engine identifies the Tenable product.

const (
	EngineNessusPro Engine = "nessus_pro" // unlimited IPs (default)
	EngineTenableSC Engine = "tenable_sc" // active-IP licensed
)

type ExecutionMode

type ExecutionMode string

ExecutionMode selects how a Tenable integration reaches the appliance (RFC-007 §3.9).

const (
	// ExecutionModeAgent (default) — a runner on the customer network reaches
	// Nessus/Tenable and pushes results back via polling. The control plane
	// holds NO scanner credentials. This is the recommended, secure default.
	ExecutionModeAgent ExecutionMode = "agent"

	// ExecutionModeDirect — the backend calls Tenable REST itself. Only for
	// Tenable cloud / a reachable .sc where the operator accepts the control
	// plane holding credentials.
	ExecutionModeDirect ExecutionMode = "direct"
)

type LicenseMode

type LicenseMode string

LicenseMode describes how a scan engine is licensed.

const (
	// LicenseUnlimited — Nessus Professional: unlimited IPs; batching is for
	// scan duration/load only, there is no cap to respect.
	LicenseUnlimited LicenseMode = "unlimited"

	// LicenseActiveIPCap — Tenable.sc: a fixed number of active IPs may carry
	// live results at once; batches must fit the remaining headroom.
	LicenseActiveIPCap LicenseMode = "active_ip_cap"
)

type LicensePolicy

type LicensePolicy struct {
	Mode LicenseMode

	// Cap is the maximum active IPs (LicenseActiveIPCap only).
	Cap int

	// SafetyMargin keeps the scheduler a few IPs below Cap so a slow reclaim
	// can't tip the account over the limit (LicenseActiveIPCap only).
	SafetyMargin int
}

LicensePolicy is the per-engine licensing rule the scheduler reads to size a batch.

func (LicensePolicy) Headroom

func (p LicensePolicy) Headroom(activeIPs, defaultBatch int) int

Headroom returns how many IPs may be added to a new batch right now.

  • Unlimited: returns defaultBatch (the caller's performance/time batch size).
  • ActiveIPCap: Cap − SafetyMargin − activeIPs, clamped at 0.

activeIPs is the count the scheduler currently believes are live on the engine (it tracks this itself rather than trusting instant reclaim — RFC-007 §3.2).

type Scheduler

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

Scheduler performs one rotation pass over all tenants' coverage configs.

func NewScheduler

func NewScheduler(source CoverageSource, dispatcher BatchDispatcher, store CursorStore, cfg *SchedulerConfig) *Scheduler

NewScheduler builds a Scheduler.

func (*Scheduler) RunOnce

func (s *Scheduler) RunOnce(ctx context.Context) (dispatched int, err error)

RunOnce performs a single rotation pass and returns the number of batches dispatched. A failure for one tenant is logged and skipped — it never aborts the pass for the other tenants (controllers must be resilient).

type SchedulerConfig

type SchedulerConfig struct {
	// CandidateLimit caps how many candidates are loaded per tenant per cycle.
	// Default: 5000.
	CandidateLimit int
	Logger         *logger.Logger
}

SchedulerConfig configures the Scheduler.

type TenableConfig

type TenableConfig struct {
	ExecutionMode ExecutionMode
	Engine        Engine

	// CoverageEnabled opts this integration into automatic rolling coverage by
	// the scheduler. It defaults to false so connecting an integration never
	// silently starts scanning — coverage is an explicit choice.
	CoverageEnabled bool
	// BatchSize is the per-cycle target batch size (perf/time window). 0 → default.
	BatchSize int
	// LicenseCap is the active-IP cap for a capped engine (.sc only).
	LicenseCap int
	// SafetyMargin keeps the scheduler a few IPs below the cap (.sc only).
	SafetyMargin int
	// AgentID optionally pins a specific runner (C3); empty → capability routing.
	AgentID string
	// TemplateUUID optionally overrides the runner's default Nessus template.
	TemplateUUID string
}

TenableConfig is the normalized config of a Tenable integration, read from the integration's JSONB config map.

func ParseTenableConfig

func ParseTenableConfig(config map[string]any) (TenableConfig, error)

ParseTenableConfig reads + normalizes a Tenable integration config map, applying secure defaults (agent + nessus_pro) and rejecting unknown values.

func (TenableConfig) EffectiveBatchSize

func (c TenableConfig) EffectiveBatchSize() int

EffectiveBatchSize returns the configured batch size or the default.

func (TenableConfig) LicensePolicy

func (c TenableConfig) LicensePolicy() LicensePolicy

LicensePolicy derives the engine's licensing rule used to size a coverage batch. Nessus Pro is unlimited; Tenable.sc is active-IP capped.

Jump to

Keyboard shortcuts

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