Phase 8: overrides (shared keycode + versioned admin lock/unlock/grant API)

Build on Phases 1–7. Adds the two override paths from AGENTS.md §4 FR-10/FR-11:
the shared device keycode and the versioned admin HTTP API the separate Kotlin
admin app will call.

- store: migration 004 adds state.grant_until and a settings table. New
  overrides.go records every override in `overrides` and verifies the shared
  keycode (bcrypt; one code for every device, §10 rule 3). ExpireLocks also
  clears an expired grant, and NextScheduleBoundary includes the grant end so a
  device re-locks on time.
- effective state: a grant unlocks a device inside a schedule window; a manual
  lock clears a grant and a grant clears a manual lock. The retained config
  payload gains grant_until (additive, v stays 1).
- web: /api/v1/admin/... (list, state, lock, unlock, grant) guarded by
  CONTROL_ADMIN_API_TOKEN, separate from the session login, plus the on-device
  keycode endpoint POST /api/v1/device/override with per-address throttling.
  A state change is published retained before the API responds.
- cmd/control: `keycode` subcommand and start-up seeding from
  CONTROL_DEVICE_KEYCODE_HASH.
- deploy/verify-phase8.sh + `make verify-phase8` prove the definition of done:
  an API lock reaches a real broker subscriber in well under a second.
- Version 0.6.0-phase8 (compose, Makefile, docs).

Measured on .13: the lock reached the TLS broker subscriber in 7 ms (handler
1 ms, request to retained publish accepted).

Tests: go vet ./... and go test -count=1 ./... pass in golang:1.25-alpine.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
2026-10-13 16:27:46 +11:00
parent b58993d994
commit 4f233a8012
19 changed files with 1833 additions and 67 deletions

View File

@@ -41,9 +41,13 @@ type Device struct {
UpdatedAt time.Time
// Desired state, from the state table.
Locked bool
Until *time.Time
StateAt time.Time
Locked bool
Until *time.Time
// GrantUntil is a time-limited exemption (Phase 8): while it is in the
// future the device is unlocked even during a schedule window. It is nil
// when no grant is active or one has been cleared.
GrantUntil *time.Time
StateAt time.Time
}
// AuditEntry is one row of the append-only audit log (FR-15).
@@ -61,7 +65,7 @@ type AuditEntry struct {
const selectDevice = `
SELECT d.id, d.name, d.child, d.platform, d.topic, d.online, d.last_seen,
d.created_at, d.updated_at,
COALESCE(s.locked, 0), s.until, s.updated_at
COALESCE(s.locked, 0), s.until, s.grant_until, s.updated_at
FROM devices d
LEFT JOIN state s ON s.device_id = d.id`
@@ -69,21 +73,22 @@ func scanDevice(row interface {
Scan(dest ...any) error
}) (*Device, error) {
var (
dev Device
online int
lastSeen, until, stateAt sql.NullString
createdAt, updatedAt sql.NullString
dev Device
online int
lastSeen, until, grantUntil sql.NullString
createdAt, updatedAt, stateAt sql.NullString
)
if err := row.Scan(
&dev.ID, &dev.Name, &dev.Child, &dev.Platform, &dev.Topic, &online,
&lastSeen, &createdAt, &updatedAt,
&dev.Locked, &until, &stateAt,
&dev.Locked, &until, &grantUntil, &stateAt,
); err != nil {
return nil, err
}
dev.Online = online != 0
dev.LastSeen = parseTimePtr(lastSeen)
dev.Until = parseTimePtr(until)
dev.GrantUntil = parseTimePtr(grantUntil)
if t := parseTime(createdAt.String); !t.IsZero() {
dev.CreatedAt = t
}
@@ -268,11 +273,12 @@ func (s *Store) SetDeviceLock(ctx context.Context, id int64, locked bool, until
}
if _, err := tx.ExecContext(ctx, `
INSERT INTO state (device_id, locked, until, updated_at)
VALUES (?, ?, ?, datetime('now'))
INSERT INTO state (device_id, locked, until, grant_until, updated_at)
VALUES (?, ?, ?, NULL, datetime('now'))
ON CONFLICT(device_id) DO UPDATE SET
locked = excluded.locked,
until = excluded.until,
grant_until = NULL,
updated_at = datetime('now')`,
id, boolToInt(locked), untilArg); err != nil {
return nil, fmt.Errorf("set state: %w", err)
@@ -280,15 +286,18 @@ func (s *Store) SetDeviceLock(ctx context.Context, id int64, locked bool, until
if err := insertAudit(ctx, tx, actor, action, &id, detail); err != nil {
return nil, err
}
if err := insertOverride(ctx, tx, id, actor, action, until); err != nil {
return nil, err
}
if err := tx.Commit(); err != nil {
return nil, fmt.Errorf("commit state: %w", err)
}
return s.GetDevice(ctx, id)
}
// ExpireLocks unlocks every device whose timed lock has passed and appends one
// audit entry per device. It returns how many locks it cleared. It is safe to
// call often.
// ExpireLocks unlocks every device whose timed lock has passed and clears every
// expired grant, appending one audit entry per device whose lock lifted. It
// returns how many locks it cleared. It is safe to call often.
func (s *Store) ExpireLocks(ctx context.Context) (int, error) {
now := time.Now().UTC().Format(time.RFC3339)
rows, err := s.db.QueryContext(ctx,
@@ -316,6 +325,14 @@ func (s *Store) ExpireLocks(ctx context.Context) (int, error) {
return 0, err
}
}
// A grant is silent: it changes no audit row and needs no device callback,
// because EffectiveState already ignores a past grant. Clearing it keeps the
// stored state tidy and the API response honest.
if _, err := s.db.ExecContext(ctx, `
UPDATE state SET grant_until = NULL, updated_at = datetime('now')
WHERE grant_until IS NOT NULL AND grant_until <= ?`, now); err != nil {
return len(ids), fmt.Errorf("expire grants: %w", err)
}
return len(ids), nil
}

View File

@@ -0,0 +1,20 @@
-- Migration 004 — Phase 8. Overrides (AGENTS.md §7, §11 Phase 8).
--
-- The shared device keycode lives in `settings` as a bcrypt hash under the key
-- 'device_keycode_hash'. It is never stored or logged in plaintext. The
-- key/value table also gives later phases a place for small settings without a
-- new migration.
--
-- grant_until is a time-limited exemption: while it is in the future the device
-- is unlocked even when a weekly window would otherwise block it. It is a
-- separate column from the manual lock's `until` so "grant 30 minutes" and
-- "lock until I unlock" cannot fight over the same value. A manual lock clears
-- a grant; a grant clears a manual lock.
ALTER TABLE state ADD COLUMN grant_until TEXT;
CREATE TABLE IF NOT EXISTS settings (
key TEXT PRIMARY KEY,
value TEXT NOT NULL,
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);

233
internal/store/overrides.go Normal file
View File

@@ -0,0 +1,233 @@
// Overrides and the shared device keycode (AGENTS.md §4 FR-10, §7 overrides,
// §10 rule 3, §11 Phase 8).
//
// An override is a deliberate change to a device's desired state: a lock, an
// unlock, or a grant of time. Every override is written to the `overrides`
// table and, through the caller, to the append-only `audit` log (FR-15). The
// state table holds only the current value; `overrides` is the history.
//
// The device keycode is a single code shared by every device (§10 rule 3). It
// is stored only as a bcrypt hash in `settings`, is seeded from the environment
// at start-up, and can be changed with `control keycode` (or, later, from the
// dashboard).
package store
import (
"context"
"database/sql"
"errors"
"fmt"
"strings"
"time"
"golang.org/x/crypto/bcrypt"
)
// keycodeSettingKey is the settings row that holds the shared device keycode.
const keycodeSettingKey = "device_keycode_hash"
// ErrNoKeycode is returned when no device keycode has been set.
var ErrNoKeycode = errors.New("device keycode is not set")
// Override is one row of the override history.
type Override struct {
ID int64
DeviceID int64
Actor string
Action string
Until *time.Time
CreatedAt time.Time
}
// insertOverride appends one override row using the given executor, so it can
// be written atomically with the state change it records.
func insertOverride(ctx context.Context, ex interface {
ExecContext(context.Context, string, ...any) (sql.Result, error)
}, deviceID int64, actor, action string, until *time.Time) error {
var untilArg any
if until != nil {
untilArg = until.UTC().Format(time.RFC3339)
}
if _, err := ex.ExecContext(ctx,
`INSERT INTO overrides (device_id, actor, action, until) VALUES (?, ?, ?, ?)`,
deviceID, actor, action, untilArg); err != nil {
return fmt.Errorf("override insert: %w", err)
}
return nil
}
// ListOverrides returns a device's override history, newest first.
func (s *Store) ListOverrides(ctx context.Context, deviceID int64, limit int) ([]Override, error) {
if limit <= 0 || limit > 500 {
limit = 50
}
rows, err := s.db.QueryContext(ctx, `
SELECT id, device_id, actor, action, until, created_at
FROM overrides WHERE device_id = ?
ORDER BY id DESC LIMIT ?`, deviceID, limit)
if err != nil {
return nil, fmt.Errorf("list overrides: %w", err)
}
defer rows.Close()
out := make([]Override, 0, limit)
for rows.Next() {
var (
o Override
until sql.NullString
created sql.NullString
)
if err := rows.Scan(&o.ID, &o.DeviceID, &o.Actor, &o.Action, &until, &created); err != nil {
return nil, fmt.Errorf("scan override: %w", err)
}
o.Until = parseTimePtr(until)
o.CreatedAt = parseTime(created.String)
out = append(out, o)
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("list overrides: %w", err)
}
return out, nil
}
// SetDeviceGrant gives a device a time-limited exemption: it is unlocked until
// `until`, even if a weekly window is active. It clears any manual lock, writes
// one override row and one audit row in the same transaction, and returns the
// fresh device. `until` must be in the future.
func (s *Store) SetDeviceGrant(ctx context.Context, id int64, until time.Time, actor, action string) (*Device, error) {
if until.IsZero() {
return nil, errors.New("grant needs an end time")
}
until = until.UTC()
if !until.After(time.Now()) {
return nil, errors.New("grant end time must be in the future")
}
if _, err := s.GetDevice(ctx, id); err != nil {
return nil, err
}
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return nil, fmt.Errorf("set grant: %w", err)
}
defer func() { _ = tx.Rollback() }()
if _, err := tx.ExecContext(ctx, `
INSERT INTO state (device_id, locked, until, grant_until, updated_at)
VALUES (?, 0, NULL, ?, datetime('now'))
ON CONFLICT(device_id) DO UPDATE SET
locked = 0,
until = NULL,
grant_until = excluded.grant_until,
updated_at = datetime('now')`,
id, until.Format(time.RFC3339)); err != nil {
return nil, fmt.Errorf("set grant: %w", err)
}
if err := insertAudit(ctx, tx, actor, action, &id,
"granted time until "+until.Format(time.RFC3339)); err != nil {
return nil, err
}
if err := insertOverride(ctx, tx, id, actor, action, &until); err != nil {
return nil, err
}
if err := tx.Commit(); err != nil {
return nil, fmt.Errorf("commit grant: %w", err)
}
return s.GetDevice(ctx, id)
}
// ---------- device keycode ----------
// SetKeycodeHash stores the bcrypt hash of the shared device keycode and
// appends one audit row. The hash is validated first, so a corrupt value never
// replaces a working code.
func (s *Store) SetKeycodeHash(ctx context.Context, hash, actor string) error {
if _, err := bcrypt.Cost([]byte(hash)); err != nil {
return fmt.Errorf("device keycode hash is not a valid bcrypt hash: %w", err)
}
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return fmt.Errorf("set keycode: %w", err)
}
defer func() { _ = tx.Rollback() }()
if _, err := tx.ExecContext(ctx, `
INSERT INTO settings (key, value, updated_at) VALUES (?, ?, datetime('now'))
ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = datetime('now')`,
keycodeSettingKey, hash); err != nil {
return fmt.Errorf("set keycode: %w", err)
}
if err := insertAudit(ctx, tx, actor, "keycode.updated", nil, "shared device keycode changed"); err != nil {
return err
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("commit keycode: %w", err)
}
return nil
}
// KeycodeHash returns the stored bcrypt hash, or ErrNoKeycode.
func (s *Store) KeycodeHash(ctx context.Context) (string, error) {
var value string
err := s.db.QueryRowContext(ctx, `SELECT value FROM settings WHERE key = ?`, keycodeSettingKey).Scan(&value)
if errors.Is(err, sql.ErrNoRows) || value == "" {
return "", ErrNoKeycode
}
if err != nil {
return "", fmt.Errorf("keycode hash: %w", err)
}
return value, nil
}
// VerifyKeycode reports whether code matches the stored shared keycode. A
// missing or invalid stored hash never matches, so a broken settings row cannot
// unlock a device by accident.
func (s *Store) VerifyKeycode(ctx context.Context, code string) bool {
code = strings.TrimSpace(code)
if code == "" {
return false
}
hash, err := s.KeycodeHash(ctx)
if err != nil {
return false
}
return bcrypt.CompareHashAndPassword([]byte(hash), []byte(code)) == nil
}
// SeedKeycodeHash stores hash only when no code is stored yet. The Control
// Service calls it at start-up so CONTROL_DEVICE_KEYCODE_HASH in environment.d
// is the first-run source of the code. Once a code exists, the settings row is
// authoritative: a restart never overwrites a code changed with `control
// keycode`, so a runtime change is durable. It returns whether it stored a code.
func (s *Store) SeedKeycodeHash(ctx context.Context, hash string) (bool, error) {
hash = strings.TrimSpace(hash)
if hash == "" {
return false, nil
}
if _, err := bcrypt.Cost([]byte(hash)); err != nil {
return false, fmt.Errorf("CONTROL_DEVICE_KEYCODE_HASH is not a valid bcrypt hash: %w", err)
}
if _, err := s.KeycodeHash(ctx); err == nil {
return false, nil // already set; never overwrite at start-up
} else if !errors.Is(err, ErrNoKeycode) {
return false, err
}
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return false, fmt.Errorf("seed keycode: %w", err)
}
defer func() { _ = tx.Rollback() }()
if _, err := tx.ExecContext(ctx, `
INSERT INTO settings (key, value, updated_at) VALUES (?, ?, datetime('now'))
ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = datetime('now')`,
keycodeSettingKey, hash); err != nil {
return false, fmt.Errorf("seed keycode: %w", err)
}
if err := insertAudit(ctx, tx, "system", "keycode.updated", nil, "seeded from CONTROL_DEVICE_KEYCODE_HASH"); err != nil {
return false, err
}
if err := tx.Commit(); err != nil {
return false, fmt.Errorf("commit seeded keycode: %w", err)
}
return true, nil
}

View File

@@ -0,0 +1,213 @@
package store
import (
"context"
"errors"
"testing"
"time"
"golang.org/x/crypto/bcrypt"
)
// TestGrantOverridesScheduleAndReLocks is the Phase 8 grant contract: a grant
// unlocks a device inside an active schedule window, and the window re-applies
// the moment the grant ends.
func TestGrantOverridesScheduleAndReLocks(t *testing.T) {
ctx := context.Background()
st := testStore(t)
dev := mustCreateDevice(t, st, "Harry Phone", "Harry", "android")
now := time.Date(2026, 10, 13, 20, 30, 0, 0, time.UTC) // Tuesday
if err := st.ReplaceSchedules(ctx, dev.ID, []ScheduleWindow{
{Weekday: weekdayMon0(now), Start: "19:00", End: "21:00"},
}, "sam"); err != nil {
t.Fatalf("ReplaceSchedules: %v", err)
}
// Before the grant the window blocks the device.
eff, err := st.EffectiveState(ctx, *dev, now)
if err != nil {
t.Fatalf("EffectiveState: %v", err)
}
if !eff.Locked || eff.Reason != "schedule" {
t.Fatalf("before grant: %+v, want locked by schedule", eff)
}
// Grant time: the device is unlocked even though the window is active.
grantUntil := now.Add(15 * time.Minute)
granted, err := st.SetDeviceGrant(ctx, dev.ID, grantUntil, "admin-api", "override.granted")
if err != nil {
t.Fatalf("SetDeviceGrant: %v", err)
}
eff, err = st.EffectiveState(ctx, *granted, now)
if err != nil {
t.Fatalf("EffectiveState: %v", err)
}
if eff.Locked || eff.Reason != "grant" {
t.Fatalf("during grant: %+v, want unlocked by grant", eff)
}
if eff.GrantUntil == nil || !eff.GrantUntil.Equal(grantUntil) {
t.Errorf("grant until = %v, want %v", eff.GrantUntil, grantUntil)
}
// The grant end is a republish boundary, so the device re-locks on time.
next, err := st.NextScheduleBoundary(ctx, now)
if err != nil {
t.Fatalf("NextScheduleBoundary: %v", err)
}
if next == nil || !next.Equal(grantUntil) {
t.Errorf("next boundary = %v, want the grant end %v", next, grantUntil)
}
// After the grant ends the schedule applies again.
eff, err = st.EffectiveState(ctx, *granted, grantUntil.Add(time.Minute))
if err != nil {
t.Fatalf("EffectiveState: %v", err)
}
if !eff.Locked || eff.Reason != "schedule" {
t.Fatalf("after grant: %+v, want locked by schedule again", eff)
}
// The override history holds the grant.
overrides, err := st.ListOverrides(ctx, dev.ID, 10)
if err != nil {
t.Fatalf("ListOverrides: %v", err)
}
if len(overrides) != 1 || overrides[0].Action != "override.granted" || overrides[0].Actor != "admin-api" {
t.Fatalf("overrides = %+v, want one grant", overrides)
}
if overrides[0].Until == nil || !overrides[0].Until.Equal(grantUntil) {
t.Errorf("override until = %v, want %v", overrides[0].Until, grantUntil)
}
}
func TestLockClearsGrant(t *testing.T) {
ctx := context.Background()
st := testStore(t)
dev := mustCreateDevice(t, st, "Finn PC", "Finn", "windows")
until := time.Now().Add(time.Hour).UTC()
dev, err := st.SetDeviceGrant(ctx, dev.ID, until, "admin-api", "override.granted")
if err != nil {
t.Fatalf("SetDeviceGrant: %v", err)
}
if dev.GrantUntil == nil {
t.Fatal("grant was not stored")
}
dev, err = st.SetDeviceLock(ctx, dev.ID, true, nil, "admin-api", "state.locked")
if err != nil {
t.Fatalf("SetDeviceLock: %v", err)
}
if !dev.Locked || dev.GrantUntil != nil {
t.Fatalf("after lock: locked=%v grant=%v, want locked with no grant", dev.Locked, dev.GrantUntil)
}
// Both actions are in the override history.
overrides, err := st.ListOverrides(ctx, dev.ID, 10)
if err != nil {
t.Fatalf("ListOverrides: %v", err)
}
if len(overrides) != 2 {
t.Fatalf("overrides = %d, want 2", len(overrides))
}
}
func TestExpireClearsGrant(t *testing.T) {
ctx := context.Background()
st := testStore(t)
dev := mustCreateDevice(t, st, "Harry Phone", "Harry", "android")
// Set an already-expired grant directly: SetDeviceGrant refuses the past,
// which is the right guard for callers, but the cleanup path must still work.
past := time.Now().Add(-time.Minute).UTC().Format(time.RFC3339)
if _, err := st.DB().ExecContext(ctx,
`UPDATE state SET grant_until = ? WHERE device_id = ?`, past, dev.ID); err != nil {
t.Fatalf("seed past grant: %v", err)
}
if _, err := st.ExpireLocks(ctx); err != nil {
t.Fatalf("ExpireLocks: %v", err)
}
got, err := st.GetDevice(ctx, dev.ID)
if err != nil {
t.Fatalf("GetDevice: %v", err)
}
if got.GrantUntil != nil {
t.Errorf("grant_until = %v after expiry, want nil", got.GrantUntil)
}
}
func TestSetDeviceGrantRejectsPastAndMissing(t *testing.T) {
ctx := context.Background()
st := testStore(t)
dev := mustCreateDevice(t, st, "Harry Phone", "Harry", "android")
if _, err := st.SetDeviceGrant(ctx, dev.ID, time.Now().Add(-time.Minute), "admin-api", "override.granted"); err == nil {
t.Error("expected a past grant to be refused")
}
if _, err := st.SetDeviceGrant(ctx, 999, time.Now().Add(time.Hour), "admin-api", "override.granted"); !errors.Is(err, ErrNotFound) {
t.Errorf("missing device: err = %v, want ErrNotFound", err)
}
}
func TestDeviceKeycode(t *testing.T) {
ctx := context.Background()
st := testStore(t)
if _, err := st.KeycodeHash(ctx); !errors.Is(err, ErrNoKeycode) {
t.Fatalf("KeycodeHash with none: err = %v, want ErrNoKeycode", err)
}
if st.VerifyKeycode(ctx, "1234") {
t.Error("an unset keycode must never verify")
}
hash, err := bcrypt.GenerateFromPassword([]byte("2468"), bcrypt.MinCost)
if err != nil {
t.Fatalf("bcrypt: %v", err)
}
if err := st.SetKeycodeHash(ctx, string(hash), "admin"); err != nil {
t.Fatalf("SetKeycodeHash: %v", err)
}
if !st.VerifyKeycode(ctx, "2468") {
t.Error("correct keycode did not verify")
}
if st.VerifyKeycode(ctx, "8642") {
t.Error("wrong keycode verified")
}
if st.VerifyKeycode(ctx, "") {
t.Error("empty keycode verified")
}
// Invalid hashes are refused and do not replace the working one.
if err := st.SetKeycodeHash(ctx, "not-a-hash", "admin"); err == nil {
t.Error("expected an invalid hash to be refused")
}
if !st.VerifyKeycode(ctx, "2468") {
t.Error("the working keycode was replaced by an invalid one")
}
// Seeding never overwrites an existing code: a runtime change made with
// `control keycode` survives a restart even if the environment still holds
// the old value.
other, _ := bcrypt.GenerateFromPassword([]byte("1357"), bcrypt.MinCost)
if seeded, err := st.SeedKeycodeHash(ctx, string(other)); err != nil || seeded {
t.Fatalf("SeedKeycodeHash over existing = (%v, %v), want (false, nil)", seeded, err)
}
if !st.VerifyKeycode(ctx, "2468") || st.VerifyKeycode(ctx, "1357") {
t.Error("seeding must not overwrite a configured keycode")
}
// A fresh store takes the environment value once.
fresh := testStore(t)
seeded, err := fresh.SeedKeycodeHash(ctx, string(other))
if err != nil || !seeded {
t.Fatalf("SeedKeycodeHash on empty store = (%v, %v), want (true, nil)", seeded, err)
}
if !fresh.VerifyKeycode(ctx, "1357") {
t.Error("seeded keycode did not verify")
}
if seeded, err := fresh.SeedKeycodeHash(ctx, string(other)); err != nil || seeded {
t.Errorf("SeedKeycodeHash repeat = (%v, %v), want (false, nil)", seeded, err)
}
}

View File

@@ -53,9 +53,13 @@ type EffectiveState struct {
DeviceID int64
Locked bool
Until *time.Time
// Reason is "manual" (a lock from the dashboard), "schedule" (an active
// weekly window) or "" (not blocked).
// Reason is "manual" (a lock from the dashboard or the admin API),
// "schedule" (an active weekly window), "grant" (a time-limited exemption)
// or "" (not blocked).
Reason string
// GrantUntil is set when a grant is active: the device is unlocked, and a
// schedule window must not block it before this instant (Phase 8).
GrantUntil *time.Time
// Allow and Block are the configured list values, always non-nil.
Allow []string
Block []string
@@ -279,8 +283,13 @@ func atClock(now time.Time, minutes int) time.Time {
}
// EffectiveState computes the desired state for one device at now: a manual
// lock, an active schedule window, or neither. While blocked, the configured
// allowlist is honoured: the device blocks Block except Allow (FR-4).
// lock, an active schedule window, a time-limited grant, or none of them.
// While blocked, the configured allowlist is honoured: the device blocks Block
// except Allow (FR-4).
//
// A grant wins over a schedule window but not over a manual lock; the write
// paths keep the two mutually exclusive (a lock clears a grant, a grant clears
// a lock), so the order below only matters for hand-edited data.
//
// A manual lock with no end time ("until I unlock") never lifts, so it wins over
// a schedule end. Otherwise Until is the latest of the manual end and the
@@ -314,6 +323,10 @@ func (s *Store) EffectiveState(ctx context.Context, dev Device, now time.Time) (
if dev.Until != nil && schedUntil != nil && schedUntil.After(*dev.Until) {
eff.Until = schedUntil
}
case dev.GrantUntil != nil && dev.GrantUntil.After(now):
eff.Locked = false
eff.Reason = "grant"
eff.GrantUntil = dev.GrantUntil
case scheduled:
eff.Locked = true
eff.Reason = "schedule"
@@ -346,26 +359,30 @@ func (s *Store) NextScheduleBoundary(ctx context.Context, now time.Time) (*time.
}
best := NextWindowBoundary(schedules, now)
// A manual lock that expires is a boundary too, so the loop lifts it from
// the device promptly instead of waiting for the next interval.
// A manual lock that expires and a grant that ends are boundaries too, so
// the loop lifts or re-locks from the device promptly instead of waiting for
// the next interval. A grant end matters because the device may be unlocked
// only because of the grant: when it passes, an active window must re-lock.
lockRows, err := s.db.QueryContext(ctx,
`SELECT until FROM state WHERE locked = 1 AND until IS NOT NULL`)
`SELECT until, grant_until FROM state WHERE (locked = 1 AND until IS NOT NULL) OR grant_until IS NOT NULL`)
if err != nil {
return nil, fmt.Errorf("next lock boundary: %w", err)
}
defer lockRows.Close()
for lockRows.Next() {
var until sql.NullString
if err := lockRows.Scan(&until); err != nil {
var until, grantUntil sql.NullString
if err := lockRows.Scan(&until, &grantUntil); err != nil {
return nil, fmt.Errorf("scan lock until: %w", err)
}
t := parseTime(until.String)
if t.IsZero() || !t.After(now) {
continue
}
if best == nil || t.Before(*best) {
c := t
best = &c
for _, ns := range []sql.NullString{until, grantUntil} {
t := parseTime(ns.String)
if t.IsZero() || !t.After(now) {
continue
}
if best == nil || t.Before(*best) {
c := t
best = &c
}
}
}
if err := lockRows.Err(); err != nil {