admin

package
v3.2.0 Latest Latest
Warning

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

Go to latest
Published: Dec 6, 2026 License: MIT Imports: 24 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 admin implements sockguard's in-band admin HTTP endpoints.

The admin surface exposes three endpoints:

POST <admin.path>                 parse + validate + compile a candidate
                                  YAML config and return a structured JSON
                                  report; the running policy is unaffected.

GET  <admin.policy_version_path>  return the current policy generation as a
                                  JSON PolicySnapshot (version counter,
                                  rule/profile counts, load timestamp, and
                                  optional bundle provenance metadata).

POST <admin.policy_diff_path> compares a candidate with one active generation without returning configuration values.

The endpoints are opt-in (admin.enabled=false by default) and can either ride the main listener or be bound to a dedicated admin.listen socket. When riding the main listener they inherit its CIDR allowlist, mTLS posture, and the per-profile rate-limit / concurrency gates configured under clients.profiles[*].limits. Wire-up in internal/cmd/serve.go places both interceptors between the rate-limit middleware and the filter middleware so admin requests are rate-limited like every other caller but never reach the Docker-API rule evaluator.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ApprovalAuditRecord added in v3.2.0

func ApprovalAuditRecord(step string, e approvals.Entry) logging.ApprovalAudit

ApprovalAuditRecord builds the audit record for a step from an entry. It names the request envelope and the rendering digest, never a leaf value.

func NewApprovalsInterceptor added in v3.2.0

func NewApprovalsInterceptor(opts ApprovalsOptions) func(http.Handler) http.Handler

NewApprovalsInterceptor returns a middleware that serves the operator approval endpoints on the dedicated admin chain:

GET  /admin/approvals?state=pending|approved|denied|all
GET  /admin/approvals/{id}
POST /admin/approvals/{id}

The routes are fixed and exist only where this middleware is installed, which is the admin chain and nothing else. Anything else falls through.

func NewPolicyDiffInterceptor

func NewPolicyDiffInterceptor(opts PolicyDiffOptions) func(http.Handler) http.Handler

NewPolicyDiffInterceptor compares a bounded body against one generation.

func NewPolicyVersionInterceptor

func NewPolicyVersionInterceptor(opts PolicyVersionOptions) func(http.Handler) http.Handler

NewPolicyVersionInterceptor returns a middleware that short-circuits GET <path> with a JSON snapshot of the active policy generation. Any other method on <path> returns 405 Allow: GET. Requests for other paths fall through to next.

The endpoint is intentionally read-only and does not accept a request body: it reports state, never mutates it.

func NewValidateInterceptor

func NewValidateInterceptor(opts Options) func(http.Handler) http.Handler

NewValidateInterceptor returns a middleware that short-circuits POST <path> to the configured validator. All other requests pass through to next.

Method gating: anything other than POST on <path> returns 405 with Allow: POST. The body is hard-capped at MaxRequestBytes via http.MaxBytesReader; oversize bodies return 413. When BodyReadTimeout is set, expired reads return 408. YAML parse / validation failures return 422 with a structured ValidateResponse.

Types

type ApprovalAuditor added in v3.2.0

type ApprovalAuditor interface {
	// Enabled reports whether an audit sink is configured. With one, an
	// approval is only recorded as made when its audit record was accepted.
	Enabled() bool
	// Record queues one record and reports whether it was accepted. It must
	// not block.
	Record(logging.ApprovalAudit) bool
	// RecordAcked writes one record and returns only once the audit writer has
	// handed it to the sink, or an error when it did not. An approval waits on
	// this, so it cannot commit unless its record is on its way to disk.
	RecordAcked(context.Context, logging.ApprovalAudit) error
}

ApprovalAuditor writes approval lifecycle records to the audit sink.

type ApprovalsOptions added in v3.2.0

type ApprovalsOptions struct {
	Registry *approvals.Registry
	// Audit receives one record per transition the endpoints cause. Nil
	// means no audit sink.
	Audit  ApprovalAuditor
	Logger *slog.Logger
}

ApprovalsOptions configures NewApprovalsInterceptor.

type Options

type Options struct {
	Path            string
	MaxRequestBytes int64
	BodyReadTimeout time.Duration
	Validate        Validator
	Logger          *slog.Logger
}

Options configures Interceptor.

Path must start with "/". MaxRequestBytes caps the request body to prevent abusive callers from forcing sockguard to parse arbitrarily large YAML. BodyReadTimeout bounds body reads when the listener leaves ReadTimeout unset. Validate is required.

type PolicyDiffOptions

type PolicyDiffOptions struct {
	Path            string
	MaxRequestBytes int64
	BodyReadTimeout time.Duration
	Source          func() *PolicySnapshot
	Compare         func([]byte, *PolicySnapshot) PolicyDiffResponse
	Logger          *slog.Logger
}

type PolicyDiffResponse

type PolicyDiffResponse struct {
	OK              bool                  `json:"ok"`
	BaseVersion     int64                 `json:"base_version,omitempty"`
	Changed         bool                  `json:"changed"`
	Changes         []config.PolicyChange `json:"changes"`
	UnknownKeys     int                   `json:"unknown_keys,omitempty"`
	Validation      string                `json:"validation,omitempty"`
	RestartRequired bool                  `json:"restart_required"`
	Error           string                `json:"error,omitempty"`
}

type PolicySnapshot

type PolicySnapshot struct {
	// Config is immutable after publication and never enters the version JSON.
	Config       *config.Config `json:"-"`
	Version      int64          `json:"version"`
	LoadedAt     time.Time      `json:"loaded_at"`
	Rules        int            `json:"rules"`
	Profiles     int            `json:"profiles"`
	CompatActive bool           `json:"compat_active"`
	Source       string         `json:"source"` // "startup" or "reload"
	ConfigSHA256 string         `json:"config_sha256,omitempty"`
	// BundleSource is the basename (filename only, no directory component) of
	// the sigstore bundle file that vouched for the running policy, or ""
	// when policy_bundle.enabled=false. The basename is sufficient to tell
	// operators which bundle was loaded without leaking the host's filesystem
	// layout to Docker API callers on the main listener.
	BundleSource string `json:"bundle_source,omitempty"`
	// BundleSigner is a stable identifier of the accepting trust path:
	// "keyed:<spki-fingerprint>" or "keyless:<issuer>:<san>".
	// Empty when policy_bundle is disabled.
	BundleSigner string `json:"bundle_signer,omitempty"`
	// BundleDigest is the sha256 hex digest of the YAML bytes verified
	// against the bundle. Empty when policy_bundle is disabled. This is the
	// same digest the bundle signs over, so it doubles as proof that the
	// YAML on disk matches what the operator published.
	BundleDigest string `json:"bundle_digest,omitempty"`
}

PolicySnapshot is the in-process record of a single active policy generation. It is published once at startup and replaced on every successful hot reload. Operators query it via GET <admin.policy_version_path> to confirm that a configuration change actually took effect.

Version is a monotonic counter starting at 1 on the first publish; it only ticks on a successful apply, so a stable Version across two scrapes means the running policy genuinely did not move.

type PolicyVersionOptions

type PolicyVersionOptions struct {
	Path   string
	Source func() *PolicySnapshot
	Logger *slog.Logger
}

PolicyVersionOptions configures NewPolicyVersionInterceptor.

Path must start with "/". Source is the snapshot accessor — production wiring passes (*PolicyVersioner).Snapshot, tests pass a closure. A nil Source degrades to a 503 middleware so a wiring bug fails closed instead of returning bogus data.

type PolicyVersioner

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

PolicyVersioner publishes the active policy snapshot. The store side (Update) is serialized by an internal mutex so the counter can't drop an increment under concurrent callers — production traffic only ever comes from the reload coordinator, but the contract is "thread-safe", so we don't lean on the caller's serialization. The load side (Snapshot) uses atomic.Pointer for wait-free reads.

func NewPolicyVersioner

func NewPolicyVersioner() *PolicyVersioner

NewPolicyVersioner returns a versioner with no snapshot yet. Callers must invoke Update at least once before HTTP queries can succeed; until then the endpoint returns 503.

func (*PolicyVersioner) Snapshot

func (v *PolicyVersioner) Snapshot() *PolicySnapshot

Snapshot returns the current active generation, or nil if Update has never been called. Callers must not mutate the returned pointer.

func (*PolicyVersioner) Update

func (v *PolicyVersioner) Update(snap PolicySnapshot) int64

Update stamps the supplied snapshot as the active generation, assigning a fresh monotonic Version (prev+1, or 1 if this is the first call). The caller-supplied Version field on snap is ignored — the counter is owned by the versioner. Returns the assigned version so callers can mirror it into metrics / logs.

Update is safe to call from any goroutine; the load-then-store on the counter happens under v.mu, so concurrent callers cannot collide on the same Version value.

type ValidateResponse

type ValidateResponse struct {
	OK           bool     `json:"ok"`
	Errors       []string `json:"errors,omitempty"`
	Rules        int      `json:"rules,omitempty"`
	Profiles     int      `json:"profiles,omitempty"`
	CompatActive bool     `json:"compat_active,omitempty"`
}

ValidateResponse is the JSON body returned by the validate endpoint.

On success: OK=true, Rules is the number of top-level compiled rules, Profiles is the number of compiled client profiles, CompatActive is true when Tecnativa-compat env aliases injected rules. Errors is nil.

On validation failure: OK=false and Errors carries the human-readable validator output split per-issue. Rules / Profiles are zero.

type Validator

type Validator func(yaml []byte) ValidateResponse

Validator is the callback wired up by internal/cmd that knows how to parse YAML bytes, run config.Validate + rule compilation, and report the result. Keeping the validator pluggable avoids an import cycle on internal/cmd while still letting this package own the HTTP surface.

Jump to

Keyboard shortcuts

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