state

package
v0.7.1 Latest Latest
Warning

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

Go to latest
Published: Oct 15, 2026 License: AGPL-3.0 Imports: 13 Imported by: 0

Documentation

Overview

Package state owns the agent's durable store: the device registry, the audit trail, and the schema version that gates upgrades.

The store is a SQLite database in WAL mode on the operator's bind mount. Callers never see *sql.DB or a SQL string — everything goes through methods on Store, each taking a context.Context first.

Index

Constants

View Source
const (
	OutcomeSuccess      = "success"
	OutcomeDeniedPolicy = "denied_policy"
	OutcomeDeniedSelf   = "denied_self"
	// OutcomeDeniedProtected is recorded when a lifecycle operation targets a
	// container matching the operator's DEVMON_PROTECTED_CONTAINERS list.
	OutcomeDeniedProtected = "denied_protected"
	OutcomeNotFound        = "not_found"
	OutcomeInvalid         = "invalid"
	OutcomeConflict        = "conflict"
	OutcomeUnavailable     = "unavailable" // self ID unknown (D3)
	OutcomeEngineError     = "engine_error"
	// OutcomeInternalError covers a failure on the agent's own side that is
	// neither the caller's fault nor a Docker Engine error — for example a
	// store write that failed while issuing or recording a device
	// certificate during pairing or renewal.
	OutcomeInternalError = "internal_error"
)
View Source
const DefaultPairingCodeTTL = 10 * time.Minute

DefaultPairingCodeTTL is the TTL callers should pass to MintPairingCode absent an operator-configured override. Ten minutes is long enough for an operator to read the code aloud or type it on a phone, short enough that a leaked, unused code stops mattering quickly — rate limiting is Phase 6, so the code's own lifetime is part of what keeps it safe until then (D3).

Variables

View Source
var (
	// ErrStateCorrupt means the file exists but is not a usable database — the
	// realistic outcome of a botched restore or a truncated copy.
	ErrStateCorrupt = errors.New("state store is unreadable or corrupt")
	// ErrSchemaTooNew means the store was written by a newer agent version.
	ErrSchemaTooNew = errors.New("state store was written by a newer agent version")
	// ErrDeviceNotFound means no device matches the given id or certificate
	// serial. Callers branch on this to distinguish "unknown" from other
	// failures; it never reveals whether the caller has ever seen that id.
	ErrDeviceNotFound = errors.New("device not found")
	// ErrPairingCodeInvalid covers every reason a pairing code cannot be
	// redeemed — unknown, expired, or already used. It is deliberately one
	// error: distinguishing those cases to a caller would let it enumerate
	// code state.
	ErrPairingCodeInvalid = errors.New("pairing code is invalid or expired")
)

Sentinel errors for the two conditions a caller must branch on. Both are fatal at startup, because a loud, early, specific failure beats an obscure one at first query.

Functions

This section is empty.

Types

type AuditEntry

type AuditEntry struct {
	ID         int64
	OccurredAt time.Time
	DeviceID   string // always set: withAudit runs inside requireDevice (D15)
	Operation  string // policy.Operation value: start, restart, stop, kill, delete
	Target     string // the reference as the device supplied it (D21)
	Outcome    string // one of the Outcome* constants below
	Detail     string // short fixed reason for the outcome when one adds information, else ""; never an Engine message or attacker-supplied text
}

AuditEntry is one mutating operation, attributed to the device that requested it.

type Device

type Device struct {
	ID         string
	Name       string
	PairedAt   time.Time
	LastSeenAt time.Time // zero when never seen
	RevokedAt  time.Time // zero when active
}

Device is one paired client. Certificates live in a separate table so a renewal is an INSERT, not a destructive UPDATE (see D6 in the Phase 2 plan).

func (Device) IsRevoked

func (d Device) IsRevoked() bool

IsRevoked reports whether the device's access has been withdrawn.

type Pruner

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

Pruner enforces audit retention on a fixed interval.

Phase 1 writes no audit rows, so this is a no-op against an empty table. It ships now anyway: retention configuration, the schema, and its enforcement are one story, and validating them together beats splitting them across phases.

func NewPruner

func NewPruner(store *Store, maxAge time.Duration, maxRows int, log *slog.Logger) *Pruner

NewPruner returns a Pruner applying the given retention bounds.

func (*Pruner) Run

func (p *Pruner) Run(ctx context.Context) error

Run prunes once immediately and then on each tick until ctx is cancelled, returning ctx.Err().

The immediate pass at the top matters because an agent restarted more often than the interval — a redeploy, a host reboot, a crash loop — would otherwise never enforce retention at all: a ticker that only fires after defaultPruneInterval never gets there before the process is replaced again. It runs synchronously before the loop rather than on a shortened first delay because runAll (cmd/devmon-agent/main.go) already starts this alongside the HTTP listener as an independent goroutine, so this pass overlaps with — and never blocks — the agent coming up. If ctx is already cancelled on entry, Run returns immediately without touching the store.

type Store

type Store struct {

	// FirstRun is true when the database file did not exist before Open.
	//
	// Phase 2 hangs the "loud on missing identity" check off this: once a
	// CA exists, a first run on a mount that should already hold one means the
	// operator lost their state directory, and the agent must say so rather than
	// silently minting a new identity that unpairs every device.
	FirstRun bool
	// contains filtered or unexported fields
}

Store is the durable state repository.

func Open

func Open(ctx context.Context, path string, log *slog.Logger) (*Store, error)

Open opens or creates the state store at path, verifies it is readable, and brings it to the current schema version.

func (*Store) AppendAudit

func (s *Store) AppendAudit(ctx context.Context, e AuditEntry) error

AppendAudit records one mutating operation. It is called once per mutating request, on every path including refusals (D14), so it must stay a single INSERT against the pool's one connection.

func (*Store) Close

func (s *Store) Close() error

Close releases the database handle.

func (*Store) CreateDevice

func (s *Store) CreateDevice(ctx context.Context, name string) (Device, error)

CreateDevice registers a new device and returns its record. The ID is 8 random bytes hex-encoded via crypto/rand — never math/rand, which is not safe for identifiers an attacker might try to predict or collide.

func (*Store) DeleteDevice

func (s *Store) DeleteDevice(ctx context.Context, id string) error

DeleteDevice removes a device and, via ON DELETE CASCADE, every certificate issued to it. It exists only for the pairing rollback path: when issuance fails after the device row was created, the orphan must not persist.

func (*Store) DeviceByCertSerial

func (s *Store) DeviceByCertSerial(ctx context.Context, serial string) (Device, error)

DeviceByCertSerial resolves the device that owns a certificate serial. It returns the device even when revoked, so the caller can distinguish "unknown serial" from "revoked device" and log precisely which happened.

func (*Store) IsDeviceRevoked added in v0.5.1

func (s *Store) IsDeviceRevoked(ctx context.Context, id string) (bool, error)

IsDeviceRevoked reports whether a device's access has been withdrawn. It exists for the per-tick revocation re-check that a long-lived SSE stream runs on every keepalive (GHSA-qrxm-qm54-xc44): revocation only takes effect on the next request, so a stream that stays open across a revocation must poll this to notice mid-stream and close itself.

It is deliberately narrower than DeviceByCertSerial: a single indexed lookup on the devices primary key, not a join through device_certs, because it runs periodically for every open stream against a pool capped at MaxOpenConns(1), where anything heavier would serialise reads behind writes for no benefit.

func (*Store) ListAudit

func (s *Store) ListAudit(ctx context.Context, limit int) ([]AuditEntry, error)

ListAudit returns the most recent entries first, capped at limit. It exists for the host-side CLI (D19); nothing on the HTTPS API calls it (D20).

func (*Store) ListDevices

func (s *Store) ListDevices(ctx context.Context) ([]Device, error)

ListDevices returns every registered device, most recently paired first.

func (*Store) MintPairingCode

func (s *Store) MintPairingCode(ctx context.Context, deviceName string, ttl time.Duration) (string, time.Time, error)

MintPairingCode generates a single-use pairing code for deviceName, valid for ttl, and persists only its hex SHA-256 (D4) — the plaintext is never written to disk and is unrecoverable once this call returns. The caller must show it to the operator once and never log it.

ttl must be positive: a non-positive value is a programming error at this layer, and MintPairingCode returns an error without minting anything.

func (*Store) PruneAudit

func (s *Store) PruneAudit(ctx context.Context, maxAge time.Duration, maxRows int) (int64, error)

PruneAudit enforces three retention bounds in one transaction and returns the number of rows removed: age, per-device fair share, and total row count, applied in that order.

The row cap alone bounds the table's size but not *whose* rows are evicted from it: without a fair-share pass, a single authenticated device flooding admitted mutations at the rate limit could push every other device's history — and even its own earlier activity — out of the table well before the age bound would ever trim it (see issue #81). The fair-share pass fixes that: it divides maxRows evenly across the distinct device buckets still present after the age pass, so one device can never evict another device's rows.

It does NOT guarantee that a device keeps everything it wrote. A device that exceeds its own share still loses its own oldest rows once it is over budget, because the table is finite by design — that backstop is what the final, unchanged row-count pass exists to enforce, and it must stay last so the fair-share pass can never weaken the hard disk-budget guarantee it gives operators on a small VPS. The share itself also shrinks as more distinct devices accumulate rows in the table — including unpaired or revoked devices whose historical rows remain — which is the intended fairness trade-off: more buckets, smaller slice per bucket.

func (*Store) PrunePairingCodes

func (s *Store) PrunePairingCodes(ctx context.Context) (int64, error)

PrunePairingCodes removes expired pairing codes and returns the number of rows deleted. It runs independently of whether the code was ever redeemed — an expired, unused code is just as unwanted as an expired, used one.

func (*Store) RecordDeviceCert

func (s *Store) RecordDeviceCert(ctx context.Context, deviceID, serial string, notBefore, notAfter time.Time) error

RecordDeviceCert stores a newly issued certificate against its owning device.

func (*Store) RedeemPairingCode

func (s *Store) RedeemPairingCode(ctx context.Context, code, deviceID string) (string, error)

RedeemPairingCode atomically marks code as used by deviceID and returns the device name it was minted for.

The single-use guarantee lives entirely in this one conditional UPDATE, not in a read-then-write pair: a SELECT followed by an UPDATE is a TOCTOU race that two simultaneous redemptions of a leaked code would win. The DSN's _txlock=immediate (store.go) plus the used_at IS NULL predicate is what makes this atomic. RETURNING folds the "read the name" and "mark it used" steps into a single statement, so there is no window between them for a second caller to observe the code as still unused.

func (*Store) RenameDevice

func (s *Store) RenameDevice(ctx context.Context, id, name string) error

RenameDevice updates a device's display name.

It exists for the pairing flow (see internal/httpapi/pair.go): a device row must exist before its pairing code can be redeemed, because RedeemPairingCode needs the device's ID, but the code — never the request — is the only legitimate source of the device's name. The row is created with a placeholder name and renamed once RedeemPairingCode returns the real one.

func (*Store) RevokeDevice

func (s *Store) RevokeDevice(ctx context.Context, id string) error

RevokeDevice withdraws a device's access. It is idempotent: revoking an already-revoked device succeeds without changing its revoked_at.

func (*Store) SchemaVersion

func (s *Store) SchemaVersion(ctx context.Context) (int, error)

SchemaVersion returns the schema version recorded in the store.

func (*Store) SupersedePriorCerts

func (s *Store) SupersedePriorCerts(ctx context.Context, deviceID, keepSerial string) error

SupersedePriorCerts marks every certificate the device holds, other than keepSerial, as superseded. It never deletes rows or shortens validity (D6): a superseded certificate stays valid until its own not_after, so a lost renewal response cannot strand the device.

func (*Store) TouchDevice

func (s *Store) TouchDevice(ctx context.Context, id string) error

TouchDevice records that a device was just seen, but only when the stored value is older than lastSeenResolution (D11), so a burst of requests costs at most one write per resolution window.

Jump to

Keyboard shortcuts

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