mirror

package
v0.12.0 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2026 License: MIT Imports: 30 Imported by: 0 modules, 0 packages

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

Documentation

Overview

Package mirror is the engine behind `patchy mirror`: vendored mirroring of upstream helm charts and OCI artifacts into a platform registry, with review-gated updates, upstream provenance verification, vulnerability scanning and signing of everything published.

The mirror store is a git tree (the caller's, not this package's concern): charts/<name>/ and artifacts/<name>/ each hold an intent manifest plus machine-derived facts (vendored chart tree, rendered manifests, digest locks, allowlists). Registries, signing and the scan defaults come from the layered patchy config, which the CLI resolves and hands in as a spec.Config — the engine never discovers config files. The engine's verbs regenerate facts from intent (upgrade), converge the registry onto the committed facts (sync), and re-derive out-of-tree to prove the committed facts are current (validate).

The engine never touches git and never creates commits, branches or PRs — it mutates files (upgrade, add) or the registry (sync), and the calling pipeline owns version control. Wall-clock-dependent steps (tracked-tag cooldown picks, allowlist expiry stamping) run only in upgrade, keeping validate's byte-identity gate deterministic.

Subpackages hold one concern each; this package orchestrates them and owns the Engine API the CLI drives: typed results on stdout's behalf, Event narration on stderr's.

Index

Constants

View Source
const (
	// ActionPushed means the artifact was published (or would be, dry run).
	ActionPushed = "pushed"
	// ActionSkippedTagExists means the chart tag already exists — an
	// existing tag is NEVER replaced.
	ActionSkippedTagExists = "skipped-tag-exists"
	// ActionSkippedCurrent means the target already matches the lock and
	// carries a valid mirror signature.
	ActionSkippedCurrent = "skipped-current"
)

Sync actions.

View Source
const (
	StageRegen  = "regen"
	StageVerify = "verify"
	StageScan   = "scan"
	StageLint   = "lint"
)

Validate stage names for --only filtering.

Variables

ValidateStages is the full roster, in run order.

Functions

func ReadCommittedFacts

func ReadCommittedFacts(entry spec.Entry) (rendered []byte, lock []byte, err error)

ReadCommittedFacts loads the committed derived state for comparison with a regeneration. Missing files come back nil.

func WriteFacts

func WriteFacts(entry spec.Entry, facts *Facts) error

WriteFacts lands regenerated facts in the entry directory (the vendor tree is already in place when destDir was the entry dir).

Types

type AllowlistResult

type AllowlistResult struct {
	// Generated is false when the entry does not opt in.
	Generated bool `json:"generated"`
	Kept      int  `json:"kept"`
	// Renewed lists still-reported IDs whose lapsed expiry was restamped.
	Renewed []string `json:"renewed,omitempty"`
	Added   int      `json:"added"`
	// Dropped lists IDs no longer reported.
	Dropped []string `json:"dropped,omitempty"`
}

AllowlistResult reports one derivation.

type ArtifactSigner

type ArtifactSigner = sign.ArtifactSigner

ArtifactSigner signs one OCI artifact reference.

type Config

type Config struct {
	// Root is the mirror store root (the directory holding charts/ and
	// artifacts/).
	Root string
	// Global is the resolved mirror view of the patchy config.
	Global *spec.Config
	// Now is the wall clock; injectable for tests. Only upgrade-path
	// stages may consult it.
	Now func() time.Time
	// Workers bounds concurrent registry operations (default 4).
	Workers int
	// OnEvent receives narration events (nil discards them).
	OnEvent func(Event)
	// Registry performs OCI operations (nil: ambient keychain).
	Registry *ocireg.Client
	// HTTP performs helm-repository fetches (nil: http.DefaultClient).
	HTTP *http.Client
	// Verify checks one signature subject (nil: the real cosign-backed
	// verifier). Tests inject key-based verification.
	Verify func(context.Context, verify.Subject) error
	// NewSigner builds a signer for a resolved signing config (nil: the
	// real keyless/KMS signer). Tests inject a key-file signer.
	NewSigner func(*spec.Signing) (ArtifactSigner, error)
	// PushChart pushes a chart tgz to ref, returning the manifest digest
	// (nil: the helm-layout push).
	PushChart func(tgz []byte, ref string) (string, error)
	// Tools runs external tool binaries — scanners and cosign (nil: the
	// real PATH).
	Tools scan.ToolRunner
	// ImageScanners overrides the enabled scanner roster (nil: built
	// from the global scan config). Tests inject fakes.
	ImageScanners []scan.ImageScanner
}

Config wires an Engine.

type Engine

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

Engine runs the mirror pipeline stages over one store.

func New

func New(cfg Config) *Engine

New builds an Engine.

func (*Engine) ApplyTracks

func (e *Engine) ApplyTracks(ctx context.Context, entry spec.Entry) ([]TrackPlan, error)

ApplyTracks re-picks every tracked pin and splices changed picks into the values files. Wall-clock dependent — upgrade only, never validate, or the byte-identity gate would fail whenever a tag aged past the cooldown between commit and CI.

func (*Engine) CheckUpdates

func (e *Engine) CheckUpdates(ctx context.Context, entries []spec.Entry) (*UpdatePlan, error)

CheckUpdates computes the update plan for the given entries without touching the tree: newest satisfying versions, lockstep group targets, and tracked-image cooldown picks.

func (*Engine) DeriveAllowlist

func (e *Engine) DeriveAllowlist(ctx context.Context, entry spec.Entry) (*AllowlistResult, error)

DeriveAllowlist regenerates the entry's security/allowlist.yaml from a fresh scan, for charts and artifacts whose resolved scan.allowlist generate is true. Runs during upgrade only — the finding set moves with the vulnerability databases, so deriving inside validate would diff a tree nobody touched.

func (*Engine) DeriveDistribution

func (e *Engine) DeriveDistribution(ctx context.Context, entry spec.Entry) ([]spec.ExtraImage, error)

DeriveDistribution regenerates a chart entry's images.extra.yaml sidecar from its distribution manifests artifact, at the tag matching the vendored chart's appVersion. No-op (and nil result) for entries without a distributionManifests block. Returns the derived extras.

func (*Engine) Entries

func (e *Engine) Entries() ([]spec.Entry, error)

Entries discovers every entry in the store.

func (*Engine) Entry

func (e *Engine) Entry(name string) (spec.Entry, error)

Entry loads one entry by name.

func (*Engine) Lint

func (e *Engine) Lint(entry spec.Entry) ([]string, error)

Lint checks one entry's manifest and allowlist against store policy. Schema-level validity (kinds, name/dir match, unknown fields) is already enforced at load time; lint covers the rules a well-formed file can still break.

func (*Engine) Regenerate

func (e *Engine) Regenerate(ctx context.Context, entry spec.Entry, destDir string, deriveDistro bool) (*Facts, error)

Regenerate derives an entry's facts from its manifest: for charts, pull the pinned tgz, extract it into destDir/vendor, render with the discovery values, discover and digest-pin every referenced image; for artifacts, resolve the pinned version to a digest. destDir is where the vendor tree materializes (usually the entry dir; validate points it at scratch); the returned Facts carry everything else.

deriveDistro re-derives the distribution-manifests sidecar between vendor and discovery (upgrade); when false the committed sidecar is used as-is (validate must not re-derive what the tree pins).

func (*Engine) Scan

func (e *Engine) Scan(ctx context.Context, entry spec.Entry) (*ScanReport, error)

Scan runs every enabled scanner over the entry's locked images (by digest), applies the entry's resolved blocking policy and the allowlist, and sweeps the rendered manifests for configuration findings.

func (*Engine) SelectRegistries added in v0.11.0

func (e *Engine) SelectRegistries(names []string) ([]spec.Registry, error)

SelectRegistries resolves registry names against the config: nil means every configured registry, an unknown name is an error. The CLI validates and completes --registry through this.

func (*Engine) SetVersion

func (e *Engine) SetVersion(entry spec.Entry, version string) error

SetVersion splices a new pinned version into an entry's manifest.yaml, touching only the version token. The entry must be reloaded afterwards.

func (*Engine) Sync

func (e *Engine) Sync(ctx context.Context, entry spec.Entry, opts SyncOptions) (*SyncResult, error)

Sync converges the registries onto the entry's committed state. Read-only on the working tree: every write goes to a registry. Idempotent per (registry, tag) — an existing chart tag is never replaced, a current-and-signed image is skipped. Each registry's pushes are signed with its effective signing config (its own block, else the global one).

func (*Engine) Upgrade

func (e *Engine) Upgrade(ctx context.Context, entry spec.Entry, target string) (*UpgradeResult, error)

Upgrade converges one entry: splice the target pin (empty target keeps the current pin), re-pick tracked tags, then regenerate the derived state in place. Later pipeline stages (upstream verification, scanning, allowlist derivation) run on top of the regenerated tree.

func (*Engine) UpgradePinned added in v0.11.4

func (e *Engine) UpgradePinned(ctx context.Context, entry spec.Entry) (*UpgradeResult, error)

UpgradePinned converges one entry on the pins already in the tree: an external updater (Renovate) moved the chart version or a tracked tag, and patchy only regenerates what derives from them. Nothing is picked — no target resolution, no tracked-tag cooldown walk — but every pin is checked against its constraint and its lockstep group first, so a bad bump fails loudly instead of shipping.

func (*Engine) Validate

func (e *Engine) Validate(ctx context.Context, entry spec.Entry, only []string) (*ValidateResult, error)

Validate proves one entry's committed state is current and clean without touching the tree: regenerate the derived state out-of-tree and byte-compare, verify upstream provenance, scan, and lint. only filters the stages (nil or empty runs all). Wall-clock steps (tracked picks, allowlist stamping) never run here — the byte-identity gate must stay deterministic.

func (*Engine) ValidatePins added in v0.11.4

func (e *Engine) ValidatePins(entry spec.Entry) error

ValidatePins checks an entry's pins as an external updater left them: the version satisfies versionConstraint, every tracked tag satisfies its explicit versionConstraint, and every lockstep group member in the store pins the same version.

func (*Engine) VerifyUpstream

func (e *Engine) VerifyUpstream(ctx context.Context, entry spec.Entry) (*VerifyReport, error)

VerifyUpstream checks the entry's upstream provenance per its manifest rules: the chart or artifact itself, then every locked image (first matching rule wins; every image must match one).

type Event

type Event struct {
	// Kind is "note" (progress), "warn" (survivable problem worth eyes)
	// or "stage" (a pipeline stage boundary).
	Kind string `json:"kind"`
	// Entry is the entry being worked, when applicable.
	Entry string `json:"entry,omitempty"`
	// Stage is the pipeline stage emitting the event.
	Stage string `json:"stage,omitempty"`
	// Message is the human-readable line.
	Message string `json:"message"`
}

Event narrates engine progress. Events are stderr material (or NDJSON under -o json); typed results returned by engine methods are the data.

type Facts

type Facts struct {
	// VendorTgz is the upstream chart archive (charts only).
	VendorTgz []byte
	// Rendered is the rendered manifest stream (charts only).
	Rendered []byte
	// ImagesLock is the chart lock (charts only).
	ImagesLock *spec.ImagesLock
	// ArtifactLock is the artifact lock (artifacts only).
	ArtifactLock *spec.ArtifactLock
	// Excluded lists image references dropped by exclude globs.
	Excluded []string
}

Facts is the regenerated derived state of one entry, in memory. Callers choose where it lands: the entry directory (upgrade) or a scratch tree for byte-comparison (validate).

type MemberPlan

type MemberPlan struct {
	Name string `json:"name"`
	Kind string `json:"kind"`
	// Current is the pinned version.
	Current string `json:"current"`
	// Newest is the newest satisfying upstream version for this member
	// alone (>= Current).
	Newest string `json:"newest"`
	// Target echoes the group target this member will move to.
	Target string `json:"target"`
	// TrackedImages reports cooldown picks for the entry's tracked
	// images; entries appear even when the pick equals the current pin.
	TrackedImages []TrackPlan `json:"trackedImages,omitempty"`
}

MemberPlan is one entry's part in a group update.

type ScanReport

type ScanReport struct {
	// Blocking are findings at blocking severity that survived the
	// allowlist; any entry here fails the gate.
	Blocking []scan.Finding `json:"blocking,omitempty"`
	// Suppressed counts findings the allowlist accepted.
	Suppressed int `json:"suppressed"`
	// Scanned lists the references scanned.
	Scanned []string `json:"scanned,omitempty"`
	// ConfigScan reports the kubescape sweep: "clean", "findings",
	// "failed", or a skip reason.
	ConfigScan string `json:"configScan,omitempty"`
	// ConfigScanFailed blocks under kubescape fail mode.
	ConfigScanFailed bool `json:"configScanFailed,omitempty"`
}

ScanReport is one entry's vulnerability-scan outcome.

func (*ScanReport) Failed

func (r *ScanReport) Failed() bool

Failed reports whether the gate blocks.

type SyncOptions added in v0.11.0

type SyncOptions struct {
	// DryRun computes every action without writing to the registry.
	DryRun bool
	// Registries restricts publishing to the named registries (nil: all).
	Registries []string
}

SyncOptions tunes one Sync call.

type SyncRecord

type SyncRecord struct {
	// Registry is the configured registry name the record converged.
	Registry string `json:"registry"`
	// Ref is the mirror reference operated on.
	Ref string `json:"ref"`
	// Digest is the manifest digest at Ref after the sync.
	Digest string `json:"digest"`
	// Action is what happened (pushed, skipped-tag-exists,
	// skipped-current).
	Action string `json:"action"`
	// Signed reports whether a signature was created this run.
	Signed bool `json:"signed"`
}

SyncRecord is one published artifact's outcome at one registry.

type SyncResult

type SyncResult struct {
	Name    string       `json:"name"`
	Kind    string       `json:"kind"`
	Records []SyncRecord `json:"records"`
	// Err carries a per-entry failure in --all summaries.
	Err string `json:"error,omitempty"`
}

SyncResult is one entry's sync outcome.

type TrackPlan

type TrackPlan struct {
	Image      string `json:"image"`
	ValuesFile string `json:"valuesFile"`
	ValuesPath string `json:"valuesPath"`
	Current    string `json:"current"`
	Selected   string `json:"selected"`
	// TagOnly means the values pin is a bare tag (the chart splits
	// repository from tag), so the pick splices just the tag.
	TagOnly bool `json:"tagOnly,omitempty"`
}

TrackPlan is one tracked image's cooldown pick.

func (TrackPlan) Changed

func (t TrackPlan) Changed() bool

Changed reports whether the pick moves the pin.

type UpdateGroup

type UpdateGroup struct {
	// Group is the lockstep name, or the entry name for solo entries.
	Group string `json:"group"`
	// Target is the group target version: the LOWEST of the members'
	// newest satisfying versions — upstream publishes lockstep members
	// near-simultaneously, so the bump holds until every member carries
	// the tag.
	Target string `json:"target"`
	// Members lists every entry in the group, including ones already at
	// Target (their tracked images may still move).
	Members []MemberPlan `json:"members"`
}

UpdateGroup is one update unit: every member bumps to Target in one PR.

type UpdatePlan

type UpdatePlan struct {
	Groups []UpdateGroup `json:"groups"`
}

UpdatePlan is the read-only answer to "what would upgrade do": one group per lockstep set (solo entries form singleton groups), only groups with work included. Empty Groups means the whole store is current.

type UpgradeResult

type UpgradeResult struct {
	Name string `json:"name"`
	Kind string `json:"kind"`
	// From and To are the pinned versions before and after (equal when
	// the pin did not move).
	From string `json:"from"`
	To   string `json:"to"`
	// Tracked reports the tracked-image picks applied.
	Tracked []TrackPlan `json:"tracked,omitempty"`
	// Changed lists entry-relative paths the upgrade rewrote. Empty
	// means the entry was already fully converged — a clean no-op.
	Changed []string `json:"changed,omitempty"`
	// Err carries a per-entry failure in --all summaries.
	Err string `json:"error,omitempty"`
}

UpgradeResult reports one entry's convergence.

type ValidateResult

type ValidateResult struct {
	Name string `json:"name"`
	Kind string `json:"kind"`
	// RegenDiffs lists derived files that no longer match a fresh
	// regeneration (the committed tree is stale — run upgrade).
	RegenDiffs []string `json:"regenDiffs,omitempty"`
	// Lint lists manifest/allowlist policy violations.
	Lint []string `json:"lint,omitempty"`
	// Verify is the upstream-provenance outcome.
	Verify *VerifyReport `json:"verify,omitempty"`
	// Scan is the vulnerability-scan outcome.
	Scan *ScanReport `json:"scan,omitempty"`
	// Err carries a stage failure (not a finding — the stage itself
	// broke or a verification failed).
	Err string `json:"error,omitempty"`
}

ValidateResult is one entry's validation outcome.

func (*ValidateResult) Failed

func (r *ValidateResult) Failed() bool

Failed reports whether validation blocks.

type VerifyReport

type VerifyReport struct {
	Verified []string `json:"verified,omitempty"`
	Gaps     []string `json:"gaps,omitempty"`
}

VerifyReport is one entry's upstream-provenance outcome. Gaps are subjects a provider-none rule deliberately leaves unverified — reported, never silently dropped, and never failures.

Directories

Path Synopsis
Package allowlist derives an entry's allowlist (a mirror entry's security/allowlist.yaml, a build entry's security/allowlists/<name>.yaml) from the blocking findings of a fresh scan, and lints any allowlist against the accepted-risk policy — mirror and build share both halves, so the two apply identical rules.
Package allowlist derives an entry's allowlist (a mirror entry's security/allowlist.yaml, a build entry's security/allowlists/<name>.yaml) from the blocking findings of a fresh scan, and lints any allowlist against the accepted-risk policy — mirror and build share both halves, so the two apply identical rules.
Package discover finds every container image a rendered chart references, in four passes: pod-spec container lists (containers, initContainers, ephemeralContainers — as sequences at any depth, which skips the CRD schemas where those keys hold maps), operator-style top-level spec.image scalars, a conservative regex sweep over ConfigMap data for image-shaped strings (embedded pod templates), and the manifest-declared extras ({appVersion} expanded from the vendored chart).
Package discover finds every container image a rendered chart references, in four passes: pod-spec container lists (containers, initContainers, ephemeralContainers — as sequences at any depth, which skips the CRD schemas where those keys hold maps), operator-style top-level spec.image scalars, a conservative regex sweep over ConfigMap data for image-shaped strings (embedded pod templates), and the manifest-declared extras ({appVersion} expanded from the vendored chart).
Package distro derives extra mirrored images from a distribution manifests artifact, for charts whose workload images are deployed by an operator from manifests helm never renders — so image discovery cannot see them, and hand-pinned extras drift the moment upstream cuts a release.
Package distro derives extra mirrored images from a distribution manifests artifact, for charts whose workload images are deployed by an operator from manifests helm never renders — so image discovery cannot see them, and hand-pinned extras drift the moment upstream cuts a release.
Package helmchart moves chart archives between upstreams, the vendored tree and the mirror registry.
Package helmchart moves chart archives between upstreams, the vendored tree and the mirror registry.
Package imageref manipulates container image references as strings: it expands docker shorthand the way container runtimes do, splits a reference into repository, tag and digest (tolerating registry ports and pinned digests), applies source-registry rewrites, and matches shell-style glob patterns against references.
Package imageref manipulates container image references as strings: it expands docker shorthand the way container runtimes do, splits a reference into repository, tag and digest (tolerating registry ports and pinned digests), applies source-registry rewrites, and matches shell-style glob patterns against references.
Package ocireg is the one registry seam mirror and build share: thin wrappers over go-containerregistry for the operations the engines need — digest resolution, tag listing, config inspection, byte-preserving copies, existence probes, raw pulls, and pushes of locally built images and indexes.
Package ocireg is the one registry seam mirror and build share: thin wrappers over go-containerregistry for the operations the engines need — digest resolution, tag listing, config inspection, byte-preserving copies, existence probes, raw pulls, and pushes of locally built images and indexes.
Package render produces an entry's rendered/manifests.yaml: the vendored chart rendered with its discovery values, exactly as `helm template <name> <vendor dir> --namespace ...
Package render produces an entry's rendered/manifests.yaml: the vendored chart rendered with its discovery values, exactly as `helm template <name> <vendor dir> --namespace ...
Package scan finds vulnerabilities in images through pluggable scanners — osv-scanner and grype, both shell-outs — either by registry reference (ImageScanner: the mirror's locked images) or over a local docker archive (ArchiveScanner: a fresh build, scanned before anything is pushed).
Package scan finds vulnerabilities in images through pluggable scanners — osv-scanner and grype, both shell-outs — either by registry reference (ImageScanner: the mirror's locked images) or over a local docker archive (ArchiveScanner: a fresh build, scanned before anything is pushed).
Package semverpick selects versions from candidate lists: the newest stable release satisfying a constraint (chart and artifact update checks), and the newest tag that has soaked past a cooldown window (tracked-image picks, where a just-published tag can still be yanked or hot-fixed).
Package semverpick selects versions from candidate lists: the newest stable release satisfying a constraint (chart and artifact update checks), and the newest tag that has soaked past a cooldown window (tracked-image picks, where a just-published tag can still be yanked or hot-fixed).
Package sign signs published OCI artifacts: keylessly (ambient OIDC — the CI workflow's identity — through Fulcio, with a public transparency log entry) or with a cloud KMS key (gcpkms://, awskms://, azurekms://).
Package sign signs published OCI artifacts: keylessly (ambient OIDC — the CI workflow's identity — through Fulcio, with a public transparency log entry) or with a cloud KMS key (gcpkms://, awskms://, azurekms://).
Package spec defines the mirror store's on-disk contract: the per-entry manifest.yaml files (intent), the lock files (facts), the generated images.extra.yaml sidecar, and the CVE allowlists — plus the typed blocks the layered patchy config shares between mirror and build (registries, signing, and the one scan block every entry overrides field by field).
Package spec defines the mirror store's on-disk contract: the per-entry manifest.yaml files (intent), the lock files (facts), the generated images.extra.yaml sidecar, and the CVE allowlists — plus the typed blocks the layered patchy config shares between mirror and build (registries, signing, and the one scan block every entry overrides field by field).
Package verify checks OCI artifact signatures for the mirror: upstream provenance per a manifest's verifyUpstream rules (keyless with an identity regexp, or a published public key), and the mirror's own signatures (the exact certificate identity or KMS key it signs with — the publish-idempotency self-check).
Package verify checks OCI artifact signatures for the mirror: upstream provenance per a manifest's verifyUpstream rules (keyless with an identity regexp, or a published public key), and the mirror's own signatures (the exact certificate identity or KMS key it signs with — the publish-idempotency self-check).
Package yamledit performs surgical edits on YAML files that humans and other tools also write: it uses the YAML AST only to LOCATE a scalar, then byte-splices exactly that token, never re-encoding the document.
Package yamledit performs surgical edits on YAML files that humans and other tools also write: it uses the YAML AST only to LOCATE a scalar, then byte-splices exactly that token, never re-encoding the document.

Jump to

Keyboard shortcuts

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