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) 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" )
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: the PRD asks for a loud, early, specific failure rather than 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 // resolved container ID, or a short reason; never an Engine message
}
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.
type Store ¶
type Store struct {
// FirstRun is true when the database file did not exist before Open.
//
// Phase 2 hangs the PRD's "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) 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 both retention bounds in one transaction and returns the number of rows removed.
Age and row count are applied together, not as alternatives: whichever bites first is the one that limits growth, which is what "bounded by both age and size" means in the PRD.
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.