From 411f6fdf8c5a7a62b23d9b50fe65b635e85ea99c Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Mon, 7 Sep 2026 16:45:30 +1000 Subject: [PATCH] test(state-store): restart/recovery + single-owner-SQLite checks, document task-grant scoping (archie-core-8cda.4.7) Works through .4.7's remaining acceptance items: - TestStateStoreDataSurvivesRestart: a task written by one archie-state-store process is still there for a fresh process opened against the same archie.db path. - TestOpenStoresNeverOwnsTaskDB: the daemon/gateway composition path never populates b.st -- that field is reserved for the standalone binary, so archie.db always has exactly one owner. - Audited internal/webui and friends for direct internal/store use: only the narrow contract interfaces (TaskStore, CaptureStore, ...) are imported, never a concrete *store.Store -- already satisfied, no code change needed. - Updated docs/prds/state-store-contract.md's token lifecycle and payload-limits sections to describe what's actually implemented now (RegisterTaskGrant/RevokeTaskGrant, per-RPC scoping, the streaming capture RPCs) instead of the pre-.4.3 in-process-listener language. - Ran the affected packages under -race; clean. Left open, for Sam to decide rather than assume: archie-state-store has no Dockerfile/CI build and isn't in RELEASING.md's two-component split (tools/release.sh only tracks cmd/archied and cmd/archie-agent). Given it's currently a native-binary/systemd deployment (deployments/*.toml), this may be intentional -- flagging rather than inventing release infra for a third binary unasked. --- docs/prds/state-store-contract.md | 29 +++++++++--- internal/app/archied/state_store_test.go | 57 ++++++++++++++++++++++++ 2 files changed, 80 insertions(+), 6 deletions(-) diff --git a/docs/prds/state-store-contract.md b/docs/prds/state-store-contract.md index 00ad8a305..762dee8e5 100644 --- a/docs/prds/state-store-contract.md +++ b/docs/prds/state-store-contract.md @@ -409,7 +409,12 @@ is why it is decomposed; proto services bypass the cap (like `ChatContract`). **Payload caps:** - Capture body: `defaultCaptureMaxBodyBytes = 256 KiB` (may reduce further; the wire message - must not exceed gRPC's default 4 MiB receive limit for a single capture). + must not exceed gRPC's default 4 MiB receive limit for a single capture). A single capture + fits, but a *batch* of them did not: the caller-side cap of up to 100 captures at 256 KiB each + could exceed 4 MiB in one unary `ListCaptures`/`ListUndispatchedCaptures` response. `.4.7` adds + `StreamCaptures`/`StreamUndispatchedCaptures` (server-streaming, one capture per message) as + the path both `staterpc.Client` methods actually call; the original unary RPCs stay defined, + unmodified and deprecated, only so `buf breaking` protects an in-flight rolling deploy. - Task `detail`/`park_reason`/event `Detail`: 4000-char hard cap (`clip(s, 4000)`). **Retention (stays server-side in the store; the wire does not carry pruning decisions):** @@ -459,16 +464,28 @@ stated explicitly rather than left implicit. confirmation caveat. The NATS-KV discovery fallback supplies endpoints but does not add transport security; that stays the operator's responsibility. -### Token lifecycle (rev. 2c) +### Token lifecycle (rev. 2c; scoping added in `.4.7`) - **Generation:** the daemon generates a per-task bearer token when it acquires the container (or per incumbence) and injects it via `containerEnv` as `STATE_STORE_TOKEN`. A single token may cover a task's container lifetime. +- **Registration (`.4.7`, post-standalone-cutover):** the State Store is now its own process + (`.4.3`/`.4.6`), so the daemon can no longer just hold an in-process issued-token set for the + server to check — it registers the token at the remote authority via the + `RegisterTaskGrant`/`RevokeTaskGrant` RPCs (`staterpc.GrantIssuer`, `daemon.StateStoreGrantIssuer`), + admin-token-authenticated calls a task-scoped token itself can never make. - **Lifetime:** tied to the task + container grace period; rotated on a new container acquisition - for the same task; a token for a released container is invalidated. -- **Validation:** a gRPC interceptor on the State Store server validates the token against the - daemon's issued-token set; missing/unknown/expired → `codes.Unauthenticated`. The token is - carried in gRPC metadata, never in a URL. + for the same task; a token for a released container is invalidated (`RevokeTaskGrant`, deferred + alongside `ContainerPool.Release`). An unrevoked grant still expires server-side (bounded by + `RegisterTaskGrantRequest.lifetime_seconds`, capped at 7 days) so a daemon crash before revoke + cannot leave a grant valid indefinitely. +- **Validation and scope (`.4.7`):** a gRPC interceptor (`staterpc.TaskGrants.UnaryInterceptor`) + validates the token against the State Store's own issued-grant set; missing/unknown/expired → + `codes.Unauthenticated`. Unlike the daemon's own administrative token (full access to all ~40 + RPCs), a task-scoped grant additionally authorizes only `Update`/`Transition`/`InsertEvent` on + its own task ID — every other RPC, including the streaming capture surface and + `RegisterTaskGrant`/`RevokeTaskGrant` themselves, is `codes.PermissionDenied` for a task-scoped + caller. The token is carried in gRPC metadata, never in a URL. ### Fail-closed on non-loopback (rev. 2c) diff --git a/internal/app/archied/state_store_test.go b/internal/app/archied/state_store_test.go index 0a30b456d..ce03dff49 100644 --- a/internal/app/archied/state_store_test.go +++ b/internal/app/archied/state_store_test.go @@ -9,6 +9,7 @@ import ( "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" + "github.com/samcharles93/archie-core/internal/config" pb "github.com/samcharles93/archie-core/internal/contracts/state/v1" "github.com/samcharles93/archie-core/internal/infrastructure/staterpc" "github.com/samcharles93/archie-core/internal/store" @@ -144,3 +145,59 @@ func TestServeStateStoreServesContract(t *testing.T) { t.Fatal("serveStateStore did not return after cancel") } } + +// TestStateStoreDataSurvivesRestart is the .4.7 restart/recovery check: a +// task written by one archie-state-store process must still be there for a +// fresh process opening the same archie.db path, proving b.openStateStore +// (RunStateStore's own opener, not a test-only shortcut) round-trips through +// the file rather than an in-memory or per-process store. +func TestStateStoreDataSurvivesRestart(t *testing.T) { + cfg := config.Config{DBPath: filepath.Join(t.TempDir(), "archie")} + + first := newBootstrap() + first.cfg = cfg + if err := first.openStateStore(t.Context()); err != nil { + t.Fatalf("first openStateStore: %v", err) + } + task, err := first.st.EnqueueChatTask(t.Context(), "acme", "widget", "restart check", "body", "implement", "") + if err != nil { + t.Fatalf("EnqueueChatTask: %v", err) + } + first.cleanup() // closes the SQLite handle, simulating process exit + + second := newBootstrap() + second.cfg = cfg + if err := second.openStateStore(t.Context()); err != nil { + t.Fatalf("second openStateStore: %v", err) + } + defer second.cleanup() + + got, err := second.st.TaskByID(t.Context(), task.ID) + if err != nil { + t.Fatalf("TaskByID after restart: %v", err) + } + if got == nil { + t.Fatal("task did not survive a restart against the same db path") + } + if got.Title != task.Title { + t.Fatalf("restarted task title = %q, want %q", got.Title, task.Title) + } +} + +// TestOpenStoresNeverOwnsTaskDB is the .4.7 single-owner-SQLite assertion: +// the daemon/gateway composition path (openStores, run by Run/RunGateway) +// must never populate b.st -- that field is reserved for the standalone +// archie-state-store binary's openStateStore (state_store.go). Regressing +// this would mean archie.db is opened by two processes at once. +func TestOpenStoresNeverOwnsTaskDB(t *testing.T) { + b := newBootstrap() + b.cfg = config.Config{DBPath: filepath.Join(t.TempDir(), "archie")} + if err := b.openStores(t.Context()); err != nil { + t.Fatalf("openStores: %v", err) + } + defer b.cleanup() + + if b.st != nil { + t.Fatal("openStores populated b.st -- the daemon/gateway path must not own archie.db directly (docs/prds/state-store-contract.md §12 step 7)") + } +}