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
- Variables
- type AuditEntry
- type Device
- type Pruner
- type Store
- func (s *Store) AppendAudit(ctx context.Context, e AuditEntry) error
- func (s *Store) Close() error
- func (s *Store) CreateDevice(ctx context.Context, name string) (Device, error)
- func (s *Store) DeleteDevice(ctx context.Context, id string) error
- func (s *Store) DeviceByCertSerial(ctx context.Context, serial string) (Device, error)
- func (s *Store) IsDeviceRevoked(ctx context.Context, id string) (bool, error)
- func (s *Store) ListAudit(ctx context.Context, limit int) ([]AuditEntry, error)
- func (s *Store) ListDevices(ctx context.Context) ([]Device, error)
- func (s *Store) MintPairingCode(ctx context.Context, deviceName string) (string, time.Time, error)
- func (s *Store) PruneAudit(ctx context.Context, maxAge time.Duration, maxRows int) (int64, error)
- func (s *Store) PrunePairingCodes(ctx context.Context) (int64, error)
- func (s *Store) RecordDeviceCert(ctx context.Context, deviceID, serial string, notBefore, notAfter time.Time) error
- func (s *Store) RedeemPairingCode(ctx context.Context, code, deviceID string) (string, error)
- func (s *Store) RenameDevice(ctx context.Context, id, name string) error
- func (s *Store) RevokeDevice(ctx context.Context, id string) error
- func (s *Store) SchemaVersion(ctx context.Context) (int, error)
- func (s *Store) SupersedePriorCerts(ctx context.Context, deviceID, keepSerial string) error
- func (s *Store) TouchDevice(ctx context.Context, id string) error
Constants ¶
const ( OutcomeSuccess = "success" OutcomeDeniedPolicy = "denied_policy" OutcomeDeniedSelf = "denied_self" OutcomeNotFound = "not_found" OutcomeInvalid = "invalid" OutcomeConflict = "conflict" 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" )
Variables ¶
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).
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 (*Pruner) Run ¶
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 ¶
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) CreateDevice ¶
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 ¶
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 ¶
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
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 ¶
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 ¶
ListDevices returns every registered device, most recently paired first.
func (*Store) MintPairingCode ¶
MintPairingCode generates a single-use pairing code for deviceName 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.
func (*Store) PruneAudit ¶
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 ¶
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 ¶
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 ¶
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 ¶
RevokeDevice withdraws a device's access. It is idempotent: revoking an already-revoked device succeeds without changing its revoked_at.
func (*Store) SchemaVersion ¶
SchemaVersion returns the schema version recorded in the store.
func (*Store) SupersedePriorCerts ¶
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.