Help us shape the future of Go! Take the 2026 Go Developer Survey

scanner

package
v0.16.0 Latest Latest
Warning

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

Go to latest
Published: Nov 2, 2026 License: MIT Imports: 12 Imported by: 0

Documentation

Overview

Package scanner defines the Scanner interface, the result and coverage types every scanner returns, and the registry that holds scanners by name.

Index

Constants

View Source
const DefaultListLimit = 500

DefaultListLimit is the per-page size used by ListAll for scanner lists. Five hundred is the upstream client-go default for paginated lists and gives a reasonable tradeoff between request count and memory pressure on the apiserver.

View Source
const DefaultListTimeout = 30 * time.Second

DefaultListTimeout caps each individual list call so a slow apiserver cannot hang a full fleet sweep on one bad cluster.

View Source
const DefaultScanTimeout = 60 * time.Second

DefaultScanTimeout bounds how long a single scanner may run against one cluster before it is abandoned, so a hung API call on one outlier cluster cannot stall the whole fleet sweep.

Variables

View Source
var ErrScan = errors.New("scan failed")

ErrScan indicates a scanner failed to collect data from a cluster.

Functions

func CacheReadOptions

func CacheReadOptions() metav1.ListOptions

CacheReadOptions returns ListOptions configured to read from the apiserver watch cache. Use these for any read that does not need a strict-consistency guarantee against etcd; on a busy cluster this is an order-of-magnitude reduction in apiserver load. Scanners can also extend the returned options with their own FieldSelector or LabelSelector when needed.

func ListAll

func ListAll[L ListPage, T any](ctx context.Context, opts metav1.ListOptions,
	list func(context.Context, metav1.ListOptions) (L, error), items func(L) []T) ([]T, error)

ListAll pages through a cluster-wide list and returns every item. list is the client's List method, for example clientset.CoreV1().Secrets("").List or dyn.Resource(gvr).List, and items extracts a page's items. opts is the first request: pass CacheReadOptions to read from the watch cache, plus any selectors. A zero Limit becomes DefaultListLimit. Later pages carry the continue token and the selectors but no resource version, which the apiserver rejects alongside a token. Each page gets DefaultListTimeout. A continue token that expires mid-list restarts the list once from the first page.

func Names added in v0.10.0

func Names(results map[string]map[string]Result) []string

Names returns the unique scanner names across every cluster's results, sorted.

func TopN added in v0.13.0

func TopN[T any](items []T, n int, cmp func(a, b T) int) []T

TopN sorts items in place by cmp and returns at most the first n. The sort is stable, so items cmp ranks equal keep their input order. Callers give cmp a full tie-break so the result does not depend on the order the API listed the objects in.

Types

type Coverage added in v0.10.0

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

Coverage folds the outcome of each API read a scanner makes into the State and Reason of its result. The zero value is ready to use.

func (*Coverage) Finish added in v0.10.0

func (c *Coverage) Finish(name string, data any) (Result, error)

Finish builds the scanner's result from data and the observed reads:

Every read succeeded, or the only failures are types the server does not serve while some read succeeded: StateOK, since an absent type is nothing missing. Every read failed and every failure is an unserved type: StateUnavailable with data. Some read succeeded and another failed for any other reason: StateDegraded with data, which is real but partial. No read succeeded, or a required read failed for any reason other than an unserved type: StateErrored with no data, plus an error wrapping ErrScan and every read's error so the failure is logged and the data never counts as a measurement.

func (*Coverage) Observe added in v0.10.0

func (c *Coverage) Observe(what string, err error) bool

Observe records the outcome of one read, named by what (for example "secrets"), and reports whether it succeeded.

func (*Coverage) Require added in v0.10.0

func (c *Coverage) Require(what string, err error) bool

Require records the outcome of one read the scanner cannot report without, named by what, and reports whether it succeeded. Use it for a read whose absence would make the result's other fields read as clean, such as a role list that every binding count depends on.

type Func added in v0.12.0

type Func func(ctx context.Context, client *kube.Client) (Result, error)

Func adapts a plain function to the Scanner interface.

func (Func) Scan added in v0.12.0

func (f Func) Scan(ctx context.Context, client *kube.Client) (Result, error)

Scan calls the underlying function.

type ListPage added in v0.10.0

type ListPage interface {
	// GetContinue returns the token for the next page, or "" on the last page.
	GetContinue() string
}

ListPage is one page of a list response, typed or unstructured, that can name the next page.

type Registry

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

Registry maps scanner names to their implementations.

func NewRegistry

func NewRegistry() *Registry

NewRegistry creates an empty scanner registry.

func (*Registry) All

func (r *Registry) All() map[string]Scanner

All returns a copy of the internal scanner map.

func (*Registry) Get

func (r *Registry) Get(name string) (Scanner, bool)

Get returns the scanner registered under name, or false if not found.

func (*Registry) Names

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

Names returns all registered scanner names in sorted order.

func (*Registry) Register

func (r *Registry) Register(name string, s Scanner)

Register adds a scanner under the given name. Panics on duplicate names.

type Result

type Result struct {
	// Scanner is the name identifying which scanner produced this result.
	Scanner string `json:"scanner"`
	// State records how much to trust Data. The zero value means StateOK.
	State State `json:"state,omitempty"`
	// Reason is a short explanation when State is not OK. Empty otherwise.
	Reason string `json:"reason,omitempty"`
	// Data is the scanner-specific payload.
	Data any `json:"data"`
}

Result holds the output of a single scanner run against one cluster.

func ErroredResult added in v0.2.0

func ErroredResult(name string, err error) Result

ErroredResult builds a result that records a failed scan for one cluster so the fleet report can surface the failure instead of dropping it silently.

func RunWithTimeout added in v0.5.0

func RunWithTimeout(ctx context.Context, s Scanner, client *kube.Client, timeout time.Duration) (Result, error)

RunWithTimeout runs a scanner against a client under a deadline. A zero or negative timeout disables the deadline. A timeout surfaces as an ordinary scan error, which the caller records as degraded coverage rather than a clean result.

func (Result) Blind added in v0.2.0

func (r Result) Blind() bool

Blind reports whether the scanner failed to observe the cluster, so its data is a failed read rather than a measurement and must be excluded from fleet statistics instead of counted as zero.

type Scanner

type Scanner interface {
	Scan(ctx context.Context, client *kube.Client) (Result, error)
}

Scanner collects cluster-specific data for a single scan dimension.

type State added in v0.2.0

type State string

State describes how much to trust a scanner's data for one cluster. It exists so an unreachable or forbidden API produces a degraded or errored result instead of an empty payload that reads as a clean, zero-resource cluster.

const (
	// StateOK means the scanner completed and its data is complete. It is the
	// zero value's meaning, so scanners that cannot fail need not set it.
	StateOK State = ""
	// StateDegraded means the scanner completed but some data is missing
	// because one or more API calls failed. The data present is real but
	// partial, so consumers must not read absent fields as zero.
	StateDegraded State = "degraded"
	// StateErrored means the scanner could not collect its data because an API
	// call failed or access was denied. The data must never be read as a real
	// "clean, zero resources" result.
	StateErrored State = "errored"
	// StateUnavailable means the scanned feature is genuinely absent, such as a
	// CRD that is not installed. This is a trustworthy "nothing here", not a
	// failure.
	StateUnavailable State = "unavailable"
)

func ClassifyError added in v0.10.0

func ClassifyError(err error) (State, string)

ClassifyError maps an error from a scanner's list read to the State that read leaves the result in and a short reason. A resource type the server does not serve (NotFound on a list, or no REST mapping) is StateUnavailable: the feature is absent and nothing exists to measure. Every other failure, Forbidden and Unauthorized included, is StateErrored, because a read that was denied or failed observed nothing and must never count as a clean, empty cluster. A nil error is StateOK with no reason. ClassifyError is for list reads; a NotFound on a Get means the object is absent, not the type.

Directories

Path Synopsis
Package admission audits MutatingWebhookConfigurations and ValidatingWebhookConfigurations for two failure modes that silently break clusters: webhooks whose backing service has zero healthy endpoints, and webhooks whose caBundle is expiring soon.
Package admission audits MutatingWebhookConfigurations and ValidatingWebhookConfigurations for two failure modes that silently break clusters: webhooks whose backing service has zero healthy endpoints, and webhooks whose caBundle is expiring soon.
Package certs scans TLS Secrets, Ingress TLS references, and admission webhook caBundles for upcoming expiry.
Package certs scans TLS Secrets, Ingress TLS references, and admission webhook caBundles for upcoming expiry.
Package clusterinfo collects node OS, kernel, container runtime, kubelet and kube-proxy versions and reports drift within a single cluster.
Package clusterinfo collects node OS, kernel, container runtime, kubelet and kube-proxy versions and reports drift within a single cluster.
Package crd enumerates the CustomResourceDefinitions installed on a cluster and surfaces per-cluster CRD divergence as a scanner result.
Package crd enumerates the CustomResourceDefinitions installed on a cluster and surfaces per-cluster CRD divergence as a scanner result.
Package deprecatedapis identifies in-use API versions that Kubernetes has deprecated or removed.
Package deprecatedapis identifies in-use API versions that Kubernetes has deprecated or removed.
Package events scans the apiserver's recent Event stream and aggregates per-namespace warning counts, surfacing clusters whose signal-to-noise has degraded.
Package events scans the apiserver's recent Event stream and aggregates per-namespace warning counts, surfacing clusters whose signal-to-noise has degraded.
Package geo locates clusters on Earth from node region/zone labels.
Package geo locates clusters on Earth from node region/zone labels.
Package imageaudit reports image hygiene across the fleet: digest pinning, latest-tag usage, distinct image counts, and optional registry probes for age and signature checks.
Package imageaudit reports image hygiene across the fleet: digest pinning, latest-tag usage, distinct image counts, and optional registry probes for age and signature checks.
Package ingress implements the scanner that lists ingress resources in a cluster.
Package ingress implements the scanner that lists ingress resources in a cluster.
Package metrics implements the scanner that reads node resource utilization from the metrics.k8s.io API.
Package metrics implements the scanner that reads node resource utilization from the metrics.k8s.io API.
Package namespace implements the scanner that lists namespaces in a cluster.
Package namespace implements the scanner that lists namespaces in a cluster.
Package networkpolicy implements the scanner that collects NetworkPolicy data from a cluster.
Package networkpolicy implements the scanner that collects NetworkPolicy data from a cluster.
Package nodehealth implements the scanner that checks node health conditions.
Package nodehealth implements the scanner that checks node health conditions.
Package policyreportingest reads wgpolicyk8s.io PolicyReport and ClusterPolicyReport custom resources written by other tools (Kyverno, Gatekeeper, Trivy, kube-bench) and aggregates their fail/warn results per cluster.
Package policyreportingest reads wgpolicyk8s.io PolicyReport and ClusterPolicyReport custom resources written by other tools (Kyverno, Gatekeeper, Trivy, kube-bench) and aggregates their fail/warn results per cluster.
Package quota inspects ResourceQuota and LimitRange coverage across namespaces.
Package quota inspects ResourceQuota and LimitRange coverage across namespaces.
Package rbac scans the cluster's RBAC graph (ClusterRoles, RoleBindings, ServiceAccounts) and flags wildcard permissions and over-broad bindings.
Package rbac scans the cluster's RBAC graph (ClusterRoles, RoleBindings, ServiceAccounts) and flags wildcard permissions and over-broad bindings.
Package rbacaudit implements the scanner that audits RBAC for over-permissive bindings and rules.
Package rbacaudit implements the scanner that audits RBAC for over-permissive bindings and rules.
Package resources implements the scanner that collects node capacity and condition data.
Package resources implements the scanner that collects node capacity and condition data.
Package security audits security-affecting workload configuration: PodSecurityStandards labels, default-deny NetworkPolicy presence, and similar fleet-wide hardening signals.
Package security audits security-affecting workload configuration: PodSecurityStandards labels, default-deny NetworkPolicy presence, and similar fleet-wide hardening signals.
Package service implements the scanner that lists services in a cluster.
Package service implements the scanner that lists services in a cluster.
Package version reports the Kubernetes server version from each cluster and detects fleet-wide skew.
Package version reports the Kubernetes server version from each cluster and detects fleet-wide skew.
Package vulnerabilities reads aquasecurity.github.io/v1alpha1 VulnerabilityReport custom resources produced by the Trivy Operator and aggregates their severity counts into a per-cluster baseline.
Package vulnerabilities reads aquasecurity.github.io/v1alpha1 VulnerabilityReport custom resources produced by the Trivy Operator and aggregates their severity counts into a per-cluster baseline.
Package workloadcoverage reports on PDB and HPA coverage of replicated workloads.
Package workloadcoverage reports on PDB and HPA coverage of replicated workloads.
Package workloadsec implements the scanner that audits pod security contexts across all namespaces.
Package workloadsec implements the scanner that audits pod security contexts across all namespaces.

Jump to

Keyboard shortcuts

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