scanner

package
v0.73.0-rc.1 Latest Latest
Warning

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

Go to latest
Published: Nov 7, 2026 License: MIT Imports: 44 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DefaultWorkerPoolSize = 3  // Max concurrent scans
	MaxQueueSize          = 50 // Max pending scans in queue
)
View Source
const (
	QueueStatusPending   = "pending"
	QueueStatusRunning   = "running"
	QueueStatusCompleted = "completed"
	QueueStatusFailed    = "failed"
	QueueStatusSkipped   = "skipped"
	QueueStatusCancelled = "cancelled"
)

QueueItemStatus represents the status of a queued scan

View Source
const (
	// RejectTamper: the signature did not verify over the raw bytes, or the
	// manifest / sidecar / verifying-key ids disagree (sidecar contract rows 12
	// and 13; SC-001's tamper classes).
	RejectTamper = "tamper"
	// RejectDowngrade: sequence below this authority's watermark for this
	// epoch, or an equal sequence with a different digest.
	RejectDowngrade = "downgrade"
	// RejectStaleEpochReplay: manifest epoch below the current trusted epoch.
	RejectStaleEpochReplay = "stale_epoch_replay"
	// RejectEpochAhead: manifest epoch above the current trusted epoch — this
	// binary (or this config) is older than the publisher's recovery release;
	// update mcpproxy. Does not demote coverage (FR-009a allows two conditions).
	RejectEpochAhead = "epoch_ahead"
	// RejectUnsignedRatchet: an unsigned candidate after a signature-verified
	// bundle has activated on this install (FR-009 ratchet).
	RejectUnsignedRatchet = "unsigned_refused_by_ratchet"
	// RejectSignatureRequired: require_signed_bundle is on and the sidecar is
	// absent.
	RejectSignatureRequired = "signature_required"
	// RejectAuthorityNotActive: verified against a real key of the NON-active
	// root (FR-004b).
	RejectAuthorityNotActive = "authority_not_active"
	// RejectRollbackTargetMismatch: the loaded artifact's full digest is not the
	// digest the operator named (FR-010).
	RejectRollbackTargetMismatch = "rollback_target_mismatch"
	// RejectDenyListed: the candidate is a release the operator rolled away
	// from (FR-010 deny-list).
	RejectDenyListed = "deny_listed"
	// RejectGateFailure: the activation self-check refused the candidate.
	RejectGateFailure = "gate_failure"
	// RejectCeilingExceeded: one of FR-011's limits (bundle 8 MiB, 2000 rules,
	// sidecar 4 KiB) — which one, and the observed value, in Detail.
	RejectCeilingExceeded = "ceiling_exceeded"
	// RejectNotRegularFile: the candidate (or its sidecar) is a FIFO, device,
	// socket, directory, or a symlink.
	RejectNotRegularFile = "not_regular_file"
	// RejectReadTimeout: the per-candidate read budget expired; the
	// single-flight slot was released.
	RejectReadTimeout = "read_timeout"
	// RejectReadError: the candidate could not be opened or read (missing file,
	// permission denied, I/O error).
	RejectReadError = "read_error"
	// RejectSidecarInvalid: the sidecar violates its grammar (bundlesig
	// sidecar_* codes other than sidecar_too_large).
	RejectSidecarInvalid = "sidecar_invalid"
	// RejectKeyNotTrusted: the sidecar key id is in neither trust set.
	RejectKeyNotTrusted = "key_not_trusted"
	// RejectInvalidBundle: the bundle failed to parse, carries a malformed
	// manifest field (sequence grammar, trust_epoch), an unsupported version, a
	// pattern that does not compile, or no runnable rule.
	RejectInvalidBundle = "invalid_bundle"
	// RejectStateCommitFailed: the anti-downgrade state could not be durably
	// committed, so the candidate was NOT activated. Refusing to activate is the
	// safe outcome: activating without a durable watermark would reopen the
	// replay window FR-011a exists to close. Last-known-good keeps serving.
	RejectStateCommitFailed = "state_commit_failed"
)

Bundle rejection reasons surfaced in BundleInfo.LastRejection.Reason (spec 101 FR-020; contracts/bundle-status-surface.md §2). The Reason is the only field anything branches on; the fine-grained cause (the bundlesig contract code, which ceiling and by how much, which key id, which epoch) goes in Detail. Every rejection keeps last-known-good serving.

View Source
const (
	DegradedUnsignedExternalActive       = "unsigned_external_active"
	DegradedEmbeddedBelowWatermark       = "embedded_below_watermark"
	DegradedOperatorBundleMissing        = "operator_bundle_missing"
	DegradedOperatorAuthorityUnbaselined = "operator_authority_unbaselined"
)

Degraded-coverage reasons (FR-007, FR-009a, FR-009b; contracts/bundle-status-surface.md §3). While any of these holds, scan-mode auto-approval is suspended and changes route to human review.

View Source
const (
	// MaxBundleBytes is the bundle byte ceiling (8 MiB).
	MaxBundleBytes = 8 << 20
	// MaxBundleRules is the rules[] entry ceiling (all entries, runnable or not).
	MaxBundleRules = 2000
	// MaxSidecarBytes is the sidecar byte ceiling (4 KiB).
	MaxSidecarBytes = 4 << 10
)

FR-011 load ceilings. A candidate AT a ceiling loads; one unit over is rejected whole. Design may tighten these, never loosen them.

View Source
const (
	// BundleSourceEmbedded is the corpus compiled into this build
	// (bundled/scanner-bundle.json).
	BundleSourceEmbedded = "embedded"
	// BundleSourceFile is a corpus read from the configured filesystem path
	// (security.tpa_bundle_path / MCPPROXY_TPA_BUNDLE_PATH).
	BundleSourceFile = "file"
	// BundleSourceFetch is a corpus fetched from the configured channel
	// (security.tpa_fetch_url, Spec 087 / Spec 101 US3). It reaches the same
	// verifier as a file drop; only the Candidate's origin differs.
	BundleSourceFetch = "fetch"
)

Bundle source labels reported by BundleInfo.Source.

View Source
const (
	// AuthorityPublisher is the binary-embedded publisher signer set.
	AuthorityPublisher = "publisher"
	// AuthorityOperator is the config-resident operator signer set
	// (security.tpa_operator_signers).
	AuthorityOperator = "operator"
)

Signing authorities (spec 101 FR-004/FR-004a). An authority is a NAMESPACE for anti-downgrade state, not a key: every publisher key — including keys being rotated in or out — belongs to the one publisher authority, so a rotated-in key inherits the existing watermark instead of starting fresh.

View Source
const (
	// RefreshTriggerStartup is the construction-time ConfigureBundleFromConfig.
	RefreshTriggerStartup = "startup"
	// RefreshTriggerConfig is a config.reloaded re-apply.
	RefreshTriggerConfig = "config"
	// RefreshTriggerTimer is the refresher's periodic tick.
	RefreshTriggerTimer = "timer"
	// RefreshTriggerManual is `security bundle refresh` / POST .../bundle/refresh.
	RefreshTriggerManual = "manual"
)

Refresh trigger vocabulary (BundleRefreshStatus.LastTrigger).

View Source
const (
	// RefreshOutcomeActivated: a new bundle was verified and activated.
	RefreshOutcomeActivated = "activated"
	// RefreshOutcomeUnchanged: the candidate equals the serving bundle, or was
	// already refused (negative cache); nothing was compiled.
	RefreshOutcomeUnchanged = "unchanged"
	// RefreshOutcomeNotModified: the channel answered 304.
	RefreshOutcomeNotModified = "not_modified"
	// RefreshOutcomeRejected: the pipeline refused the candidate; the detail
	// is in BundleInfo.LastRejection.
	RefreshOutcomeRejected = "rejected"
	// RefreshOutcomeFetchUnavailable: a non-verification failure (network,
	// timeout, HTTP status, rate limit). Never a last_rejection.
	RefreshOutcomeFetchUnavailable = "fetch_unavailable"
	// RefreshOutcomeChannelInvalid: the channel answered but is malformed
	// (zero or several candidate assets, missing sidecar asset, oversize JSON).
	RefreshOutcomeChannelInvalid = "channel_invalid"
	// RefreshOutcomeSuperseded: the fetch or trust settings changed while a
	// download was in flight, so its candidate was discarded (Δ30).
	RefreshOutcomeSuperseded = "superseded"
	// RefreshOutcomeDisabled: the fetch leg may not issue requests (B10); the
	// reason says why.
	RefreshOutcomeDisabled = "disabled"
)

Refresh outcome vocabulary (BundleRefreshStatus.LastOutcome).

View Source
const (
	RefreshReasonNetworkError = "network_error"
	RefreshReasonTimeout      = "timeout"
	RefreshReasonHTTPStatus   = "http_status"
	RefreshReasonRateLimited  = "rate_limited"

	RefreshReasonFetchOff         = "fetch_off"
	RefreshReasonNoURL            = "no_url"
	RefreshReasonInvalidURL       = "invalid_url"
	RefreshReasonNoTrustedSigner  = "no_trusted_signer"
	RefreshReasonStateUnavailable = "state_unavailable"
)

Refresh reason vocabulary (BundleRefreshStatus.LastReason). Fetch-unavailable reasons first, then the disabled reasons (tasks B6, B10).

View Source
const (
	ReprotectStateIdle      = "idle"
	ReprotectStateRunning   = "running"
	ReprotectStateSuspended = "suspended"
	ReprotectStateFailed    = "failed"
)

Re-protection sweep state vocabulary (BundleReprotectStatus.State).

View Source
const (
	// ScannerStatusAvailable means the scanner is known to mcpproxy but
	// not enabled. Toggling it on moves it into ScannerStatusPulling.
	ScannerStatusAvailable = "available"
	// ScannerStatusPulling means the Docker image is currently being
	// downloaded in the background. UI should show a spinner.
	ScannerStatusPulling = "pulling"
	// ScannerStatusInstalled means the image is present locally and the
	// scanner is ready to run. No required API keys are configured yet.
	ScannerStatusInstalled = "installed"
	// ScannerStatusConfigured means the image is present AND user-supplied
	// env (e.g. API keys) have been stored.
	ScannerStatusConfigured = "configured"
	// ScannerStatusError means the last operation (typically a pull) failed.
	// ErrorMsg carries the reason. The UI should offer a "Retry" button.
	ScannerStatusError = "error"
)

Scanner status constants

View Source
const (
	ScanJobStatusPending   = "pending"
	ScanJobStatusRunning   = "running"
	ScanJobStatusCompleted = "completed"
	ScanJobStatusFailed    = "failed"
	ScanJobStatusCancelled = "cancelled"
)

Scan job status constants

View Source
const (
	SeverityCritical = "critical"
	SeverityHigh     = "high"
	SeverityMedium   = "medium"
	SeverityLow      = "low"
	SeverityInfo     = "info"
)

Scan finding severity constants

View Source
const (
	ScanPassSecurityScan     = 1 // Fast pass: source code + lockfile scanning
	ScanPassSupplyChainAudit = 2 // Background pass: full filesystem CVE analysis
)

Scan pass constants

View Source
const (
	MaxScanLogLines   = 5000   // Max lines of stdout/stderr per scanner
	MaxScannedFiles   = 10000  // Max file entries in scanned_files list
	MaxScansPerServer = 20     // Keep last N scans per server
	MaxLogBytes       = 500000 // ~500KB max per log field
)

Scan context limits

View Source
const (
	ThreatToolPoisoning   = "tool_poisoning"   // Hidden instructions in tool descriptions
	ThreatPromptInjection = "prompt_injection" // Malicious payloads in tool responses
	ThreatRugPull         = "rug_pull"         // Tool definitions changed after approval
	ThreatSupplyChain     = "supply_chain"     // Known CVEs in dependencies
	ThreatMaliciousCode   = "malicious_code"   // Malware, backdoors, suspicious code
	ThreatUncategorized   = "uncategorized"    // Other findings
)

User-facing threat category constants

View Source
const (
	ThreatLevelDangerous = "dangerous" // Blocks approval: tool poisoning, active injection
	ThreatLevelWarning   = "warning"   // Rug pull, high CVEs
	ThreatLevelInfo      = "info"      // Low CVEs, informational
)

User-facing severity levels (simpler than CVSS)

View Source
const (
	TierHard = "hard"
	TierSoft = "soft"
)

Finding tiers (Spec 077). A hard-tier baseline finding gates approval (auto-quarantine / dangerous verdict); a soft-tier finding is review-only. The tier mirrors detect.TierHard/TierSoft and is set from detect output when a finding comes from the deterministic baseline engine (see detectFindingToScanFinding). Empty for findings that predate the two-tier model (legacy/external scanners) — those keep their existing threat_level semantics.

View Source
const RedactedEnvValue = "***"

RedactedEnvValue replaces a literal scanner env value on every API serialization path. It is a fixed sentinel rather than a partial mask so it carries no information about the secret's length or shape, and it is TRUTHY so a client can still tell that the variable is set — which is all the Web UI ever needed from the value (it renders "(configured)" and gates the "needs an API key" badge on presence).

View Source
const ReprotectReasonAutoBaselineScanOff = "auto_baseline_scan_off"

ReprotectReasonAutoBaselineScanOff is the suspended reason shown while security.auto_baseline_scan is off (tasks B17).

View Source
const TPABundleStateSchemaVersion = 1

TPABundleStateSchemaVersion versions the persisted TPABundleState record.

Variables

View Source
var ErrBundleRollbackUsage = errors.New("invalid bundle rollback request")

ErrBundleRollbackUsage marks a malformed rollback request: both or neither of embedded/path, or a digest that is not 64 lowercase hex characters (a 12-hex fingerprint included). It is a caller error (HTTP 400), not a recorded rejection.

View Source
var ErrBundleSuperseded = errors.New("the requested bundle is no longer the active bundle: no cached scan")

ErrBundleSuperseded is returned by StartScanFromCachedContracts when the bundle the caller asked to cover is no longer the active one at the moment the job would be registered: a job labelled with the requested digest would not describe the bundle that serves.

View Source
var ErrNoCachedContracts = errors.New("no cached tool contracts to scan")

ErrNoCachedContracts is returned by StartScanFromCachedContracts when the server has no recorded tool contract to scan (or the provider cannot list them). No job is recorded, so the server reads as unscanned, never clean.

View Source
var ErrScanInProgress = errors.New("scan already in progress")

ErrScanInProgress is returned (wrapped) by StartScan when the server already has a registered scan job.

View Source
var ErrServerQuarantined = errors.New("server is quarantined: no cached scan")

ErrServerQuarantined is returned by StartScanFromCachedContracts for a quarantined server: its stored contracts are not what a scan-mode admission verdict is about, so a quarantined server never gets a cached scan job (Spec 101 tasks B17).

View Source
var ErrToolApprovalBlockNotFound = errors.New("tool approval block target not found")

Functions

func AddBundleActivationObserver added in v0.72.0

func AddBundleActivationObserver(fn func(BundleActivation)) (unsubscribe func())

AddBundleActivationObserver registers fn to be called, on its own goroutine and outside bundleRT.mu, after every activation or rollback that wrote a history row. It never fires on an LKG restore, an embedded fallback, an idempotent rerun or a refusal. The returned function unsubscribes; a dispatch already under way still completes.

func BundleCoverageDegraded added in v0.72.0

func BundleCoverageDegraded() (bool, string)

BundleCoverageDegraded reports whether the active bundle demotes the install to degraded coverage, and why. The scan-mode admission gates consult it: while it is true auto-approval is suspended and changes route to human review.

func BundleDoctorWarnings added in v0.72.0

func BundleDoctorWarnings(info BundleInfo, now time.Time) []string

BundleDoctorWarnings turns the bundle status into at most three short doctor warnings: stale, stuck on last-known-good, and fetch configured but inactive (tasks B16). The strings carry no digest, path, URL or host: a doctor report is made to be shared, and the reason codes are a closed vocabulary. It is a pure function of its arguments so the truth table is testable without a runtime; the caller supplies the status (the server registers BundleStatus() with time.Now()).

These warnings intentionally feed the doctor verdict, the MCP doctor tool and the telemetry runtime_warnings pass/fail bit: each one is an actionable state on an install that configured a refresh. A stale embedded corpus on an install that never configured a refresh stays in the status surfaces only; binary upgrades are Spec 079's nudge.

now is accepted for the signature's symmetry with the other status readers; every age here was already computed at read time into the info (Stale, StalenessDays), so the function does not recompute against a second clock.

func CalculateRiskScore

func CalculateRiskScore(findings []ScanFinding) int

CalculateRiskScore computes a 0-100 risk score from findings. Scoring is based on user-facing threat levels, not raw CVSS.

This uses logarithmic diminishing returns so duplicate findings from multiple scanners don't inflate the score, while still reflecting cumulative risk. Identical findings reported by several scanners (same rule_id + location) are deduplicated before scoring.

Scoring is a pure function of each finding's OWN severity/category (Spec 077 US2). Cross-scanner AGREEMENT — two scanners independently flagging the same (location, threat_type) via different rule ids — raises the merged finding's CONFIDENCE in MergeFindings (SC-008) but adds NO risk-score weight: a weak external finding that merely agrees with a strong one contributes only its own (weak) category and can never inflate the stronger bucket. This keeps the score deterministic, order-independent, and identical whether it is computed before or after MergeFindings has run.

Spec 076 (FR-006, SC-007) — a finding's OWN detect signals still add: the deterministic scanner emits ONE finding per tool whose Signals list every independent check that fired within that single scanner, so a finding flagged by N of its own checks weighs N. That is a per-finding property of one scanner's output, not cross-scanner agreement, so it is retained. Findings from scanners that emit no per-signal data weigh 1, so legacy scoring is unchanged.

Formula per category: category_score = weight * log2(1 + weighted_count)

  • Dangerous: weight 25 (1=25, 2=40, 4=58, 8=72, cap 80)
  • Warning: weight 6 (1=6, 2=10, 4=15, 8=18, cap 25)
  • Info: weight 2 (1=2, 2=3, 4=5, 8=6, cap 10)

Note: This score is an experimental heuristic. There is no industry standard for aggregating multi-scanner MCP security findings into a single number.

func ClassifyAllFindings

func ClassifyAllFindings(findings []ScanFinding)

ClassifyAllFindings applies threat classification to all findings

func ClassifyScannerExecFailure added in v0.24.3

func ClassifyScannerExecFailure(stderr string, exitCode int) string

ClassifyScannerExecFailure inspects a scanner's stderr and exit code and returns a human-readable remediation hint when the failure matches a well-known environment incompatibility. Returns an empty string when the stderr does not match a known pattern.

Currently recognised:

  • snap-docker × AppArmor × no-new-privileges: runc reports "exec /usr/local/bin/...: operation not permitted" (exit 255) when the dockerd snap profile blocks the inner profile transition.

func ClassifyThreat

func ClassifyThreat(f *ScanFinding)

ClassifyThreat assigns user-facing threat_type and threat_level to a finding based on rule ID, category, description, and severity.

func CollectFileList

func CollectFileList(dir string) (files []string, totalFiles int, totalSize int64)

CollectFileList walks a directory and returns a list of files (relative paths). Caps at MaxScannedFiles entries. Also returns total count and size.

func ConfigureBundle added in v0.53.0

func ConfigureBundle(path string, logger *zap.Logger)

ConfigureBundle installs the TPA signature corpus the scanner will run, reading it from path when non-empty and falling back to the embedded default otherwise (spec 086 FR-019: the path MUST NOT be hardcoded). It is a thin wrapper over the serialized runtime with an otherwise default policy and NO environment override: the path is explicit. Production code configures the full trust policy through ConfigureBundleFromConfig.

Failure policy (fail-closed, never fail-empty): if the configured file cannot be read, verified, parsed, version-checked, or compiled, the currently active corpus (or the embedded default on first call) stays live and the reason is recorded in BundleInfo.LoadError and BundleInfo.LastRejection AND logged through the INJECTED logger.

func ConfigureBundleFromConfig added in v0.72.0

func ConfigureBundleFromConfig(sec *config.SecurityConfig, logger *zap.Logger)

ConfigureBundleFromConfig applies the security config's bundle policy: the path (MCPPROXY_TPA_BUNDLE_PATH outranks the file value), require_signed_bundle, the active signing root, the operator signers, baseline and epoch. It is safe to call repeatedly and from any goroutine; an unchanged configuration with an unchanged bundle file is a no-op (no commit, no history row, no log line).

func EnableActivationSelfCheck added in v0.72.0

func EnableActivationSelfCheck()

EnableActivationSelfCheck installs the activation self-check as the pipeline's bundleSelfCheck hook. Production wiring (internal/server/server.go) calls it once, next to configureTPABundleRuntime; US1 fixtures and clearBundleRuntime keep the nil default. It is idempotent and safe to call from concurrent server constructions: the hook is read under bundleRT.mu, so it is written under it too (Enable is never called from inside the pipeline).

func GenerateContainerName

func GenerateContainerName(scannerID, serverName string) string

GenerateContainerName creates a unique container name for a scanner run

func IsSARIF

func IsSARIF(data []byte) bool

IsSARIF checks if the given data looks like a SARIF document

func PrepareReportDir

func PrepareReportDir(baseDir, jobID, scannerID string) (string, error)

PrepareReportDir creates a temporary directory for scanner output

func SetBundleRefreshObserver added in v0.72.0

func SetBundleRefreshObserver(fn func(RefreshOutcomeClass))

SetBundleRefreshObserver registers fn to receive exactly one RefreshOutcomeClass per refresh cycle. A nil fn clears it. internal/server maps the class to the telemetry enum.

func SetBundleRefresher added in v0.72.0

func SetBundleRefresher(r *BundleRefresher)

SetBundleRefresher installs r as the process's refresher, the one RefreshBundle consults. nil clears the slot.

func SetBundleRuntime added in v0.72.0

func SetBundleRuntime(store TPABundleStateStore, dataDir string)

SetBundleRuntime injects the persistent state store and the data directory the LKG files live under. Call it once at startup, before the first configure; it resets the runtime so the next run loads state from the new store (spec 101 Δ4). A nil store keeps the anti-downgrade state in memory only; an empty dataDir keeps no LKG files.

func SetReprotectStatus added in v0.72.0

func SetReprotectStatus(status BundleReprotectStatus)

SetReprotectStatus publishes the re-protection sweep status that BundleStatus merges into BundleInfo.Reprotect (tasks B15, B17). A zero status (empty State) clears it.

func ToolContractDigests added in v0.71.0

func ToolContractDigests(tools []map[string]interface{}) map[string][]string

ToolContractDigests maps each exported tool name to the sorted, de-duplicated hash.ToolContractDigest of every definition exported under that name.

func ValidateManifest

func ValidateManifest(s *ScannerPlugin) error

ValidateManifest validates a scanner plugin manifest

Types

type AggregatedReport

type AggregatedReport struct {
	JobID      string        `json:"job_id"`
	ServerName string        `json:"server_name"`
	Findings   []ScanFinding `json:"findings"`
	RiskScore  int           `json:"risk_score"`
	// Summary carries the RAW threat-level / severity counts across ALL
	// findings (baseline + deep-scan/external) for transparency. It is NOT a
	// verdict — verdict-bearing UI must read Verdict/FindingCounts below.
	Summary ReportSummary `json:"summary"`
	// Verdict is the tier-driven, baseline-only verdict for this report
	// (Spec 077 FR-014): "dangerous" (≥1 hard-tier baseline finding),
	// "warnings" (≥1 soft-tier baseline finding), else "clean". It is derived
	// by the SAME predicate as the server-list summary (GetScanSummary), so
	// the report page can never disagree with the server verdict — a tierless
	// deep-scan/external finding never moves it, regardless of threat_level.
	Verdict string `json:"verdict"`
	// FindingCounts buckets findings identically to ScanSummary.FindingCounts
	// (hard-tier → dangerous; tierless "dangerous" → warning: informs, never
	// gates), keeping the report page consistent with the server list.
	FindingCounts  *FindingCounts `json:"finding_counts,omitempty"`
	ScannedAt      time.Time      `json:"scanned_at"`
	Reports        []ScanReport   `json:"reports"`
	ScannersRun    int            `json:"scanners_run"`    // How many scanners actually produced results
	ScannersFailed int            `json:"scanners_failed"` // How many scanners failed
	ScannersTotal  int            `json:"scanners_total"`  // Total scanners attempted
	ScanComplete   bool           `json:"scan_complete"`   // True only if at least one scanner succeeded
	EmptyScan      bool           `json:"empty_scan"`      // True when scanners ran but had no files to analyze
	// Two-pass scan tracking
	Pass1Complete bool `json:"pass1_complete"` // Security scan (fast) done
	Pass2Complete bool `json:"pass2_complete"` // Supply chain audit done
	Pass2Running  bool `json:"pass2_running"`  // Supply chain audit in progress
	// Scan context from the primary job (for report page display)
	ScanContext     *ScanContext       `json:"scan_context,omitempty"`
	ScannerStatuses []ScannerJobStatus `json:"scanner_statuses,omitempty"` // Per-scanner execution logs
	// DeepScan is the opt-in heavy-layer availability descriptor (Spec 077 US3),
	// mirrored from ScanSummary so the report page can render the informational
	// deep-scan banner. Informational only — a failed or unavailable deep scanner
	// never changes the baseline verdict. nil/omitted when deep scan is disabled.
	DeepScan *DeepScanDescriptor `json:"deep_scan,omitempty"`
}

AggregatedReport combines results from all scanners for a single scan job

func AggregateReports

func AggregateReports(jobID, serverName string, reports []*ScanReport) *AggregatedReport

AggregateReports combines multiple scan reports into an aggregated report. Note: scannersTotal and scannersFailed should be provided by the caller from the ScanJob.ScannerStatuses, since reports only contains successful results.

func AggregateReportsWithJobStatus

func AggregateReportsWithJobStatus(jobID, serverName string, reports []*ScanReport, job *ScanJob) *AggregatedReport

AggregateReportsWithJobStatus combines reports and enriches with scanner failure info from the job.

type ApprovalIncarnationBinder added in v0.71.0

type ApprovalIncarnationBinder interface {
	// CaptureApprovalIncarnation returns expected when it is > 0 (the
	// incarnation the caller reviewed), otherwise the server's current one.
	CaptureApprovalIncarnation(serverName string, expected int64) (int64, error)
	WithServerApprovalLockAt(serverName string, inc int64, fn func() error) error
	UnquarantineServerAt(serverName string, inc int64) error
}

ApprovalIncarnationBinder is an OPTIONAL capability of the ServerUnquarantiner (Spec 116 FR-014, FR-015): bind a scanner approval to the incarnation of the server it reviewed. The approval captures the incarnation when it starts, saves the baseline and blocks under the server's approval lock only while the stored row still carries it, and unquarantines through a commit that expects it — so a remove and re-add of the name in between can never release, or hand a baseline to, the replacement.

type BundleActivation added in v0.72.0

type BundleActivation struct {
	// Digest is the full SHA-256 of the newly serving bundle.
	Digest string
	// Sequence is the decimal-string manifest sequence ("" when none).
	Sequence string
	// Authority is the signing authority ("publisher" or "operator").
	Authority string
	// Source is BundleSourceFile or BundleSourceFetch.
	Source string
	// Rollback is true when the activation was an explicit rollback.
	Rollback bool
	// PreviousDigest is the digest that served before ("" for the embedded
	// default or a first activation).
	PreviousDigest string
	// ActivatedAt is the history row's timestamp.
	ActivatedAt time.Time
	// Seq orders activations of this process: assigned (1, 2, ...) in commit
	// order as the event is dispatched. Observers run on separate goroutines,
	// so arrival order is not commit order; an observer that must not act on a
	// stale event compares Seq. Zero means "not a dispatched event" (a
	// synthetic catch-up activation).
	Seq uint64
}

BundleActivation is the payload handed to activation observers after a history row was written (an activation or a rollback). It carries no bundle bytes and no patterns.

type BundleCheck added in v0.53.0

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

BundleCheck is the bundle-backed detect.Check (spec 086 FR-003). It holds the pre-compiled, pre-sorted runnable rules and emits one hard-tier Signal per regex hit against a tool's description. Pure, total, and deterministic per the detect.Check contract; regexp is allowed in any package so no detect import guard is violated.

func (*BundleCheck) ID added in v0.53.0

func (*BundleCheck) ID() string

ID implements detect.Check with a stable identifier.

func (*BundleCheck) Inspect added in v0.53.0

func (c *BundleCheck) Inspect(tool detect.ToolView, _ detect.RegistryView) []detect.Signal

Inspect ranges the pre-sorted runnable rules and emits one hard-tier Signal for each regex that matches the tool's description. Order follows the bundle's (id, detector) sort, so output is byte-stable across calls.

type BundleInfo added in v0.53.0

type BundleInfo struct {
	// Source is BundleSourceEmbedded, BundleSourceFile or BundleSourceFetch.
	Source string `json:"source"`
	// Path is the configured filesystem path, when Source is "file".
	Path string `json:"path,omitempty"`
	// BundleVersion / SchemaVersion are the corpus's own declared versions.
	BundleVersion string `json:"bundle_version,omitempty"`
	SchemaVersion string `json:"schema_version,omitempty"`
	// SignatureCount is the bundle's self-declared signature count.
	SignatureCount int `json:"signature_count"`
	// RunnableRules is how many rules are LIVE in the offline tier; SkippedRules
	// and DeclaredSkipped are the not-runnable / bundle-declared-skipped
	// remainder (FR-006/FR-007) — un-evaluated coverage, never clean coverage.
	RunnableRules   int `json:"runnable_rules"`
	SkippedRules    int `json:"skipped_rules"`
	DeclaredSkipped int `json:"declared_skipped"`
	// GeneratedAt is the corpus freshness stamp. It is the bundle's own
	// `generated_at` key when present; for a file-sourced bundle without one it
	// falls back to the file's modification time, so a years-stale corpus is
	// distinguishable from a fresh export.
	GeneratedAt string `json:"generated_at,omitempty"`
	// Fingerprint is the first 12 hex chars of the SHA-256 of the corpus bytes:
	// a stable identity an operator (or automation) can compare across hosts
	// without shipping the whole file around.
	Fingerprint string `json:"fingerprint,omitempty"`
	// LoadedAt is when this corpus became active in this process.
	LoadedAt time.Time `json:"loaded_at"`
	// LoadError is the reason the LAST configured-path load failed, if any. The
	// previously active (or embedded) corpus stays live — a bundle problem must
	// never leave the scanner with no signatures — but the failure is surfaced
	// here rather than swallowed.
	LoadError string `json:"load_error,omitempty"`

	// FullDigest is the complete lowercase-hex SHA-256 of the bundle bytes —
	// the ONLY value rollback accepts (FR-010). Fingerprint stays the 12-hex
	// human label beside it.
	FullDigest string `json:"full_digest,omitempty"`
	// Sequence is the manifest sequence as published (decimal string), "" when
	// the bundle carries none.
	Sequence string `json:"sequence,omitempty"`
	// Authority is the signing root serving this bundle: "publisher" (the
	// embedded default, or verified against a publisher key), "operator", or ""
	// for an unsigned external bundle.
	Authority string `json:"authority,omitempty"`
	// TrustEpoch is the epoch the bundle was published under.
	TrustEpoch uint64 `json:"trust_epoch"`
	// SignatureVerified reports whether the active bundle's detached signature
	// verified. Always false for the embedded default (it is binary-trusted).
	SignatureVerified bool `json:"signature_verified"`
	// StalenessDays is the whole days since GeneratedAt (nil when unknown).
	StalenessDays *int `json:"staleness_days,omitempty"`
	// CoverageDegraded suspends scan-mode auto-approval; DegradedReason says
	// why (one of the Degraded* constants).
	CoverageDegraded bool   `json:"coverage_degraded"`
	DegradedReason   string `json:"degraded_reason,omitempty"`
	// Pinned is true while an operator rollback pin governs activation.
	Pinned bool `json:"pinned,omitempty"`
	// Rollback is true when the active bundle was activated by an explicit
	// rollback.
	Rollback bool `json:"rollback,omitempty"`
	// LastRejection is the most recent refused candidate. It is retained
	// across a later successful load so "what did it refuse, and when"
	// survives.
	LastRejection *BundleRejection `json:"last_rejection,omitempty"`

	// LastCheckedAt is the end of the most recent pipeline run, including
	// no-op runs the idempotence short-circuit skipped.
	LastCheckedAt *time.Time `json:"last_checked_at,omitempty"`
	// LastActivatedAt is when the serving external bundle was activated; nil
	// for the embedded default.
	LastActivatedAt *time.Time `json:"last_activated_at,omitempty"`
	// Stale and StaleAfterDays are computed at read time next to
	// StalenessDays; a future generated_at is never stale. StaleAfterDays nil
	// means the flag is not evaluated.
	Stale          bool `json:"stale,omitempty"`
	StaleAfterDays *int `json:"stale_after_days,omitempty"`
	// Refresh is the refresh-cycle status (nil before any cycle or setting is
	// known). Reprotect is the post-activation re-protection sweep status,
	// set from the server through SetReprotectStatus.
	Refresh   *BundleRefreshStatus   `json:"refresh,omitempty"`
	Reprotect *BundleReprotectStatus `json:"reprotect,omitempty"`
}

BundleInfo is the operator-facing status of the TPA signature corpus the scanner is actually running (spec 086 FR-019, GH #938 finding 2). Before this existed there was no supported way to answer "which signatures is my proxy running, and how old are they?" — the bundle was embed-only and its single load report went to an unconfigured global logger.

func BundleStatus added in v0.53.0

func BundleStatus() BundleInfo

BundleStatus returns a snapshot of the active corpus for the operator-facing surfaces (REST /api/v1/security/overview, `mcpproxy security overview`). It lazily installs the embedded default so a caller that never configured a bundle still gets a truthful answer instead of a zero value.

func RefreshBundle added in v0.72.0

func RefreshBundle(ctx context.Context, logger *zap.Logger) BundleInfo

RefreshBundle is the manual refresh (`security bundle refresh`, B20): one joined cycle (file leg plus fetch leg), trigger "manual". When no running refresher is installed it falls back to ReloadBundle, so a manual refresh still picks up a dropped file.

func ReloadBundle added in v0.72.0

func ReloadBundle(logger *zap.Logger) BundleInfo

ReloadBundle re-runs the pipeline with the last applied policy and returns the resulting status. It is the local, network-free refresh the REST/CLI reload action uses (B20): it never issues a request, whatever the fetch settings.

func RollbackBundle added in v0.72.0

func RollbackBundle(req BundleRollbackRequest, logger *zap.Logger) (BundleInfo, error)

RollbackBundle performs the explicit rollback of FR-010. On success the target serves, is pinned, the release rolled away from is deny-listed, the watermark is untouched and the override is logged at WARN. A refusal returns a *BundleRollbackRefused (also recorded as LastRejection); a malformed request returns ErrBundleRollbackUsage. The returned BundleInfo is the status after the call in every case.

func UnpinBundle added in v0.72.0

func UnpinBundle(logger *zap.Logger) (BundleInfo, error)

UnpinBundle clears the rollback pin of the active signing root (FR-010) and re-validates the serving bundle WITHOUT it: a rolled-back target below the watermark no longer passes and the install falls back to the embedded default under the FR-009a rules, exactly as a restart would. The deny-list is kept. Unpinning when nothing is pinned is a quiet no-op.

type BundleRefreshStatus added in v0.72.0

type BundleRefreshStatus struct {
	FetchEnabled bool `json:"fetch_enabled"`
	// FetchHost is the host of the configured fetch URL ("" when none).
	FetchHost       string `json:"fetch_host,omitempty"`
	IntervalSeconds int    `json:"interval_seconds"`
	// LastTrigger, LastOutcome and LastReason use the closed vocabularies above.
	LastTrigger         string     `json:"last_trigger,omitempty"`
	LastOutcome         string     `json:"last_outcome,omitempty"`
	LastReason          string     `json:"last_reason,omitempty"`
	LastAttemptAt       *time.Time `json:"last_attempt_at,omitempty"`
	ConsecutiveFailures int        `json:"consecutive_failures"`
	NextCheckAt         *time.Time `json:"next_check_at,omitempty"`
	// FetchState and FetchReason are the fetch leg's own last answer (one of the
	// RefreshOutcome* values and its reason), kept apart from LastOutcome: a file
	// activation owns the merged cycle outcome but must not hide a fetch leg that
	// cannot run (B16 warning 3).
	FetchState  string `json:"fetch_state,omitempty"`
	FetchReason string `json:"fetch_reason,omitempty"`
}

BundleRefreshStatus is the refresh-cycle status merged into BundleInfo at read time (B15). It carries the host only, never the URL (B12).

type BundleRefresher added in v0.72.0

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

BundleRefresher owns the refresh lifecycle. Start/Stop follow the telemetry.Service pattern: Stop cancels and joins, a Start after Stop is a no-op.

func CurrentBundleRefresher added in v0.72.0

func CurrentBundleRefresher() *BundleRefresher

CurrentBundleRefresher returns the installed refresher, or nil. The runtime uses it on Close to clear the slot only if it still points at its own instance.

func NewBundleRefresher added in v0.72.0

func NewBundleRefresher(opts BundleRefresherOptions) *BundleRefresher

NewBundleRefresher builds a refresher; it does nothing until Start.

func (*BundleRefresher) Nudge added in v0.72.0

func (r *BundleRefresher) Nudge(sec *config.SecurityConfig)

Nudge tells the refresher the security config changed: it re-reads the fetch and trust settings, bumps the generation (superseding an in-flight download whose inputs changed) and moves the due time. Non-blocking; a Nudge after Stop began is a no-op.

A nil sec means the security block was removed: the default policy applies, exactly as configureTPABundle(nil) applied it to the runtime.

func (*BundleRefresher) Refresh added in v0.72.0

func (r *BundleRefresher) Refresh(ctx context.Context, logger *zap.Logger) BundleInfo

Refresh runs one cycle now (trigger "manual"), joining an in-flight cycle if there is one, and returns the resulting status. Without a running loop it is ReloadBundle.

func (*BundleRefresher) Running added in v0.72.0

func (r *BundleRefresher) Running() bool

Running reports whether the loop goroutine is alive.

func (*BundleRefresher) Start added in v0.72.0

func (r *BundleRefresher) Start(ctx context.Context)

Start begins the cycle loop, bound to ctx. A second Start, or a Start after Stop, is a no-op. The loop timer is created before Start returns.

func (*BundleRefresher) Stop added in v0.72.0

func (r *BundleRefresher) Stop()

Stop cancels any in-flight cycle and returns only after the loop goroutine and every cycle goroutine exited. Idempotent.

type BundleRefresherOptions added in v0.72.0

type BundleRefresherOptions struct {
	// Clock replaces the real clock and timers.
	Clock RefreshClock
	// Rand returns a uniform value in [0,1) for jitter.
	Rand func() float64
	// HTTPClient, when set, is used as is; otherwise one is built from
	// Transport and the egress rules.
	HTTPClient *http.Client
	// Transport replaces the base transport of the built client.
	Transport http.RoundTripper
	// Resolver replaces DNS for the egress checks.
	Resolver FetchResolver
	// ConfigProvider returns the live security config each cycle. The
	// refresher never takes Runtime.mu to read it. The refresher also calls it
	// inside the bundle runtime's critical section (the freshness checks of the
	// file leg and of the offer), so it must be quick and must not call back into
	// the bundle runtime.
	ConfigProvider func() *config.SecurityConfig
	// Logger is the injected logger (nil => no-op).
	Logger *zap.Logger
	// Version is the mcpproxy version for the User-Agent header.
	Version string
	// IntervalOverride is a test seam that replaces the configured interval
	// and bypasses the 1h floor; zero means "use the config".
	IntervalOverride time.Duration
}

BundleRefresherOptions are the construction-time seams of a BundleRefresher. Every field is optional; the zero value selects the production defaults.

type BundleRejection added in v0.72.0

type BundleRejection struct {
	// Reason is one of the Reject* constants; the only field to branch on.
	Reason string `json:"reason"`
	// Detail is a short human string (which ceiling, which key id, which
	// epoch, the bundlesig contract code). Never parsed.
	Detail string    `json:"detail,omitempty"`
	At     time.Time `json:"at"`
}

BundleRejection is one refused candidate (FR-020).

type BundleReprotectStatus added in v0.72.0

type BundleReprotectStatus struct {
	// State is one of the ReprotectState* constants.
	State string `json:"state"`
	// Reason qualifies suspended and failed (for example
	// ReprotectReasonAutoBaselineScanOff).
	Reason          string     `json:"reason,omitempty"`
	LastCompletedAt *time.Time `json:"last_completed_at,omitempty"`
	ServersScanned  int        `json:"servers_scanned"`
	ServersWithHits int        `json:"servers_with_hits"`
}

BundleReprotectStatus is the post-activation re-protection sweep status (Spec 101 FR-019, B17), set from the server through SetReprotectStatus.

type BundleRollbackRefused added in v0.72.0

type BundleRollbackRefused struct{ Rejection BundleRejection }

BundleRollbackRefused is returned when the target was refused after the request was well-formed. The refusal is also recorded as the install's LastRejection; last-known-good keeps serving.

func (*BundleRollbackRefused) Error added in v0.72.0

func (e *BundleRollbackRefused) Error() string

type BundleRollbackRequest added in v0.72.0

type BundleRollbackRequest struct {
	// Embedded rolls back to the corpus compiled into this binary.
	Embedded bool `json:"embedded,omitempty"`
	// Path is where to find the target bundle (and Path+".sig"); a hint only.
	Path string `json:"path,omitempty"`
	// Digest is the 64-hex SHA-256 the loaded artifact must have.
	Digest string `json:"digest"`
}

BundleRollbackRequest names the rollback target. Exactly one of Embedded and Path is set; Digest is the full lowercase-hex SHA-256 of the target's bytes.

type Candidate added in v0.72.0

type Candidate struct {
	// Bundle is the exact candidate bytes. They are verified and then parsed
	// from this one buffer (FR-006): nothing re-reads Path.
	Bundle []byte
	// Sidecar is the detached-signature sidecar; meaningful only when
	// SidecarPresent. A present-but-invalid sidecar is a rejection, never a
	// fallback to the unsigned path (tasks.md A7).
	Sidecar        []byte
	SidecarPresent bool
	// Source is the BundleSource* label; Path is informational only.
	Source string
	Path   string
	// ModTime is the modification time of the descriptor the bundle was read
	// from (zero when unknown); the freshness fallback for an unsigned drop
	// without generated_at. Never re-read from the path.
	ModTime time.Time
}

Candidate is one bundle offered for activation, independent of where it came from. The file-drop adapter builds it from two bounded reads; Spec 087's fetch adapter builds the same struct from a download (FR-018). Everything the pipeline decides is a function of these bytes and the evalEnv.

type DeepScanDescriptor added in v0.47.0

type DeepScanDescriptor struct {
	// Enabled reflects security.deep_scan.enabled (default false).
	Enabled bool `json:"enabled"`
	// Ran is true when at least one deep scanner executed this scan.
	Ran bool `json:"ran"`
	// Available is false when Docker/source-extraction/prereqs are unavailable.
	Available bool `json:"available"`
	// ScannersFailed lists per-scanner best-effort failures (informational).
	ScannersFailed []DeepScanScannerFailure `json:"scanners_failed,omitempty"`
	// SkippedScanners lists Docker scanners the user enabled that are being
	// skipped because deep scan is off (informational; disabled state only).
	SkippedScanners []string `json:"skipped_scanners,omitempty"`
}

DeepScanDescriptor reports the informational status of the opt-in "deep scan" layer (Docker-based scanners + source extraction) separately from the baseline verdict (Spec 077 FR-008, US3). A disabled, unavailable, or failed deep scan is surfaced here as a quiet note — it never downgrades an otherwise clean baseline to "degraded" and never gates approval (FR-007/FR-021).

Invariant: when Enabled is false, Ran and Available are false and ScannersFailed is empty; SkippedScanners is only populated in that disabled state. The descriptor itself is ALWAYS emitted (audit FIX 3a), so a deep-scan-off scan observably reports enabled=false rather than omitting the field.

type DeepScanScannerFailure added in v0.47.0

type DeepScanScannerFailure struct {
	ID     string `json:"id"`
	Reason string `json:"reason"`
}

DeepScanScannerFailure names a single deep scanner that could not run and why. It is informational only and never affects the baseline verdict.

type DockerRunner

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

DockerRunner executes Docker operations for scanner containers.

Security note: the scanner runs untrusted container images (vulnerability scanners, SBOM generators, etc). It MUST NOT inherit the user's ambient credentials (AWS, GitHub, Anthropic tokens, …). We therefore:

  1. Resolve the docker binary once via shellwrap.ResolveDockerPath — this picks up Homebrew / Docker Desktop / Colima installs even when mcpproxy was launched from a GUI with a minimal PATH, WITHOUT re-spawning a login shell on every invocation (important for hot paths like the ~2s health check loop).
  2. Invoke docker directly with cmd.Env set to a minimal PATH+HOME allowlist via shellwrap.MinimalEnv, so environment-based secrets do not leak into the docker CLI's subprocess tree.

func NewDockerRunner

func NewDockerRunner(logger *zap.Logger) *DockerRunner

NewDockerRunner creates a new DockerRunner

func (*DockerRunner) GetImageDigest

func (d *DockerRunner) GetImageDigest(ctx context.Context, image string) (string, error)

GetImageDigest returns the Docker image digest

func (*DockerRunner) ImageExists

func (d *DockerRunner) ImageExists(ctx context.Context, image string) bool

ImageExists checks if a Docker image exists locally

func (*DockerRunner) IsDockerAvailable

func (d *DockerRunner) IsDockerAvailable(ctx context.Context) bool

IsDockerAvailable checks if Docker daemon is running

func (*DockerRunner) KillContainer

func (d *DockerRunner) KillContainer(ctx context.Context, name string) error

KillContainer forcefully kills a running container

func (*DockerRunner) PullImage

func (d *DockerRunner) PullImage(ctx context.Context, image string) error

PullImage pulls a Docker image with progress logging

func (*DockerRunner) ReadReportFile

func (d *DockerRunner) ReadReportFile(reportDir string) ([]byte, error)

ReadReportFile reads the SARIF report from the report directory

func (*DockerRunner) RemoveImage

func (d *DockerRunner) RemoveImage(ctx context.Context, image string) error

RemoveImage removes a Docker image

func (*DockerRunner) RunScanner

func (d *DockerRunner) RunScanner(ctx context.Context, cfg ScannerRunConfig) (stdout, stderr string, exitCode int, err error)

RunScanner runs a scanner container and returns the exit code and stdout/stderr

func (*DockerRunner) StopContainer

func (d *DockerRunner) StopContainer(ctx context.Context, name string, timeout int) error

StopContainer gracefully stops a container with timeout

type Engine

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

Engine orchestrates parallel scanner execution for a server

func NewEngine

func NewEngine(docker *DockerRunner, registry *Registry, dataDir string, logger *zap.Logger) *Engine

NewEngine creates a new scan orchestration engine

func (*Engine) CancelScan

func (e *Engine) CancelScan(serverName string) error

CancelScan cancels a running scan for a server.

A job stays in activeScans for a short window AFTER executeScan has written its terminal status — the completion callback persists the report and emits the completion event inside that window. Cancelling there must fail rather than succeed: the terminal outcome has already been cloned and is on its way to storage, so flipping Status to cancelled would leave the API reporting a cancellation that the stored job contradicts.

func (*Engine) DetachObsoleteJob added in v0.71.0

func (e *Engine) DetachObsoleteJob(serverName string, obsolete func(*ScanJob) bool) bool

DetachObsoleteJob releases serverName's activeScans slot when obsolete reports that its job belongs to a server identity that no longer exists (Spec 116 FR-014a, review round 1: a removed server's scan must not keep the slot of a same-name replacement). The detached job is NOT cancelled: its goroutine runs to its normal end so its callbacks still release the temporary source directory, and every write it makes is bound to its own (obsolete) incarnation and dropped by storage. Its clearActiveJob then finds the slot not held by it and leaves a replacement's job alone. It reports whether a job was detached.

func (*Engine) GetActiveJob

func (e *Engine) GetActiveJob(serverName string) *ScanJob

GetActiveJob returns a snapshot of the active scan job for a server, or nil when no scan is running.

It MUST be a snapshot: the scan goroutines keep writing Status, CompletedAt and ScannerStatuses on the live record until the job leaves activeScans, so handing the live pointer to a REST reader (GET /api/v1/security/scan/status, which JSON-encodes it) is a data race.

func (*Engine) StartScan

func (e *Engine) StartScan(_ context.Context, req ScanRequest, callback ScanCallback) (*ScanJob, error)

StartScan begins a scan of the specified server Returns the scan job immediately; scanning runs in the background

func (*Engine) StartScanBound added in v0.72.0

func (e *Engine) StartScanBound(execCtx context.Context, req ScanRequest, callback ScanCallback) (*ScanJob, error)

StartScanBound is StartScan with a caller-owned execution context: the scan runs under execCtx instead of a detached one, so the caller's lifecycle (a sweep, a shutdown) ends it. The returned job's Done channel closes once the scan goroutine has returned, i.e. after its completion callback ran, so the caller can join the worker before the stores it writes to close.

type EnvRequirement

type EnvRequirement struct {
	Key    string `json:"key"`
	Label  string `json:"label"`
	Secret bool   `json:"secret"`
}

EnvRequirement represents a required or optional environment variable for a scanner

type EventEmitter

type EventEmitter interface {
	EmitSecurityScanStarted(serverName string, scanners []string, jobID string)
	EmitSecurityScanProgress(serverName, scannerID, status string, progress int)
	EmitSecurityScanCompleted(serverName string, findingsSummary map[string]int)
	EmitSecurityScanFailed(serverName, scannerID, errMsg string)
	EmitSecurityIntegrityAlert(serverName, alertType, action string)
	// EmitSecurityScannerChanged signals that a scanner plugin's state has
	// changed (e.g., background pull started/finished/failed) so the web UI
	// can refresh its scanner list without polling.
	EmitSecurityScannerChanged(scannerID, status, errMsg string)
	// EmitSecurityScanTelemetry records ONE anonymous, counts-only sample for a
	// terminal scan JOB. It is deliberately separate from the UI-facing
	// EmitSecurityScanCompleted/EmitSecurityScanFailed events, which fire per
	// SCANNER and per PASS and would therefore over-count: the unit measured
	// here is "one non-deep-scan (Pass 1) scan job".
	//
	// Only the scanner package knows a job's pass and dry-run status, so the
	// decision of whether a job counts lives here (scanCallbackAdapter) rather
	// than in the emitter. Implementations must accept counts only:
	// findingsBySeverity is severity -> count and carries no server name,
	// scanner id, rule id, or free text.
	EmitSecurityScanTelemetry(completed bool, findingsBySeverity map[string]int)
}

EventEmitter defines how the service emits events

type FetchResolver added in v0.72.0

type FetchResolver interface {
	LookupIPAddr(ctx context.Context, host string) ([]net.IPAddr, error)
}

FetchResolver is the DNS seam of the fetch adapter, satisfied by *net.Resolver. Tests inject a fake to exercise the egress rules without the network.

type FindingCounts

type FindingCounts struct {
	Dangerous int `json:"dangerous"`
	Warning   int `json:"warning"`
	Info      int `json:"info"`
	Total     int `json:"total"`
}

FindingCounts groups findings by user-facing threat level.

type IncarnationServerApprovalCommitter added in v0.71.0

type IncarnationServerApprovalCommitter interface {
	ServerApprovalCommitter
	CommitServerApprovalAt(serverName string, inc int64, blocks []string, expected map[string]string, by string, commit func() error) (int, error)
}

IncarnationServerApprovalCommitter extends ServerApprovalCommitter with the Spec 116 incarnation binding: CommitServerApprovalAt runs the same locked section but first checks (under the approval lock) that the stored row still carries incarnation inc, returning ErrServerReplaced otherwise without recording the marker or running commit.

type IncarnationStorage added in v0.71.0

type IncarnationStorage interface {
	SaveScanJobIfIncarnation(job *ScanJob, inc int64) (bool, error)
	SaveScanReportIfIncarnation(report *ScanReport, inc int64) (bool, error)
}

IncarnationStorage is an OPTIONAL capability of the Storage: scan job and report saves conditional on the server's stored row carrying the job's incarnation, in one transaction (Spec 116 FR-014a, research D12).

type IntegrityBaseline

type IntegrityBaseline struct {
	ServerName    string            `json:"server_name"`
	ImageDigest   string            `json:"image_digest"`
	SourceHash    string            `json:"source_hash"`
	LockfileHash  string            `json:"lockfile_hash"`
	DiffManifest  []string          `json:"diff_manifest,omitempty"`
	ToolHashes    map[string]string `json:"tool_hashes,omitempty"`
	ScanReportIDs []string          `json:"scan_report_ids,omitempty"`
	ApprovedAt    time.Time         `json:"approved_at"`
	ApprovedBy    string            `json:"approved_by"`
}

IntegrityBaseline represents the approved integrity state for a server

func (*IntegrityBaseline) MarshalBinary

func (b *IntegrityBaseline) MarshalBinary() ([]byte, error)

MarshalBinary implements encoding.BinaryMarshaler

func (*IntegrityBaseline) UnmarshalBinary

func (b *IntegrityBaseline) UnmarshalBinary(data []byte) error

UnmarshalBinary implements encoding.BinaryUnmarshaler

type IntegrityCheckResult

type IntegrityCheckResult struct {
	ServerName string               `json:"server_name"`
	Passed     bool                 `json:"passed"`
	CheckedAt  time.Time            `json:"checked_at"`
	Violations []IntegrityViolation `json:"violations,omitempty"`
}

IntegrityCheckResult holds the result of an integrity check

type IntegrityViolation

type IntegrityViolation struct {
	Type     string `json:"type"`
	Message  string `json:"message"`
	Expected string `json:"expected,omitempty"`
	Actual   string `json:"actual,omitempty"`
}

IntegrityViolation describes a specific integrity check failure

type NoopCallback

type NoopCallback struct{}

NoopCallback is a no-op implementation of ScanCallback

func (*NoopCallback) OnScanCompleted

func (n *NoopCallback) OnScanCompleted(_ *ScanJob, _ []*ScanReport)

func (*NoopCallback) OnScanFailed

func (n *NoopCallback) OnScanFailed(_ *ScanJob, _ error)

func (*NoopCallback) OnScanStarted

func (n *NoopCallback) OnScanStarted(_ *ScanJob)

func (*NoopCallback) OnScannerCompleted

func (n *NoopCallback) OnScannerCompleted(_ *ScanJob, _ string, _ *ScanReport)

func (*NoopCallback) OnScannerFailed

func (n *NoopCallback) OnScannerFailed(_ *ScanJob, _ string, _ error)

func (*NoopCallback) OnScannerStarted

func (n *NoopCallback) OnScannerStarted(_ *ScanJob, _ string)

type NoopEmitter

type NoopEmitter struct{}

NoopEmitter is a no-op implementation of EventEmitter

func (*NoopEmitter) EmitSecurityIntegrityAlert

func (n *NoopEmitter) EmitSecurityIntegrityAlert(string, string, string)

func (*NoopEmitter) EmitSecurityScanCompleted

func (n *NoopEmitter) EmitSecurityScanCompleted(string, map[string]int)

func (*NoopEmitter) EmitSecurityScanFailed

func (n *NoopEmitter) EmitSecurityScanFailed(string, string, string)

func (*NoopEmitter) EmitSecurityScanProgress

func (n *NoopEmitter) EmitSecurityScanProgress(string, string, string, int)

func (*NoopEmitter) EmitSecurityScanStarted

func (n *NoopEmitter) EmitSecurityScanStarted(string, []string, string)

func (*NoopEmitter) EmitSecurityScanTelemetry added in v0.53.0

func (n *NoopEmitter) EmitSecurityScanTelemetry(bool, map[string]int)

func (*NoopEmitter) EmitSecurityScannerChanged

func (n *NoopEmitter) EmitSecurityScannerChanged(string, string, string)

type QueueItem

type QueueItem struct {
	ServerName string    `json:"server_name"`
	Status     string    `json:"status"`
	JobID      string    `json:"job_id,omitempty"`
	Error      string    `json:"error,omitempty"`
	StartedAt  time.Time `json:"started_at,omitempty"`
	DoneAt     time.Time `json:"done_at,omitempty"`
	SkipReason string    `json:"skip_reason,omitempty"` // Why the scan was skipped
}

QueueItem represents a single scan request in the queue

type QueueProgress

type QueueProgress struct {
	BatchID   string      `json:"batch_id"`
	Status    string      `json:"status"` // running, completed, cancelled
	Total     int         `json:"total"`
	Pending   int         `json:"pending"`
	Running   int         `json:"running"`
	Completed int         `json:"completed"`
	Failed    int         `json:"failed"`
	Skipped   int         `json:"skipped"`
	Cancelled int         `json:"cancelled"`
	StartedAt time.Time   `json:"started_at"`
	DoneAt    time.Time   `json:"done_at,omitempty"`
	Items     []QueueItem `json:"items"`
}

QueueProgress tracks overall scan-all progress

type RefreshClock added in v0.72.0

type RefreshClock interface {
	Now() time.Time
	// NewTimer returns a timer that fires once after d.
	NewTimer(d time.Duration) RefreshTimer
}

RefreshClock is the time seam of the scheduler. Tests inject a fake whose timers fire on demand; production uses the real clock (nil Clock).

type RefreshOutcomeClass added in v0.72.0

type RefreshOutcomeClass string

RefreshOutcomeClass is the coarse class of one refresh cycle handed to the refresh observer (SetBundleRefreshObserver). It is scanner's own enum; internal/telemetry must not import scanner, so internal/server maps it to telemetry.TPABundleRefreshClass (tasks B21).

const (
	// RefreshClassActivated: the cycle activated a bundle.
	RefreshClassActivated RefreshOutcomeClass = "activated"
	// RefreshClassRejected: the pipeline refused a candidate.
	RefreshClassRejected RefreshOutcomeClass = "rejected"
	// RefreshClassUnavailable: fetch_unavailable or channel_invalid.
	RefreshClassUnavailable RefreshOutcomeClass = "unavailable"
	// RefreshClassUnchanged: unchanged, not_modified, superseded or disabled.
	RefreshClassUnchanged RefreshOutcomeClass = "unchanged"
)

type RefreshTimer added in v0.72.0

type RefreshTimer interface {
	// C delivers the fire time.
	C() <-chan time.Time
	Stop() bool
	Reset(d time.Duration) bool
}

RefreshTimer is the timer half of RefreshClock, shaped like *time.Timer.

type Registry

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

Registry manages the scanner plugin registry.

Concurrency contract: the *ScannerPlugin records in `scanners` are owned by the registry and may only be read or written while holding `mu`. Get and List therefore return defensive copies, and every mutation of a stored record goes through a locked method on this type (UpdateStatus, SetConfiguredEnv, SetRuntimeConfig). Callers must never write to a plugin they got back from Get/List and expect the registry to see it — a stored record mutated outside the lock races every concurrent reader, including the REST scanner-list path.

func NewRegistry

func NewRegistry(dataDir string, logger *zap.Logger) *Registry

NewRegistry creates a new scanner registry

func (*Registry) Get

func (r *Registry) Get(id string) (*ScannerPlugin, error)

Get returns a defensive copy of the scanner with the given ID. Mutating the result does NOT change registry state — use UpdateStatus/SetConfiguredEnv/ SetRuntimeConfig to write it back under the lock.

func (*Registry) InProcessRunnableIDs added in v0.61.0

func (r *Registry) InProcessRunnableIDs() []string

InProcessRunnableIDs returns the IDs of in-process scanners whose status means the engine will actually run them (installed or configured), sorted.

It exists so a caller can count the always-on in-process baseline without copying the whole plugin set: resolving the predicate here keeps the read under the same lock as the write, and returns only the ids.

func (*Registry) List

func (r *Registry) List() []*ScannerPlugin

List returns all known scanners (bundled + user) sorted by ID so that API consumers, CLI output, and the web UI all see a deterministic order.

The returned plugins are defensive copies: the caller may read and mutate them freely without racing a concurrent install/pull.

func (*Registry) Register

func (r *Registry) Register(s *ScannerPlugin) error

Register adds a custom scanner to the registry It validates the manifest and saves to user registry file

func (*Registry) SetConfiguredEnv added in v0.61.0

func (r *Registry) SetConfiguredEnv(id string, env map[string]string) error

SetConfiguredEnv replaces a scanner's configured env under the registry lock, so the engine picks up newly stored API keys without a restart. The map is copied — the caller may keep mutating the one it passed in.

func (*Registry) SetRuntimeConfig added in v0.61.0

func (r *Registry) SetRuntimeConfig(id string, env map[string]string, imageOverride string) error

SetRuntimeConfig replaces a scanner's configured env AND image override in a single locked update, so a concurrent reader never observes a half-applied configuration (new env with the old image, or vice versa).

func (*Registry) Unregister

func (r *Registry) Unregister(id string) error

Unregister removes a custom scanner from the registry Cannot unregister bundled scanners

func (*Registry) UpdateStatus

func (r *Registry) UpdateStatus(id, status string) error

UpdateStatus updates the status of a scanner in the registry

type ReportSummary

type ReportSummary struct {
	Critical  int `json:"critical"`
	High      int `json:"high"`
	Medium    int `json:"medium"`
	Low       int `json:"low"`
	Info      int `json:"info"`
	Total     int `json:"total"`
	Dangerous int `json:"dangerous"`  // Threat level: tool poisoning, prompt injection
	Warnings  int `json:"warnings"`   // Threat level: rug pull, high CVEs
	InfoLevel int `json:"info_level"` // Threat level: low CVEs, informational
}

ReportSummary provides counts by severity and threat level

func SummarizeFindings

func SummarizeFindings(findings []ScanFinding) ReportSummary

SummarizeFindings produces a ReportSummary from findings

type ResolvedSource

type ResolvedSource struct {
	SourceDir      string   // Host directory containing source files
	ContainerID    string   // Docker container ID (if applicable)
	ContainerOwner string   // Server name that owns ContainerID, per the com.mcpproxy.server label (verified, not just name-matched)
	ContainerImage string   // Docker image reference (for "container_image" input)
	ServerURL      string   // URL for mcp_connection input (HTTP/SSE servers)
	Method         string   // How source was resolved: "docker_extract", "container_image", "working_dir", "local_path", "url", "manual"
	Cleanup        func()   // Cleanup function (removes temp dirs)
	Files          []string // List of files found in source dir (capped)
	TotalFiles     int      // Total file count
	TotalSize      int64    // Total size in bytes
}

ResolvedSource contains the resolved source information for scanning

type ReviewedServerApprover added in v0.71.0

type ReviewedServerApprover interface {
	ServerApprovalCommitter
	FinishServerApproval(serverName string) error
}

ReviewedServerApprover is the Spec 117 PR-2 (#1566) form of the approval commit capability. Its CommitServerApproval runs the whole server approval in one critical section under the per-server tool-approval lock: validate expected (the review binding; nil = unbound), record the tool baseline, run commit (the integrity baseline + blocks), promote the pending tools present at that moment, and clear the quarantine in storage, config and file. A stale binding returns *toolreview.StaleToolReviewError with nothing written. FinishServerApproval then runs the rest without the lock (activity record, upstream/index refresh) and promotes nothing, so a tool filed after the commit stays pending (FR-012). When the unquarantiner implements it the scanner never calls UnquarantineServer for an approval.

type SARIFArtifactLocation

type SARIFArtifactLocation struct {
	URI string `json:"uri"`
}

SARIFArtifactLocation describes a file path

type SARIFConfiguration

type SARIFConfiguration struct {
	Level string `json:"level,omitempty"`
}

SARIFConfiguration holds rule configuration

type SARIFDriver

type SARIFDriver struct {
	Name    string      `json:"name"`
	Version string      `json:"version,omitempty"`
	Rules   []SARIFRule `json:"rules,omitempty"`
}

SARIFDriver describes the scanner driver

type SARIFLocation

type SARIFLocation struct {
	PhysicalLocation *SARIFPhysicalLocation `json:"physicalLocation,omitempty"`
}

SARIFLocation describes where a finding was detected

type SARIFMessage

type SARIFMessage struct {
	Text string `json:"text"`
}

SARIFMessage holds text content

type SARIFPhysicalLocation

type SARIFPhysicalLocation struct {
	ArtifactLocation *SARIFArtifactLocation `json:"artifactLocation,omitempty"`
	Region           *SARIFRegion           `json:"region,omitempty"`
}

SARIFPhysicalLocation describes the physical file location

type SARIFRegion

type SARIFRegion struct {
	StartLine   int `json:"startLine,omitempty"`
	StartColumn int `json:"startColumn,omitempty"`
	EndLine     int `json:"endLine,omitempty"`
	EndColumn   int `json:"endColumn,omitempty"`
}

SARIFRegion describes a region within a file

type SARIFReport

type SARIFReport struct {
	Version string     `json:"version"`
	Schema  string     `json:"$schema,omitempty"`
	Runs    []SARIFRun `json:"runs"`
}

SARIFReport represents the top-level SARIF 2.1.0 document

func ParseSARIF

func ParseSARIF(data []byte) (*SARIFReport, error)

ParseSARIF parses a SARIF 2.1.0 JSON document

type SARIFResult

type SARIFResult struct {
	RuleID     string          `json:"ruleId,omitempty"`
	Level      string          `json:"level,omitempty"` // "error", "warning", "note", "none"
	Message    SARIFMessage    `json:"message"`
	Locations  []SARIFLocation `json:"locations,omitempty"`
	Properties map[string]any  `json:"properties,omitempty"`
}

SARIFResult represents an individual finding

type SARIFRule

type SARIFRule struct {
	ID               string              `json:"id"`
	ShortDescription *SARIFMessage       `json:"shortDescription,omitempty"`
	FullDescription  *SARIFMessage       `json:"fullDescription,omitempty"`
	DefaultConfig    *SARIFConfiguration `json:"defaultConfiguration,omitempty"`
	HelpURI          string              `json:"helpUri,omitempty"`
	Properties       map[string]any      `json:"properties,omitempty"`
}

SARIFRule defines a detection rule

type SARIFRun

type SARIFRun struct {
	Tool    SARIFTool     `json:"tool"`
	Results []SARIFResult `json:"results"`
}

SARIFRun represents a single scanner execution run

type SARIFTool

type SARIFTool struct {
	Driver SARIFDriver `json:"driver"`
}

SARIFTool describes the scanner that produced results

type ScanAllRequest

type ScanAllRequest struct {
	ScannerIDs  []string // Specific scanners (empty = all installed)
	SkipEnabled bool     // If true, only scan quarantined servers
}

ScanAllRequest defines what to scan

type ScanCallback

type ScanCallback interface {
	OnScanStarted(job *ScanJob)
	OnScannerStarted(job *ScanJob, scannerID string)
	OnScannerCompleted(job *ScanJob, scannerID string, report *ScanReport)
	OnScannerFailed(job *ScanJob, scannerID string, err error)
	OnScanCompleted(job *ScanJob, reports []*ScanReport)
	OnScanFailed(job *ScanJob, err error)
}

ScanCallback receives scan lifecycle events

type ScanContext

type ScanContext struct {
	SourceMethod    string            `json:"source_method"`              // "docker_extract", "working_dir", "local_path", "url", "none"
	SourcePath      string            `json:"source_path"`                // Actual path/URL that was scanned
	DockerIsolation bool              `json:"docker_isolation"`           // Whether server runs in Docker
	ContainerID     string            `json:"container_id,omitempty"`     // Docker container ID (if applicable)
	ContainerOwner  string            `json:"container_owner,omitempty"`  // Server name that owns ContainerID (verified via com.mcpproxy.server label)
	ContainerImage  string            `json:"container_image,omitempty"`  // Docker image used
	ServerProtocol  string            `json:"server_protocol"`            // stdio, http, sse
	ServerCommand   string            `json:"server_command,omitempty"`   // Command used to start server
	ToolsExported   int               `json:"tools_exported,omitempty"`   // Number of tool definitions exported for scanning
	ToolsExportedAt time.Time         `json:"tools_exported_at,omitzero"` // When the exported definitions were read; a definition changed after this was not analysed
	ToolNames       []string          `json:"tool_names,omitempty"`       // Sorted, de-duplicated names of the exported tool definitions (Pass 1)
	ToolHashes      map[string]string `json:"tool_hashes,omitempty"`      // Exported tool name -> hash.ToolDefinitionDigest of the definition analysed; absent on legacy scans
	// ToolContractDigests maps each analysed tool name to the
	// hash.ToolContractDigest (description, input AND output schema) of EVERY
	// contract the scan analysed under that name — the live export and each
	// divergent ingested contract (RT-06). Absent on scans recorded before
	// output schemas were exported; review then treats ToolHashes as
	// output-unaware.
	ToolContractDigests map[string][]string `json:"tool_contract_digests,omitempty"`
	// BundleDigest is the full SHA-256 of the TPA signature bundle whose
	// activation triggered this scan. Set only on a post-activation
	// re-protection scan (Spec 101 FR-019), which analyses cached contracts
	// rather than a fresh export.
	BundleDigest   string   `json:"bundle_digest,omitempty"`
	ScannedFiles   []string `json:"scanned_files,omitempty"` // List of files that were scanned (capped at MaxScannedFiles)
	TotalFiles     int      `json:"total_files"`             // Total file count (may be > len(ScannedFiles) if capped)
	TotalSizeBytes int64    `json:"total_size_bytes"`        // Total size of scanned source
}

ScanContext describes what was scanned and how the source was resolved. This gives users full transparency into what the scanners actually checked.

type ScanFinding

type ScanFinding struct {
	RuleID           string  `json:"rule_id"`
	Severity         string  `json:"severity"`     // critical, high, medium, low, info
	Category         string  `json:"category"`     // SARIF category
	ThreatType       string  `json:"threat_type"`  // User-facing: tool_poisoning, prompt_injection, rug_pull, supply_chain
	ThreatLevel      string  `json:"threat_level"` // User-facing: dangerous, warning, info
	Title            string  `json:"title"`
	Description      string  `json:"description"`
	Location         string  `json:"location,omitempty"`
	Scanner          string  `json:"scanner"`
	HelpURI          string  `json:"help_uri,omitempty"`          // Link to CVE/advisory details
	CVSSScore        float64 `json:"cvss_score,omitempty"`        // CVSS severity score (0-10)
	PackageName      string  `json:"package_name,omitempty"`      // Affected package
	InstalledVersion string  `json:"installed_version,omitempty"` // Current version
	FixedVersion     string  `json:"fixed_version,omitempty"`     // Version with fix
	ScanPass         int     `json:"scan_pass,omitempty"`         // 1 = security scan, 2 = supply chain audit
	Evidence         string  `json:"evidence,omitempty"`          // The text/content that triggered the finding
	// SupplyChainAudit marks findings that belong in the "Supply Chain Audit (CVEs)"
	// UI section regardless of which pass produced them. True only for real CVE/package
	// vulnerabilities (CVE-prefixed rule ID or a populated PackageName). AI scanner and
	// other non-package findings stay false so the UI can route them to their proper
	// threat_type group instead of the CVE section.
	SupplyChainAudit bool `json:"supply_chain_audit,omitempty"`
	// Confidence is the combined 0.0–1.0 confidence of the deterministic
	// tool-scanner (Spec 076). Independent signals on a tool add (capped at
	// 1.0), so agreement raises it. Zero/omitted for findings produced by
	// scanners that do not emit confidence. Additive — see detect.Engine.
	Confidence float64 `json:"confidence,omitempty"`
	// Signals lists the deterministic check IDs that contributed to this
	// finding (e.g. "unicode.hidden", "directive.imperative"), giving operators
	// transparency into why a tool was flagged (Spec 076, FR-010). Additive.
	Signals []string `json:"signals,omitempty"`
	// Tier is "hard" or "soft" (Spec 077). A hard baseline finding gates
	// approval and drives a "dangerous" verdict; a soft finding is review-only.
	// Set from detect output for baseline findings; empty for legacy/external
	// findings that predate the two-tier model. Additive, back-compat.
	Tier string `json:"tier,omitempty"`
	// Sources lists the contributing scanner ids for this finding (e.g.
	// "tpa-descriptions", "cisco-mcp-scanner"). When two scanners agree on the
	// same issue the merged finding lists both (Spec 077 FR-013). ≥1 for
	// findings produced under Spec 077; empty for legacy findings. Additive.
	Sources []string `json:"sources,omitempty"`
	// Spans locate the exact words in the tool's raw text that tripped each
	// contributing check, so the Web UI can highlight them inline in the tool
	// list instead of stranding the operator on a scan-report page with a prose
	// sentence. Offsets are UTF-16 code units (JavaScript string indices) —
	// see detect.Span. Omitted entirely for findings whose checks match
	// normalized text, and for external scanners (Docker/SARIF), which report
	// no offsets at all; a missing key means "no highlight", never "clean".
	// Additive, back-compat.
	Spans []detect.Span `json:"spans,omitempty"`
}

ScanFinding represents an individual security finding

func MergeFindings added in v0.47.0

func MergeFindings(findings []ScanFinding) []ScanFinding

MergeFindings collapses findings from every scanner into a single unified list (Spec 077 FR-010/FR-011). Findings sharing a (rule_id, location) merge into one entry whose Sources lists every contributing scanner. When ≥2 distinct sources independently agree on the same (location, threat_type) — even via different rule ids — each agreeing finding's Confidence is raised to reflect that consensus (FR-012). Findings with an empty rule_id are never merged (each is treated as a distinct issue) but still carry populated Sources.

Order is preserved (first occurrence wins) so the report is stable.

func NormalizeFindings

func NormalizeFindings(report *SARIFReport, scannerID string) []ScanFinding

NormalizeFindings converts SARIF results into normalized ScanFindings

func ScanToolMetadataVerdict added in v0.53.0

func ScanToolMetadataVerdict(serverName string, tools []*config.ToolMetadata, peerTools map[string][]*config.ToolMetadata) (verdict string, findings []ScanFinding, coverageOK bool)

ScanToolMetadataVerdict runs the deterministic, offline detect.Engine over the given tools and returns the baseline-only verdict (spec 086 stage 2). It is the synchronous seam the runtime tool-change gate consults under trust_mode: scan — it performs NO Docker, network, or filesystem I/O, so it is safe to call inline on the discovery path.

peerTools maps each OTHER connected server's name to its current tool definitions. It is fed into the RegistryView so the cross-server, peer-dependent hard checks (checks.Shadowing — name-collision and cross-server-reference impersonation) have the SAME context they get on the async full-server scan. Without it those checks are structurally inert (they consult reg.ToolsByName, which only holds the single changed tool), so a shadowing/impersonation rug-pull would resolve to "clean" while coverageOK stayed true — a fail-open. Passing the real peer registry keeps the change gate's "green == fully-covered verdict" promise honest. nil/empty is legitimate for a genuinely single-server deployment (there is nothing to shadow).

Returns:

  • verdict: deriveBaselineVerdict's string — "clean", "warnings", or "dangerous". Green (auto-approvable) is "clean" ONLY (FR-013).
  • findings: the baseline findings, carrying the matched TPA signal ids so a non-clean verdict can be surfaced to the operator (FR-018).
  • coverageOK: false when the scan degraded (a check panicked/failed) OR the embedded tpa-db bundle was unavailable OR there was nothing to scan. The caller MUST fail closed (hold for review) whenever coverageOK is false, regardless of the verdict string (FR-014).

type ScanJob

type ScanJob struct {
	ID          string    `json:"id"`
	ServerName  string    `json:"server_name"`
	Status      string    `json:"status"`    // pending, running, completed, failed, cancelled
	ScanPass    int       `json:"scan_pass"` // 1 = security scan (fast), 2 = supply chain audit (background)
	Scanners    []string  `json:"scanners"`
	StartedAt   time.Time `json:"started_at"`
	CompletedAt time.Time `json:"completed_at,omitempty"`
	Error       string    `json:"error,omitempty"`
	DryRun      bool      `json:"dry_run,omitempty"`
	// Per-scanner status
	ScannerStatuses []ScannerJobStatus `json:"scanner_statuses"`
	// Scan context — what was scanned and how
	ScanContext *ScanContext `json:"scan_context,omitempty"`
	// Incarnation is the incarnation of the server this job scans (Spec 116
	// FR-014a): its saves are conditional on the server still having it, so
	// a scan that outlives a remove and re-add leaves nothing for the
	// replacement. 0 for a job started without a committed view.
	Incarnation int64 `json:"incarnation,omitempty"`
	// contains filtered or unexported fields
}

ScanJob represents a scan execution job

func (*ScanJob) Done added in v0.72.0

func (j *ScanJob) Done() <-chan struct{}

Done returns a channel that is closed when the engine's scan goroutine for this job has returned, completion callback included. It is nil for a job that carries no completion handle (a nil channel blocks forever in a select).

func (*ScanJob) MarshalBinary

func (j *ScanJob) MarshalBinary() ([]byte, error)

MarshalBinary implements encoding.BinaryMarshaler

func (*ScanJob) TrackCompletion added in v0.72.0

func (j *ScanJob) TrackCompletion() (finish func())

TrackCompletion attaches a completion handle to a job that is not yet shared and returns the idempotent function that closes it. The engine calls it for every job it starts; test doubles of the scan service use it to hand a caller a handle they control.

func (*ScanJob) UnmarshalBinary

func (j *ScanJob) UnmarshalBinary(data []byte) error

UnmarshalBinary implements encoding.BinaryUnmarshaler

type ScanJobMeta added in v0.39.0

type ScanJobMeta struct {
	ID          string    `json:"id"`
	ServerName  string    `json:"server_name"`
	Status      string    `json:"status"`
	ScanPass    int       `json:"scan_pass"`
	StartedAt   time.Time `json:"started_at"`
	CompletedAt time.Time `json:"completed_at,omitempty"`
}

ScanJobMeta is a lightweight projection of a scan job, persisted in a dedicated index bucket so that companion-job lookups during report aggregation never deserialize the full job payload (whose ScannerStatuses can carry large stdout/stderr blobs). This keeps report latency independent of a server's scan history. See MCP-2205.

type ScanJobSummary

type ScanJobSummary struct {
	ID            string    `json:"id"`
	ServerName    string    `json:"server_name"`
	Status        string    `json:"status"`
	ScanPass      int       `json:"scan_pass"`
	StartedAt     time.Time `json:"started_at"`
	CompletedAt   time.Time `json:"completed_at,omitempty"`
	FindingsCount int       `json:"findings_count"`
	RiskScore     int       `json:"risk_score"`
	Scanners      []string  `json:"scanners"`
}

ScanJobSummary is a lightweight view of a scan job for history listing

type ScanQueue

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

ScanQueue manages a queue of scan requests with a worker pool

func NewScanQueue

func NewScanQueue(logger *zap.Logger) *ScanQueue

NewScanQueue creates a new scan queue

func (*ScanQueue) CancelAll

func (q *ScanQueue) CancelAll() error

CancelAll cancels the current batch scan

func (*ScanQueue) GetProgress

func (q *ScanQueue) GetProgress() *QueueProgress

GetProgress returns the current batch scan progress

func (*ScanQueue) IsRunning

func (q *ScanQueue) IsRunning() bool

IsRunning returns true if a batch scan is in progress

func (*ScanQueue) StartScanAll

func (q *ScanQueue) StartScanAll(
	serverList []ServerStatus,
	scanFunc func(ctx context.Context, serverName string) (*ScanJob, error),
) (*QueueProgress, error)

StartScanAll begins scanning all eligible servers using a worker pool. scanFunc is called for each server to perform the actual scan. serverList provides the list of servers to scan.

type ScanReport

type ScanReport struct {
	ID         string          `json:"id"`
	JobID      string          `json:"job_id"`
	ServerName string          `json:"server_name"`
	ScannerID  string          `json:"scanner_id"`
	Findings   []ScanFinding   `json:"findings"`
	RiskScore  int             `json:"risk_score"` // 0-100
	SarifRaw   json.RawMessage `json:"sarif_raw,omitempty"`
	ScannedAt  time.Time       `json:"scanned_at"`
	// Incarnation is the incarnation of the scanned server (Spec 116
	// FR-014a), copied from the job.
	Incarnation int64 `json:"incarnation,omitempty"`
}

ScanReport represents aggregated scan results for a server

func (*ScanReport) MarshalBinary

func (r *ScanReport) MarshalBinary() ([]byte, error)

MarshalBinary implements encoding.BinaryMarshaler

func (*ScanReport) UnmarshalBinary

func (r *ScanReport) UnmarshalBinary(data []byte) error

UnmarshalBinary implements encoding.BinaryUnmarshaler

type ScanRequest

type ScanRequest struct {
	ServerName string
	// Incarnation is the scanned server's incarnation when the scan was
	// requested (Spec 116 FR-014a); the job carries it.
	Incarnation    int64
	SourceDir      string            // Path to server source files (for "source" input)
	ContainerImage string            // Docker image reference (for "container_image" input)
	DryRun         bool              // If true, don't affect quarantine state
	ScannerIDs     []string          // Specific scanners to use (empty = all installed)
	Env            map[string]string // Additional environment variables
	ScanContext    *ScanContext      // Context metadata (set by service)
	ScanPass       int               // 1 = security scan (fast), 2 = supply chain audit (background)
	// IsolationMode is THIS server's resolved isolation mode ("docker",
	// "sandbox", "none", or "" to fall back to the engine's service-wide
	// default). Set per-server by the Service so the Docker-scanner skip
	// (MCP-34.4) follows the scanned server's effective mode — a per-server
	// isolation.mode override beats the global mode (internal/upstream/core
	// IsolationManager.ResolveMode). Under "sandbox"/"none" Docker scanner
	// plugins are skipped; under "docker" they run.
	IsolationMode string
	// PeerTools is a cross-server snapshot (other servers' current tool
	// definitions, keyed by server name) used by the in-process tpa-descriptions
	// scanner to build a multi-server RegistryView so the deterministic
	// shadowing.cross_server check can detect impersonation/collisions across
	// servers. Populated by the Service; nil for callers that don't supply it.
	PeerTools map[string][]map[string]interface{}
	// ToolDefinitions is the exact tools.json document the Service exported
	// for this scan (RT-06, Sol r4 P1): an immutable in-memory snapshot of the
	// live + ingested contracts. The in-process baseline scanner analyses it
	// instead of re-reading SourceDir/tools.json, which an upstream that can
	// write its own source dir could swap for clean metadata between export
	// and the asynchronous scanner read. Docker scanners still read the file
	// from the mounted source dir; their result is discarded when the file no
	// longer matches this snapshot. Nil for callers that export nothing.
	ToolDefinitions []byte
	// ToolDefinitionsUnavailable marks a scan whose tool definitions could not
	// be exported (Pass 2 only, Sol r4 P2): the source dir may hold a
	// tools.json this pass did not write, so every scanner that may analyse
	// it is failed, while scanners independent of tool metadata (supply-chain
	// / CVE analysis) still run.
	ToolDefinitionsUnavailable bool
	// contains filtered or unexported fields
}

ScanRequest describes a scan to execute

type ScanSummary

type ScanSummary struct {
	LastScanAt    *time.Time     `json:"last_scan_at,omitempty"`
	RiskScore     int            `json:"risk_score"`
	Status        string         `json:"status"` // clean, warnings, dangerous, failed, not_scanned, scanning
	FindingCounts *FindingCounts `json:"finding_counts,omitempty"`
	// Scanner coverage for the primary (security) scan pass. Informational only.
	// Spec 077 US3 (FR-008/FR-014): Status is derived SOLELY from baseline
	// findings — a failed Docker deep scanner no longer downgrades a clean
	// verdict to "degraded"; that failure is surfaced via DeepScan instead.
	ScannersRun    int `json:"scanners_run"`
	ScannersFailed int `json:"scanners_failed"`
	ScannersTotal  int `json:"scanners_total"`
	// DeepScan is the opt-in heavy-layer availability descriptor (Spec 077
	// FR-008). It is a SEPARATE informational dimension and MUST NOT influence
	// Status. Always emitted on a computed summary: when deep scan is off (the
	// default) it reports enabled=false plus any enabled-but-skipped Docker
	// scanners, so the skip is observable (audit FIX 3a).
	DeepScan *DeepScanDescriptor `json:"deep_scan,omitempty"`
}

ScanSummary is a compact representation of scan status for the server list.

type ScannerJobStatus

type ScannerJobStatus struct {
	ScannerID     string    `json:"scanner_id"`
	Status        string    `json:"status"`
	StartedAt     time.Time `json:"started_at,omitempty"`
	CompletedAt   time.Time `json:"completed_at,omitempty"`
	DurationMs    int64     `json:"duration_ms"` // Wall-clock execution time in ms; 0 when timing is unavailable
	Error         string    `json:"error,omitempty"`
	FindingsCount int       `json:"findings_count"`
	Stdout        string    `json:"stdout,omitempty"` // Scanner stdout (for log viewing)
	Stderr        string    `json:"stderr,omitempty"` // Scanner stderr (for log viewing)
	ExitCode      int       `json:"exit_code"`
}

ScannerJobStatus tracks a single scanner's execution within a scan job

func (ScannerJobStatus) Duration added in v0.39.0

func (s ScannerJobStatus) Duration() time.Duration

Duration returns the scanner's wall-clock execution time, or 0 when the start/complete timestamps are unavailable or inconsistent (e.g. the scanner is still running, never started, or the completion clock skewed earlier than the start).

type ScannerPlugin

type ScannerPlugin struct {
	ID          string           `json:"id"`
	Name        string           `json:"name"`
	Vendor      string           `json:"vendor"`
	Description string           `json:"description"`
	License     string           `json:"license"`
	Homepage    string           `json:"homepage"`
	DockerImage string           `json:"docker_image"`
	Inputs      []string         `json:"inputs"`  // "source", "mcp_connection", "container_image"
	Outputs     []string         `json:"outputs"` // "sarif"
	RequiredEnv []EnvRequirement `json:"required_env"`
	OptionalEnv []EnvRequirement `json:"optional_env"`
	Command     []string         `json:"command"`
	// ImageCommand is the command template used when the scan target is a Docker
	// image reference rather than a source directory (input "container_image").
	// The token "{{IMAGE}}" is replaced with the image reference at runtime.
	// Only consulted when the scanner declares "container_image" in Inputs.
	ImageCommand []string `json:"image_command,omitempty"`
	Timeout      string   `json:"timeout"`
	NetworkReq   bool     `json:"network_required"`
	// InProcess marks a Docker-less, built-in scanner that the engine runs
	// in-process (e.g. the tool-description TPA analyzer). Such scanners have
	// no Docker image to pull, are always "installed", and skip the
	// image-availability gate so they run even for remote servers with no
	// source/Docker (MCP-2082).
	InProcess bool `json:"in_process,omitempty"`
	// Runtime state (not in registry)
	Status      string    `json:"status"` // available, installed, configured, error
	InstalledAt time.Time `json:"installed_at,omitempty"`
	// ConfiguredEnv holds the env values an operator set for this scanner —
	// vendor API keys, in practice. RedactedForAPI() is what makes the "secrets
	// redacted in API" promise true; call it on every serialization path.
	ConfiguredEnv map[string]string `json:"configured_env,omitempty"` // Set env values (secrets redacted in API — see RedactedForAPI)
	ImageOverride string            `json:"image_override,omitempty"` // User override for DockerImage
	LastUsedAt    time.Time         `json:"last_used_at,omitempty"`
	ErrorMsg      string            `json:"error_message,omitempty"`
	Custom        bool              `json:"custom,omitempty"` // User-added (not from registry)
}

ScannerPlugin represents a security scanner plugin

func RedactScannersForAPI added in v0.64.0

func RedactScannersForAPI(list []*ScannerPlugin) []*ScannerPlugin

RedactScannersForAPI applies RedactedForAPI to a whole list, allocating a new slice so the registry's own records are never touched.

func (*ScannerPlugin) EffectiveImage

func (s *ScannerPlugin) EffectiveImage() string

EffectiveImage returns ImageOverride if set, otherwise DockerImage.

func (*ScannerPlugin) MarshalBinary

func (s *ScannerPlugin) MarshalBinary() ([]byte, error)

MarshalBinary implements encoding.BinaryMarshaler

func (*ScannerPlugin) RedactedForAPI added in v0.64.0

func (s *ScannerPlugin) RedactedForAPI() *ScannerPlugin

RedactedForAPI returns a copy of the plugin safe to serialize to an API client: every literal ConfiguredEnv value is replaced by RedactedEnvValue.

#1166 round 10, P3. GET /api/v1/security/scanners and /security/scanners/{id}/status marshalled this struct straight out, so the vendor API keys an operator had typed into the scanner config dialog came back down the wire in the clear — while the field's own comment claimed they were "redacted in API". Redacting HERE, at the type, rather than at each handler is what keeps that comment true for a serialization path added later.

A `${keyring:...}` value is preserved verbatim: it is a REFERENCE to a secret, not the secret, and the UI reads it to distinguish "stored in your keychain" from "stored in the config file". Preserving it also keeps the save path honest — the dialog re-submits only values that are neither a keyring reference nor the redaction sentinel, so a round-trip through this function can never overwrite a real secret with its own mask.

func (*ScannerPlugin) UnmarshalBinary

func (s *ScannerPlugin) UnmarshalBinary(data []byte) error

UnmarshalBinary implements encoding.BinaryUnmarshaler

type ScannerRunConfig

type ScannerRunConfig struct {
	ContainerName string            // e.g., "mcpproxy-scanner-mcp-scan-abc123"
	Image         string            // Docker image to use
	Command       []string          // Command to run inside container
	Env           map[string]string // Environment variables
	SourceDir     string            // Host directory to mount at /scan/source (read-only)
	ReportDir     string            // Host directory to mount at /scan/report (writable)
	CacheDir      string            // Host directory for scanner cache (persists between runs)
	NetworkMode   string            // "none", "bridge", or custom network name
	Timeout       time.Duration     // Container execution timeout
	ReadOnly      bool              // Read-only root filesystem
	MemoryLimit   string            // e.g., "512m"
	ExtraMounts   []string          // Additional -v mounts (e.g., "~/.claude:/app/.claude:ro")

	// DisableNoNewPrivileges, when true, omits the
	// `--security-opt no-new-privileges` flag. Required on hosts running
	// snap-installed Docker where the AppArmor profile transition would
	// otherwise fail with "operation not permitted". See
	// SecurityConfig.ScannerDisableNoNewPrivileges in internal/config.
	DisableNoNewPrivileges bool
}

ScannerRunConfig defines how to run a scanner container

type SecretResolverFunc

type SecretResolverFunc func(ctx context.Context, ref string) (string, error)

SecretResolverFunc resolves a secret reference like ${keyring:name} to its value

type SecretStore

type SecretStore interface {
	StoreSecret(ctx context.Context, name, value string) error
	ResolveSecret(ctx context.Context, ref string) (string, error)
}

SecretStore allows storing and resolving secrets via the OS keyring

type SecurityOverview

type SecurityOverview struct {
	TotalScans         int           `json:"total_scans"`
	ActiveScans        int           `json:"active_scans"`
	FindingsBySeverity ReportSummary `json:"findings_by_severity"`
	ScannersInstalled  int           `json:"scanners_installed"`
	ScannersEnabled    int           `json:"scanners_enabled"` // Subset of installed that the engine will run (status installed or configured)
	ServersScanned     int           `json:"servers_scanned"`
	LastScanAt         time.Time     `json:"last_scan_at,omitempty"`
	DockerAvailable    bool          `json:"docker_available"`
	// SignatureBundle describes the offline TPA signature corpus the scanner is
	// actually running: source (embedded vs a configured file), version,
	// freshness stamp, fingerprint, and the runnable/skipped rule split
	// (spec 086 FR-019, GH #938 finding 2). Before this, a years-stale corpus
	// was indistinguishable from a fresh export on every operator surface.
	SignatureBundle *BundleInfo `json:"signature_bundle,omitempty"`
}

SecurityOverview provides dashboard aggregate stats

type ServerApprovalCommitter added in v0.71.0

type ServerApprovalCommitter interface {
	CommitServerApproval(serverName string, blocks []string, expected map[string]string, by string, commit func() error) (int, error)
}

ServerApprovalCommitter is an OPTIONAL capability of the ServerUnquarantiner (Spec 117 PR-1, #1567): run the approval's storage commit under the runtime's per-server tool-approval lock, after recording the server's durable tool baseline decision (source server_approval, by). It lets the scanner reach the baseline marker without importing storage or the runtime (storage imports this package). expected is the Spec 117 PR-2 review binding and is nil in this release; the returned count is the number of tools the commit section promoted (0 in this release).

type ServerIncarnationProvider added in v0.71.0

type ServerIncarnationProvider interface {
	ServerIncarnation(serverName string) (int64, bool)
}

ServerIncarnationProvider is an OPTIONAL capability of the ServerUnquarantiner: the server's current incarnation, recorded on scan jobs and reports (Spec 116 FR-014a).

type ServerInfo

type ServerInfo struct {
	Name       string // Server name
	Protocol   string // "stdio", "http", "sse", "streamable-http"
	Command    string // Command used to start the server (stdio only)
	Args       []string
	WorkingDir string            // Configured working directory
	URL        string            // Server URL (HTTP/SSE only)
	Env        map[string]string // Environment variables
}

ServerInfo contains the information needed to resolve a server's source

type ServerInfoProvider

type ServerInfoProvider interface {
	GetServerInfo(serverName string) (*ServerInfo, error)
	GetServerTools(serverName string) ([]map[string]interface{}, error)
	// EnsureConnected attempts to connect a disconnected/quarantined server
	// so that tool definitions can be retrieved for scanning.
	// Returns nil if already connected or successfully connected.
	EnsureConnected(ctx context.Context, serverName string) error
	// IsConnected returns whether the server has an active MCP connection.
	IsConnected(serverName string) bool
}

ServerInfoProvider resolves server configuration for auto-source resolution

type ServerStatus

type ServerStatus struct {
	Name      string
	Enabled   bool
	Connected bool
	Protocol  string
}

ServerStatus provides info about a server for queue filtering

type ServerUnquarantiner

type ServerUnquarantiner interface {
	UnquarantineServer(serverName string) error
}

ServerUnquarantiner performs the full unquarantine workflow for a server. Implementations are expected to:

  • Clear the quarantined flag in storage and persist config
  • Trigger a tool (re)index for the server
  • Emit the same events/activity entries that the normal unquarantine path emits

This interface is intentionally small so the scanner service does not need to depend on the full runtime package.

type Service

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

Service coordinates scanner management, scan execution, and approval workflow

func NewService

func NewService(storage Storage, registry *Registry, docker *DockerRunner, dataDir string, logger *zap.Logger) *Service

NewService creates a new SecurityService

func (*Service) ApplySecurityConfig added in v0.47.0

func (s *Service) ApplySecurityConfig(sec *config.SecurityConfig)

ApplySecurityConfig (re)configures the opt-in deep-scan layer from the effective security config in a single call, so both the startup wiring and config hot-reload gate the scanner identically (Spec 077 US3). It resolves the deep-scan master switch + per-scanner allow-list (SetDeepScan), the no-new-privileges escape hatch (SetScannerDisableNoNewPrivileges), and the published-package-source fetch (SetFetchPackageSource) — which only runs when deep scan is ON and fetch is not explicitly disabled. All accessors are nil-safe, so a nil SecurityConfig forces the layer fully off (baseline-only). Idempotent: safe to call on every config.reloaded event.

func (*Service) ApproveServer

func (s *Service) ApproveServer(ctx context.Context, serverName string, force bool, approvedBy string) error

ApproveServer approves a scanned server, storing the integrity baseline

func (*Service) ApproveServerAt added in v0.71.0

func (s *Service) ApproveServerAt(ctx context.Context, serverName string, force bool, approvedBy string, toolNames []string, expectedIncarnation int64) error

ApproveServerAt is ApproveServerWithBlocks (toolNames may be empty) bound to expectedIncarnation, the incarnation of the server the caller reviewed (Spec 116 FR-017). A remove and re-add since then fails it with server_replaced and leaves the replacement quarantined. 0 binds to the incarnation current when the call starts.

func (*Service) ApproveServerReviewed added in v0.71.0

func (s *Service) ApproveServerReviewed(ctx context.Context, serverName string, force bool, approvedBy string, blocks []string, expected map[string]string) error

ApproveServerReviewed approves a scanned server bound to the review the caller showed (Spec 117 PR-2, #1566). expected maps tool name to the review fingerprint (current_hash) the operator saw; nil is an unbound (legacy) request and an empty map binds to the empty snapshot. blocks are the tools to keep disabled. The dangerous-scan gate runs first and keeps its message; a stale binding returns *toolreview.StaleToolReviewError unchanged, with nothing written and the server still quarantined.

func (*Service) ApproveServerReviewedAt added in v0.71.0

func (s *Service) ApproveServerReviewedAt(ctx context.Context, serverName string, force bool, approvedBy string, blocks []string, expected map[string]string, expectedIncarnation int64) error

ApproveServerReviewedAt is ApproveServerReviewed also bound to expectedIncarnation, the incarnation of the server the caller reviewed (Spec 116 FR-017). The two bindings are independent: a remove and re-add since the review fails with server_replaced (the replacement stays quarantined), changed definitions with the stale-review error. 0 binds to the incarnation current when the call starts.

func (*Service) ApproveServerWithBlocks added in v0.70.0

func (s *Service) ApproveServerWithBlocks(ctx context.Context, serverName string, force bool, approvedBy string, toolNames []string) error

ApproveServerWithBlocks approves a scanned server and atomically records the selected tool blocks with the integrity baseline before the server can be unquarantined.

func (*Service) BundleHistory added in v0.72.0

func (s *Service) BundleHistory() ([]TPABundleActivation, error)

BundleHistory returns the append-only TPA bundle activation history, oldest first (spec 101 FR-010/FR-020).

func (*Service) BundleStatus added in v0.53.0

func (s *Service) BundleStatus() BundleInfo

BundleStatus reports the offline TPA signature corpus this process is running (spec 086 FR-019). Exposed on the service so the REST/CLI surfaces can answer "which signatures is my proxy running, and how old are they?" without importing the loader internals (GH #938 finding 2).

func (*Service) CancelAllScans

func (s *Service) CancelAllScans() error

CancelAllScans cancels the current batch scan

func (*Service) CancelScan

func (s *Service) CancelScan(ctx context.Context, serverName string) error

CancelScan cancels a running scan for a server

func (*Service) CheckIntegrity

func (s *Service) CheckIntegrity(ctx context.Context, serverName string) (*IntegrityCheckResult, error)

CheckIntegrity verifies a server's runtime integrity against its baseline

func (*Service) CleanupStaleJobs

func (s *Service) CleanupStaleJobs()

CleanupStaleJobs marks any running/pending scan jobs as failed. Called on startup to clean up jobs that were interrupted by a process crash.

func (*Service) ConfigureScanner

func (s *Service) ConfigureScanner(_ context.Context, id string, env map[string]string, dockerImage string) error

ConfigureScanner sets environment variables (API keys) and/or an image override for a scanner.

Scanner env values are stored DIRECTLY in the scanner's ConfiguredEnv map in BBolt, NOT in the OS keyring. Previous versions attempted to write to the OS keyring and fall back on failure, but that path is unsafe on macOS: keyring.Set (which wraps Security.framework under the hood) can pop a blocking "Keychain Not Found" system modal when the user's default keychain is in an unusual state, and the underlying goroutine cannot be cancelled once started (it stays live until it hits the real backend, which may never happen). The scanner env values end up in the container's /proc/environ at scan time anyway, so keyring storage adds no meaningful confidentiality — it's a trust-boundary we don't actually have.

Users who want OS-keyring storage for a specific secret can still use a `${keyring:my-secret-name}` reference as the env value. The resolver expands it at scan time via a read-only keyring Get, which is safe on all platforms.

If the effective Docker image changes (user set a new override) and the new image is not already cached locally, the scanner is transitioned to the "pulling" state and a background pull is kicked off. The call returns immediately — the UI tracks the pull via SSE or polling.

func (*Service) DeepScanEnabled added in v0.47.0

func (s *Service) DeepScanEnabled() bool

DeepScanEnabled reports whether the opt-in deep-scan layer is currently on. Exported so the wiring/reload path (and its tests) can observe a config hot-reload taking effect without recreating the service (Spec 077 US3).

func (*Service) GetOverview

func (s *Service) GetOverview(ctx context.Context) (*SecurityOverview, error)

GetOverview returns aggregated security statistics

func (*Service) GetQueueProgress

func (s *Service) GetQueueProgress() *QueueProgress

GetQueueProgress returns the current batch scan progress

func (*Service) GetScanJobSummary added in v0.72.0

func (s *Service) GetScanJobSummary(_ context.Context, serverName, jobID string) *ScanSummary

GetScanJobSummary is the terminal ScanSummary of ONE specific job, read by its ID: the status and findings of that job alone, never the server-wide latest summary, which another scan of the same server (a manual scan, an admission scan) may have displaced or still be running. Nil when the job does not exist, belongs to another server or to an incarnation other than the server's current one, or has not reached a terminal state. A failed or cancelled job, or one without any usable scanner report, reports "failed".

func (*Service) GetScanReport

func (s *Service) GetScanReport(ctx context.Context, serverName string) (*AggregatedReport, error)

GetScanReport returns the aggregated report for a server, merging both Pass 1 and Pass 2 results.

func (*Service) GetScanReportByJobID

func (s *Service) GetScanReportByJobID(ctx context.Context, jobID string) (*AggregatedReport, error)

GetScanReportByJobID returns an aggregated report for a specific scan job ID.

func (*Service) GetScanStatus

func (s *Service) GetScanStatus(ctx context.Context, serverName string) (*ScanJob, error)

GetScanStatus returns the current scan status for a server. Prefers Pass 1 (security scan) which contains the primary scanner execution data. Pass 2 (supply chain audit) is only returned if Pass 1 is not available.

func (*Service) GetScanStatusByPass

func (s *Service) GetScanStatusByPass(ctx context.Context, serverName string, pass int) (*ScanJob, error)

GetScanStatusByPass returns the scan job for a specific pass (1=security, 2=supply chain). If pass is 0 or not found, falls back to GetScanStatus behavior (latest job).

func (*Service) GetScanSummary

func (s *Service) GetScanSummary(ctx context.Context, serverName string) *ScanSummary

GetScanSummary returns a compact scan summary for a server (for the server list API). Returns nil if no scans have been run for this server. Considers both Pass 1 and Pass 2 results when computing status.

func (*Service) GetScanner

func (s *Service) GetScanner(ctx context.Context, id string) (*ScannerPlugin, error)

GetScanner returns a scanner by ID

func (*Service) GetScannerStatus

func (s *Service) GetScannerStatus(ctx context.Context, id string) (*ScannerPlugin, error)

GetScannerStatus returns the current status of a scanner

func (*Service) GetSecurityOverview

func (s *Service) GetSecurityOverview(ctx context.Context) (*SecurityOverview, error)

GetSecurityOverview returns aggregated security statistics. Satisfies the httpapi.SecurityController interface.

func (*Service) HasApprovalBaseline added in v0.53.0

func (s *Service) HasApprovalBaseline(serverName string) bool

HasApprovalBaseline reports whether an integrity baseline already exists for the server — i.e. it has been approved/unquarantined at least once. The spec-086 admission gate uses this to distinguish a first-time admission quarantine (auto-approve on a clean baseline scan) from a deliberate operator re-quarantine of an already-admitted server (never silently auto-approved).

func (*Service) InstallScanner

func (s *Service) InstallScanner(ctx context.Context, id string) error

InstallScanner enables a scanner and kicks off a background Docker image pull. Returns immediately — the UI tracks progress via SSE events (security.scanner_changed) or by polling GET /api/v1/security/scanners.

Behavior:

  1. If the image is already present locally, the scanner is marked "installed" synchronously and the function returns nil.
  2. Otherwise the scanner is marked "pulling" and a goroutine performs the actual docker pull. On success status → "installed"; on failure status → "error" with ErrorMsg set.
  3. If Docker itself is not running, the scanner is marked "error" so the user gets clear feedback.

func (*Service) InvalidateServerState added in v0.71.0

func (s *Service) InvalidateServerState(serverName string)

InvalidateServerState drops the scan state of a server whose stored scan state was purged (Spec 116 FR-014a: a removal), so a re-added server never shows the old server's verdict: the cached summary, and the engine's active job when it belongs to an incarnation that is no longer current (review round 1). A job of the current incarnation — a re-added server's own scan that started before this observer ran — is kept; the engine's identity- checked cleanup keeps the detached job's goroutine from evicting it.

func (*Service) IsQueueRunning

func (s *Service) IsQueueRunning() bool

IsQueueRunning returns true if a batch scan is in progress

func (*Service) ListScanHistory

func (s *Service) ListScanHistory(ctx context.Context) ([]ScanJobSummary, error)

ListScanHistory returns all scan jobs as summaries, enriched with findings count and risk score.

func (*Service) ListScanners

func (s *Service) ListScanners(ctx context.Context) ([]*ScannerPlugin, error)

ListScanners returns all scanners from registry merged with installed state from storage

func (*Service) RefreshBundle added in v0.72.0

func (s *Service) RefreshBundle(ctx context.Context) BundleInfo

RefreshBundle runs one joined refresh cycle (the network-free file leg, then the optional fetch leg) and returns the resulting status; without a running refresher it behaves as ReloadBundle (Spec 087 FR-004, Spec 101 US3 B20).

func (*Service) RejectServer

func (s *Service) RejectServer(ctx context.Context, serverName string) error

RejectServer rejects a server, cleaning up all artifacts

func (*Service) ReloadBundle added in v0.72.0

func (s *Service) ReloadBundle() BundleInfo

ReloadBundle re-runs the bundle pipeline with the current policy, so a file drop is picked up without waiting for a config change (spec 101 Δ5).

func (*Service) RemoveScanner

func (s *Service) RemoveScanner(ctx context.Context, id string) error

RemoveScanner removes a scanner, its Docker image, and stored configuration. If a background pull is in progress for this scanner it is cancelled.

func (*Service) RollbackBundle added in v0.72.0

func (s *Service) RollbackBundle(req BundleRollbackRequest) (BundleInfo, error)

RollbackBundle runs the explicit FR-010 rollback; see RollbackBundle.

func (*Service) ScanAll

func (s *Service) ScanAll(ctx context.Context, servers []ServerStatus, scannerIDs []string) (*QueueProgress, error)

ScanAll starts scanning all eligible servers using the worker pool. Disabled servers are skipped with a reason.

func (*Service) SetAfterBaselineBeforeUnquarantineHookForTest added in v0.71.0

func (s *Service) SetAfterBaselineBeforeUnquarantineHookForTest(fn func(serverName string, incarnation int64))

SetAfterBaselineBeforeUnquarantineHookForTest installs the afterBaselineBeforeUnquarantine seam. Test-only.

func (*Service) SetDeepScan added in v0.47.0

func (s *Service) SetDeepScan(enabled bool, scanners []string)

SetDeepScan configures the opt-in "deep scan" layer (Spec 077 US3). When enabled is false (the default), only the deterministic in-process baseline scanner runs and no Docker container is ever invoked; a deep-scan failure can therefore never degrade the baseline verdict. scanners optionally restricts which deep scanners are eligible (empty ⇒ all enabled deep scanners). This is the runtime knob for security.deep_scan.enabled / security.deep_scan.scanners.

func (*Service) SetEmitter

func (s *Service) SetEmitter(emitter EventEmitter)

SetEmitter sets the event emitter for the service.

func (*Service) SetFetchPackageSource added in v0.39.0

func (s *Service) SetFetchPackageSource(enabled bool)

SetFetchPackageSource toggles whether the source resolver may fetch the published source of package-runner servers (npx/uvx) for scanning. This is a facet of the opt-in deep-scan layer (Spec 077 US3): the server layer only enables it when security.deep_scan.enabled is true AND security.deep_scan.fetch_package_source is not explicitly false (the deprecated top-level ScannerFetchPackageSource, MCP-2206, is still honored as a fallback). With deep scan off the effective value is always false, so scanning an npx/uvx server performs no published-package-source network egress by default.

func (*Service) SetInstanceID added in v0.68.0

func (s *Service) SetInstanceID(instanceID string)

SetInstanceID scopes this service's Docker container-ownership lookups to the given mcpproxy instance ID (internal/upstream/core.GetInstanceID()). See SourceResolver.instanceID for why this is injected rather than imported.

func (*Service) SetIsolationMode added in v0.47.0

func (s *Service) SetIsolationMode(mode string)

SetIsolationMode records the engine-wide DEFAULT isolation mode ("docker", "sandbox", "none", or "" == docker), used when a scan has no per-server mode (no resolver wired, or the resolver returns ""). Per-server resolution via SetIsolationModeResolver takes precedence. Under "sandbox"/"none" the host runs no Docker for scanners, so Docker (deep) scanner plugins are cleanly skipped while the in-process baseline still runs — MCP-34.4 / D3 option (b). Per Spec 077 US3 such a skip is informational (surfaced via the deep-scan descriptor) and NEVER degrades the baseline verdict; deep scanners only run at all when security.deep_scan.enabled is set.

func (*Service) SetIsolationModeResolver added in v0.47.0

func (s *Service) SetIsolationModeResolver(resolver func(serverName string) string)

SetIsolationModeResolver injects a per-server isolation-mode resolver so the Docker-scanner skip (MCP-34.4) follows each scanned server's RESOLVED mode — a per-server isolation.mode override beats the global default. The resolver returns "docker"/"sandbox"/"none", or "" to fall back to the engine-wide default. Wired in the server layer from the upstream IsolationManager so the scanner package stays decoupled from the resolver.

func (*Service) SetScannerDisableNoNewPrivileges added in v0.24.3

func (s *Service) SetScannerDisableNoNewPrivileges(disable bool)

SetScannerDisableNoNewPrivileges controls whether scanner containers are launched without `--security-opt no-new-privileges`. This is the runtime knob for SecurityConfig.ScannerDisableNoNewPrivileges. See the config field doc for background on why a user might need to enable this.

func (*Service) SetSecretStore

func (s *Service) SetSecretStore(store SecretStore)

SetSecretStore sets the secret store for secure API key management. Also wires secret resolution into the scan engine for resolving ${keyring:...} references in scanner env vars at scan time.

func (*Service) SetServerInfoProvider

func (s *Service) SetServerInfoProvider(provider ServerInfoProvider)

SetServerInfoProvider sets the provider for resolving server configuration

func (*Service) SetServerUnquarantiner

func (s *Service) SetServerUnquarantiner(u ServerUnquarantiner)

SetServerUnquarantiner wires the unquarantine callback used by ApproveServer. If not set, ApproveServer will still succeed in storing a baseline but will log a warning because it cannot actually unquarantine the server.

func (*Service) StartScan

func (s *Service) StartScan(ctx context.Context, serverName string, dryRun bool, scannerIDs []string, sourceDir string) (*ScanJob, error)

StartScan triggers a security scan for a server (Pass 1: fast security scan). After Pass 1 completes, Pass 2 (supply chain audit) is auto-started in the background.

func (*Service) StartScanFromCachedContracts added in v0.72.0

func (s *Service) StartScanFromCachedContracts(ctx context.Context, serverName, bundleDigest string) (*ScanJob, error)

StartScanFromCachedContracts starts the post-activation re-protection scan of one server (Spec 101 FR-019, tasks B17): an informational job over the tool contracts discovery already ingested for its tools, labelled with the activated bundle's digest. It never connects to the upstream (no IsConnected, EnsureConnected or live tools export), never schedules Pass 2 and is excluded from the scan telemetry counters.

The job runs the in-process tpa-descriptions baseline only, over the immutable snapshot built here (ScanRequest.ToolDefinitions), with no source directory. A server with no recorded contracts gets no job at all (ErrNoCachedContracts): it stays unscanned, never clean. A busy server returns ErrScanInProgress so the caller can re-arm. A quarantined server is refused (ErrServerQuarantined) when the provider can say so.

ctx is the scan's EXECUTION context, not just the call's: the job runs under it (unlike the live StartScan, which detaches), so a stopping caller ends it, and a context that is already done starts nothing. The returned job's Done channel closes after the completion callback returned, so the caller can join the worker before the stores it writes to close.

func (*Service) UnpinBundle added in v0.72.0

func (s *Service) UnpinBundle() (BundleInfo, error)

UnpinBundle clears the active root's rollback pin; see UnpinBundle.

type SourceResolver

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

SourceResolver automatically determines the source directory for scanning a server. It resolves source based on server type:

  • Docker-isolated stdio servers: extracts changed files from running container
  • HTTP/SSE servers: no source needed (scanners use mcp_connection)
  • Local stdio servers: uses working_dir or command directory

func NewSourceResolver

func NewSourceResolver(logger *zap.Logger) *SourceResolver

NewSourceResolver creates a new SourceResolver

func (*SourceResolver) EnrichWithFileList

func (r *SourceResolver) EnrichWithFileList(resolved *ResolvedSource)

EnrichWithFileList populates the Files, TotalFiles, TotalSize fields on a ResolvedSource

func (*SourceResolver) Resolve

func (r *SourceResolver) Resolve(ctx context.Context, info ServerInfo) (*ResolvedSource, error)

Resolve determines the source directory for scanning a server. It tries these strategies in order:

  1. Find running Docker container for the server (mcpproxy-<name>-*)
  2. Use working_dir from server config
  3. Use directory containing the server command
  4. For HTTP servers, return URL for mcp_connection scanners

func (*SourceResolver) ResolveFullSource

func (r *SourceResolver) ResolveFullSource(ctx context.Context, info ServerInfo) (*ResolvedSource, error)

ResolveFullSource resolves the FULL source directory for a server, including all dependencies (site-packages, node_modules, UV archives, etc.). This is used for Pass 2 (supply chain audit) to scan the complete filesystem.

func (*SourceResolver) SetFetchPackageSource added in v0.39.0

func (r *SourceResolver) SetFetchPackageSource(enabled bool)

SetFetchPackageSource toggles the published-package-source fetch fallback.

func (*SourceResolver) SetInstanceID added in v0.68.0

func (r *SourceResolver) SetInstanceID(instanceID string)

SetInstanceID scopes container-ownership lookups to this mcpproxy instance. See the instanceID field doc for why this is injected rather than imported.

type Storage

type Storage interface {
	SaveScanner(s *ScannerPlugin) error
	GetScanner(id string) (*ScannerPlugin, error)
	ListScanners() ([]*ScannerPlugin, error)
	DeleteScanner(id string) error

	SaveScanJob(job *ScanJob) error
	GetScanJob(id string) (*ScanJob, error)
	ListScanJobs(serverName string) ([]*ScanJob, error)
	ListScanJobMetas(serverName string) ([]*ScanJobMeta, error)
	GetLatestScanJob(serverName string) (*ScanJob, error)
	DeleteScanJob(id string) error
	DeleteServerScanJobs(serverName string) error

	SaveScanReport(report *ScanReport) error
	GetScanReport(id string) (*ScanReport, error)
	ListScanReports(serverName string) ([]*ScanReport, error)
	ListScanReportsByJob(jobID string) ([]*ScanReport, error)
	DeleteScanReport(id string) error
	DeleteServerScanReports(serverName string) error

	SaveIntegrityBaseline(baseline *IntegrityBaseline) error
	SaveIntegrityBaselineWithBlocks(baseline *IntegrityBaseline, blocks []ToolApprovalBlock) error
	GetIntegrityBaseline(serverName string) (*IntegrityBaseline, error)
	DeleteIntegrityBaseline(serverName string) error
	ListIntegrityBaselines() ([]*IntegrityBaseline, error)
}

Storage defines the storage interface needed by SecurityService

type TPAAuthorityState added in v0.72.0

type TPAAuthorityState struct {
	Epoch uint64 `json:"epoch"`
	// Watermark is the highest sequence ever activated for (authority, Epoch),
	// never below the authority's baseline. Monotonic: rollback does not lower
	// it (FR-010).
	Watermark uint64 `json:"watermark"`
	// WatermarkSetBy is the full digest of the bundle that set Watermark ("" when
	// the watermark is only the seeded baseline).
	WatermarkSetBy string `json:"watermark_set_by,omitempty"`
	// ExternalEverActivated records that an external bundle of this authority
	// has ever activated on this install. It SURVIVES a trust-epoch re-scope:
	// the bump is what makes that corpus "no longer valid", so FR-009a(b)
	// (`operator_bundle_missing`) must still tell "operator bundle lost or
	// invalidated" from "operator root declared, nothing ever activated". Only
	// a newly activated bundle (which serves externally) makes it moot.
	ExternalEverActivated bool `json:"external_ever_activated,omitempty"`
	// Pin is the FR-010 rollback pin. It binds only while this authority is the
	// active root and Epoch equals the current trusted epoch; switching roots
	// suspends (never deletes) it.
	Pin *TPABundlePin `json:"pin,omitempty"`
	// DenyList holds the releases rolled away from (FR-010). Same scoping as Pin.
	DenyList []TPABundleDenyEntry `json:"deny_list,omitempty"`
}

TPAAuthorityState is one authority's anti-downgrade state, scoped to Epoch (FR-005a: every comparison is (authority, epoch, sequence), epoch first). When the current trusted epoch for the authority differs from Epoch the whole record is re-scoped: the watermark re-baselines from the authority's baseline and prior-epoch pins and deny entries are retired (loudly logged).

type TPABundleActivation added in v0.72.0

type TPABundleActivation struct {
	Authority  string `json:"authority,omitempty"`
	TrustEpoch uint64 `json:"trust_epoch"`
	// Sequence is the decimal-string sequence as published ("" when unsigned or
	// embedded without one).
	Sequence          string    `json:"sequence,omitempty"`
	FullDigest        string    `json:"full_digest"`
	GeneratedAt       string    `json:"generated_at,omitempty"`
	ActivatedAt       time.Time `json:"activated_at"`
	Source            string    `json:"source"`
	SignatureVerified bool      `json:"signature_verified"`
	Rollback          bool      `json:"rollback,omitempty"`
}

TPABundleActivation is one append-only activation-history row (FR-010, SC-010; contracts/bundle-status-surface.md §5). The history makes a legitimate rollback POSSIBLE — it is how an operator learns the full digest of a known-good artifact — it never AUTHORIZES one.

func BundleHistory added in v0.72.0

func BundleHistory() ([]TPABundleActivation, error)

BundleHistory returns the append-only activation history, oldest first. It is how an operator learns the full digest of a known-good artifact to name in a rollback; it makes a legitimate rollback possible, it never authorizes one.

type TPABundleActiveRecord added in v0.72.0

type TPABundleActiveRecord struct {
	// Authority is AuthorityPublisher / AuthorityOperator for a
	// signature-verified bundle, "" for an unsigned one.
	Authority string `json:"authority,omitempty"`
	// TrustEpoch is the manifest epoch (signed bundles only).
	TrustEpoch uint64 `json:"trust_epoch"`
	// Sequence is the manifest sequence (signed bundles only; 0 when unsigned).
	Sequence uint64 `json:"sequence"`
	// FullDigest is the lowercase-hex SHA-256 of the exact bundle bytes.
	FullDigest string `json:"full_digest"`
	// SidecarDigest is the lowercase-hex SHA-256 of the sidecar bytes ("" when
	// unsigned) — part of the idempotence key.
	SidecarDigest     string    `json:"sidecar_digest,omitempty"`
	SignatureVerified bool      `json:"signature_verified"`
	Source            string    `json:"source"`
	Path              string    `json:"path,omitempty"`
	GeneratedAt       string    `json:"generated_at,omitempty"`
	ActivatedAt       time.Time `json:"activated_at"`
	// Rollback is true when this bundle was activated by an explicit
	// operator rollback (FR-010) rather than normal watermark governance.
	Rollback bool `json:"rollback,omitempty"`
}

TPABundleActiveRecord describes the serving external bundle (FR-011a).

type TPABundleDenyEntry added in v0.72.0

type TPABundleDenyEntry struct {
	Sequence   uint64    `json:"sequence"`
	FullDigest string    `json:"full_digest"`
	DeniedAt   time.Time `json:"denied_at"`
}

TPABundleDenyEntry is one deny-listed release, keyed (authority, epoch, sequence, digest) — the authority and epoch are the enclosing TPAAuthorityState's.

type TPABundlePin added in v0.72.0

type TPABundlePin struct {
	Sequence   uint64 `json:"sequence"`
	FullDigest string `json:"full_digest"`
	// Embedded is true when the pin is the embedded default.
	Embedded bool      `json:"embedded,omitempty"`
	PinnedAt time.Time `json:"pinned_at"`
	// SidecarDigest, Source and Path identify the exact (bundle, sidecar) pair
	// kept in the last-known-good store for this target, so the pin can restore
	// it after the active root was switched away and back (FR-004b). Empty for
	// the embedded default and for an unsigned target.
	SidecarDigest string `json:"sidecar_digest,omitempty"`
	Source        string `json:"source,omitempty"`
	Path          string `json:"path,omitempty"`
}

TPABundlePin is an operator-pinned rollback target, identified by full digest.

type TPABundleState added in v0.72.0

type TPABundleState struct {
	SchemaVersion int `json:"schema_version"`

	// SignatureRatchet is set once ANY signature-verified external bundle has
	// activated on this install. From then on unsigned candidates are refused
	// regardless of require_signed_bundle (FR-009).
	SignatureRatchet bool `json:"signature_ratchet"`

	// Active is the external bundle currently serving, or nil when the
	// embedded default serves. Its digest names the content-addressed
	// last-known-good file tpa-lkg/<FullDigest>.json in the data directory.
	Active *TPABundleActiveRecord `json:"active,omitempty"`

	// Authorities holds per-authority scoped state keyed by AuthorityPublisher
	// / AuthorityOperator. A missing entry means "no state yet" and is seeded
	// from the authority's baseline (FR-009b) on first use.
	Authorities map[string]*TPAAuthorityState `json:"authorities,omitempty"`
}

TPABundleState is the per-install anti-downgrade record (spec 101 FR-009, FR-010, FR-011a; data-model §4). It is persisted as ONE value and written in ONE storage transaction together with the activation-history row of the activation that produced it, so a crash can never pair a new active bundle with an old watermark, or a preserved rollback with a lost deny-list.

Everything here is data-directory resident and therefore BEST-EFFORT against an attacker who can substitute config.db (spec threat-model boundary, SC-012): the guarantees that survive that attacker are the ones anchored outside the data dir — the publisher baseline re-seeded from the binary, the config-resident operator baseline, require_signed_bundle and the active-root declaration. Code MUST NOT present the ratchet, watermark, pin or deny-list as surviving state substitution.

type TPABundleStateStore added in v0.72.0

type TPABundleStateStore interface {
	// LoadTPABundleState returns the persisted state, or (nil, nil) when none
	// has ever been written. A read MUST NOT create the bucket.
	LoadTPABundleState() (*TPABundleState, error)
	// CommitTPABundleState writes state and, when entry is non-nil, appends it
	// to the activation history — both in ONE storage transaction (FR-011a).
	CommitTPABundleState(state *TPABundleState, entry *TPABundleActivation) error
	// ListTPABundleHistory returns every history row, oldest first.
	ListTPABundleHistory() ([]TPABundleActivation, error)
}

TPABundleStateStore persists TPABundleState and its activation history. It is implemented by *storage.Manager (storage imports this package, so the interface lives here — the same pattern as IncarnationStorage).

type ToolApprovalBlock added in v0.70.0

type ToolApprovalBlock struct {
	ToolName   string
	ApprovedAt time.Time
	ApprovedBy string
}

ToolApprovalBlock describes the approval fields needed to persist a block alongside the server integrity baseline in one storage transaction.

type ToolApprovalLocker added in v0.71.0

type ToolApprovalLocker interface {
	WithToolApprovalLock(serverName string, fn func() error) error
}

ToolApprovalLocker is an OPTIONAL capability of the ServerUnquarantiner: run fn while holding the runtime's per-server tool-approval lock (UX-02). The atomic baseline+blocks commit writes approval records directly in storage; serializing it with discovery passes keeps a pass holding a stale pending copy of a record from overwriting the operator's block (approved+disabled) back to pending+enabled, which the server-approval baseline would then promote to approved+enabled. fn must not unquarantine the server.

type ToolBlockRecorder added in v0.70.0

type ToolBlockRecorder interface {
	RecordToolBlocksForSecurityApproval(serverName string, toolNames []string, blockedBy string)
}

Jump to

Keyboard shortcuts

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