diff --git a/internal/app/archied/bootstrap.go b/internal/app/archied/bootstrap.go index 4ec5556cd..c65a2fa57 100644 --- a/internal/app/archied/bootstrap.go +++ b/internal/app/archied/bootstrap.go @@ -129,10 +129,8 @@ type boot struct { // accessChain is the daemon's policy engine, built once from the stored // policies (openAccessChain); accessProblems is what the readiness // surface reports. Both are nil when no policy store is wired. - accessChain access.Authorizer - accessPrincipals access.PrincipalSource - accessDenials access.DenialStore - accessProblems []infraaccess.Problem + accessChain access.Authorizer + accessProblems []infraaccess.Problem // stateStoreGrants issues per-task, scoped State Store credentials for // agent containers (daemon.StateStoreGrantIssuer), wrapping the same // *staterpc.Client as stateStore. Nil when the State Store adapter isn't @@ -444,6 +442,20 @@ func (b *boot) openStateStoreAdapter() error { return nil } +// openStateStage opens the state-store adapter and its daemon-side surfaces +// plus the policy chain, in one step of the composition sequence: the three +// are ordered but not interleaved, and any failure fails the boot +// (openStateStoreAdapter, openDaemonStateSurfaces, openAccessChain). +func (b *boot) openStateStage(ctx context.Context) error { + if err := b.openStores(ctx); err != nil { + return err + } + if err := b.openDaemonStateSurfaces(); err != nil { + return err + } + return b.openAccessChain(ctx) +} + // openAccessChain builds the policy chain the daemon dispatches through // (docs/prds/orgs-and-access.md, "Where it lives"): the stored policies over // the wire, compiled once at boot. An invalid instance policy fails the boot; diff --git a/internal/app/archied/main.go b/internal/app/archied/main.go index f738aa3b6..abc2f35d9 100644 --- a/internal/app/archied/main.go +++ b/internal/app/archied/main.go @@ -358,27 +358,11 @@ func Run() int { //nolint:cyclop,funlen // the composition root's setup sequence return 1 } - if err := b.openStores(ctx); err != nil { - return 1 - } - // Resolve the State Store surfaces before setupObservability wires the - // dashboard's storage surfaces (§10): the shared contract adapter (the - // remote *staterpc.Client dialed to [services.state].target; the daemon no - // longer owns archie.db in-process, so an empty target is a composition - // error, docs/prds/state-store-contract.md §12 step 7) and then, daemon - // root only, the workflow-definitions client on this process's step - // vocabulary. The daemon resolves step types through that client, so it is - // built here -- after the adapter, whose transport it wraps -- and before - // buildDaemon captures it. The gateway root shares only the adapter and - // resolves no step type, so openDaemonStateSurfaces owns the order and - // step_vocabulary_test.go pins the cut. - if err := b.openDaemonStateSurfaces(); err != nil { - return 1 - } - // The policy chain the dispatch loop evaluates, built once from the - // stored policies (docs/prds/orgs-and-access.md). It runs after the - // state surfaces exist and before the daemon is built. - if err := b.openAccessChain(ctx); err != nil { + // The state-store adapter, its daemon-side surfaces and the policy chain + // dispatch evaluates: one ordered stage of the composition sequence + // (openStateStage; docs/prds/state-store-contract.md §12 step 7 and + // docs/prds/orgs-and-access.md). + if err := b.openStateStage(ctx); err != nil { return 1 } if err := b.loadRuntimeConfig(ctx); err != nil { diff --git a/internal/app/archied/state_store.go b/internal/app/archied/state_store.go index 0fc6037f7..32e8a3118 100644 --- a/internal/app/archied/state_store.go +++ b/internal/app/archied/state_store.go @@ -72,7 +72,7 @@ type StateStoreOptions struct { // The conversation store belongs to the separate archie-gateway process. The // store service owns its own DB lifecycle, so // b.cleanup() is the sole owner closing b.st here (in-process owner). -func RunStateStore(ctx context.Context, options StateStoreOptions) error { +func RunStateStore(ctx context.Context, options StateStoreOptions) error { //nolint:cyclop // the composition root's setup sequence is deliberately flat and sequential b := newBootstrap() defer b.cleanup() if err := b.loadConfig(ctx, options.Config, options.Overlay); err != nil { @@ -107,52 +107,15 @@ func RunStateStore(ctx context.Context, options StateStoreOptions) error { return fmt.Errorf("upgrade default org: %w", err) } } - // The shipped role policies mean the org level always has policies - // (docs/prds/orgs-and-access.md, "Roles"): seed them for every org that - // lacks them, then re-validate every stored policy this process serves. - // An invalid org, workspace or object policy is logged here and named as - // a problem by the engines the consumers build; an invalid instance - // policy fails this boot -- the store stops serving until it is fixed. - if policies, ok := b.st.(access.PolicyStore); ok { - // An agent is granted access the way a user is: its assigned org, - // with the shipped developer role, so dispatch's principal evaluates. - if agents, ok := b.st.(interface { - EnsureAgentOrgMembership(context.Context) error - }); ok { - if err := agents.EnsureAgentOrgMembership(ctx); err != nil { - return fmt.Errorf("grant agent org membership: %w", err) - } - } - if orgs, ok := b.st.(org.Repository); ok { - list, err := orgs.ListOrgs(ctx) - if err != nil { - return fmt.Errorf("list orgs for policy seeding: %w", err) - } - for _, o := range list { - if err := policies.EnsureShippedOrgPolicies(ctx, o.ID); err != nil { - return fmt.Errorf("seed shipped org policies for %s: %w", o.ID, err) - } - } - } - stored, err := policies.ListPolicies(ctx) - if err != nil { - return fmt.Errorf("load stored policies: %w", err) - } - engine, err := infraaccess.New(stored) - if err != nil { - return fmt.Errorf("validate stored policies: %w", err) - } - for _, problem := range engine.Problems() { - b.log.Error("stored access policy is invalid and denies its level", - "policy", problem.Policy.ID, "level", problem.Policy.Level, "err", problem.Err) - } + if err := b.seedAndValidatePolicies(ctx); err != nil { + return err } + // The validating side's control plane, built here at the composition root + // before the first definition is read or replaced. resources, ok := b.st.(controlplane.ResourceStore) if !ok { return fmt.Errorf("state store does not support control-plane resources") } - // The validating side's control plane, built here at the composition root - // before the first definition is read or replaced. control, err := openStateStoreControlPlane(resources) if err != nil { return err @@ -189,6 +152,52 @@ func RunStateStore(ctx context.Context, options StateStoreOptions) error { return serveStateStore(ctx, listener, deps, opts) } +// seedAndValidatePolicies seeds the shipped role policies for every org +// that lacks them, grants the agent identities their org's shipped developer +// role, and re-validates every stored policy this process serves +// (docs/prds/orgs-and-access.md, "Storing and changing policies" and +// "Roles"). An invalid org, workspace or object policy is logged here and +// named as a problem by the engines the consumers build; an invalid instance +// policy fails this boot -- the store stops serving until it is fixed. A +// store without the access surfaces degrades: there is no chain to seed. +func (b *boot) seedAndValidatePolicies(ctx context.Context) error { + policies, ok := b.st.(access.PolicyStore) + if !ok { + return nil + } + if agents, ok := b.st.(interface { + EnsureAgentOrgMembership(context.Context) error + }); ok { + if err := agents.EnsureAgentOrgMembership(ctx); err != nil { + return fmt.Errorf("grant agent org membership: %w", err) + } + } + if orgs, ok := b.st.(org.Repository); ok { + list, err := orgs.ListOrgs(ctx) + if err != nil { + return fmt.Errorf("list orgs for policy seeding: %w", err) + } + for _, o := range list { + if err := policies.EnsureShippedOrgPolicies(ctx, o.ID); err != nil { + return fmt.Errorf("seed shipped org policies for %s: %w", o.ID, err) + } + } + } + stored, err := policies.ListPolicies(ctx) + if err != nil { + return fmt.Errorf("load stored policies: %w", err) + } + engine, err := infraaccess.New(stored) + if err != nil { + return fmt.Errorf("validate stored policies: %w", err) + } + for _, problem := range engine.Problems() { + b.log.Error("stored access policy is invalid and denies its level", + "policy", problem.Policy.ID, "level", problem.Policy.Level, "err", problem.Err) + } + return nil +} + // reportUnseededResources logs every kind ImportConfig could not seed. // // Reported, not fatal: a stale TOML value in a setting the database owns must diff --git a/internal/app/archied/step_vocabulary_test.go b/internal/app/archied/step_vocabulary_test.go index ed0b068c4..509706cd7 100644 --- a/internal/app/archied/step_vocabulary_test.go +++ b/internal/app/archied/step_vocabulary_test.go @@ -138,25 +138,27 @@ func TestOnlyTheDaemonRootRegistersAStepVocabulary(t *testing.T) { t.Error("the gateway root file mentions stepVocabulary; the gateway resolves no workflow step type") } - // The daemon root opens both halves -- the shared adapter and the - // daemon-only definitions client -- through one call, so the sequence costs - // Run a single branch. The guarantee is the one this pin always held, - // relocated to where the sequence now lives: adapter first, then the client - // built on its transport, both before buildDaemon captures the client. + // The daemon root opens the state stage -- the shared adapter, the + // daemon-only definitions client and the access chain -- through one + // call, so the sequence costs Run a single branch. The guarantee is the + // one this pin always held, relocated to where the sequence now lives: + // adapter first, then the client built on its transport, both before + // buildDaemon captures the client. run := parsedBody(t, "main.go", "Run") - surfaces := methodCallPosition(run, "openDaemonStateSurfaces") + stage := methodCallPosition(run, "openStateStage") build := methodCallPosition(run, "buildDaemon") - if surfaces == token.NoPos { - t.Fatal("Run never opens the daemon's State Store surfaces; every task pin would fall back to the shipped definitions") + if stage == token.NoPos { + t.Fatal("Run never opens the daemon's state stage; every task pin would fall back to the shipped definitions") } - if build == token.NoPos || surfaces > build { - t.Errorf("Run opens the daemon's State Store surfaces at %v, after buildDaemon at %v: the daemon would capture no definitions surface", surfaces, build) + if build == token.NoPos || stage > build { + t.Errorf("Run opens the state stage at %v, after buildDaemon at %v: the daemon would capture no definitions surface", stage, build) } - // Neither half may also be opened from Run directly: a second call site - // would be a copy of the sequence outside the order asserted below. - for _, direct := range []string{"openStateStoreAdapter", "openDaemonWorkflowDefinitions"} { + // No half of the stage may also be opened from Run directly: a second + // call site would be a copy of the sequence outside the order asserted + // below. + for _, direct := range []string{"openStateStoreAdapter", "openDaemonWorkflowDefinitions", "openDaemonStateSurfaces", "openAccessChain"} { if pos := methodCallPosition(run, direct); pos != token.NoPos { - t.Errorf("Run calls %s directly at %v; the daemon's State Store surfaces open through openDaemonStateSurfaces alone", direct, pos) + t.Errorf("Run calls %s directly at %v; the state stage opens through openStateStage alone", direct, pos) } } diff --git a/internal/app/archieui/run.go b/internal/app/archieui/run.go index 9c73c6be9..ab9e9ed80 100644 --- a/internal/app/archieui/run.go +++ b/internal/app/archieui/run.go @@ -20,18 +20,19 @@ import ( "github.com/samcharles93/archie-core/internal/webui" ) -// errAccessStoreUnavailable reports that no policy store is wired. The -// dashboard degrades to the credential check rather than refusing to serve. -var errAccessStoreUnavailable = errors.New("access policy store unavailable") - // buildAccessChain loads the stored policies over the wire and builds the // engine. The wire client satisfies the two access contracts the dashboard // needs alongside the engine. -func buildAccessChain(ctx context.Context, store *staterpc.Client) (access.Authorizer, []infraaccess.Problem, error) { +// buildAccessChain loads the stored policies over the wire and builds the +// engine. A State Store serving no policies has no chain to evaluate: the +// dashboard degrades to the credential check rather than refusing to serve, +// so an unavailable policy store is a warning, not a boot failure. +func buildAccessChain(ctx context.Context, store *staterpc.Client, log *slog.Logger) (access.Authorizer, []infraaccess.Problem, error) { stored, err := store.ListPolicies(ctx) if err != nil { if status.Code(err) == codes.Unavailable { - return nil, nil, errAccessStoreUnavailable + log.Warn("access chain unavailable; the credential check is the gate", "err", err) + return nil, nil, nil } return nil, nil, err } @@ -39,6 +40,10 @@ func buildAccessChain(ctx context.Context, store *staterpc.Client) (access.Autho if err != nil { return nil, nil, err } + for _, problem := range engine.Problems() { + log.Error("stored access policy is invalid and denies its level", + "policy", problem.Policy.ID, "level", problem.Policy.Level, "err", problem.Err) + } return engine, engine.Problems(), nil } @@ -71,21 +76,9 @@ func Run(ctx context.Context, options Options) error { } cleanups = append(cleanups, closeGateway) - // The access chain is built here, from the stored policies over the - // wire: an invalid instance policy stops this process serving until it - // is fixed; an invalid org, workspace or object policy is reported as a - // health issue naming the policy and the error, and its level denies - // everything (docs/prds/orgs-and-access.md, "Storing and changing - // policies"). - chain, problems, err := buildAccessChain(ctx, tasks) + chain, problems, err := buildAccessChain(ctx, tasks, log) if err != nil { - if errors.Is(err, errAccessStoreUnavailable) { - // A State Store serving no policies has no chain to evaluate: - // the dashboard keeps the credential check as the whole gate. - log.Warn("access chain unavailable; the credential check is the gate", "err", err) - } else { - return err - } + return err } for _, problem := range problems { log.Error("stored access policy is invalid and denies its level", diff --git a/internal/daemon/daemon.go b/internal/daemon/daemon.go index 96f332a06..94d52505f 100644 --- a/internal/daemon/daemon.go +++ b/internal/daemon/daemon.go @@ -748,6 +748,13 @@ func (d *Daemon) dispatchOneBinding(ctx context.Context, b binding.Binding, c st if !d.authorizeDispatch(ctx, b, c, target) { return } + d.claimAndEnqueue(ctx, b, c, target, values) +} + +// claimAndEnqueue claims the dispatch in the at-most-once ledger and enqueues +// the task. A failed enqueue after the claim loses that dispatch, which is +// the at-most-once side of the trade (docs/prds/playbook-binding.md). +func (d *Daemon) claimAndEnqueue(ctx context.Context, b binding.Binding, c storecontract.CapturedEvent, target bindingTarget, values map[string]any) { if err := d.BindingDispatcher.RecordDispatch(ctx, b.ID, int64(b.Version), c.ID, 0); err != nil { if !errors.Is(err, storecontract.ErrAlreadyDispatched) { d.Log.Warn("binding dispatch: record", "binding", b.ID, "capture", c.ID, "error", err) diff --git a/internal/webui/authorize.go b/internal/webui/authorize.go index d7fdaa64a..d3fabe915 100644 --- a/internal/webui/authorize.go +++ b/internal/webui/authorize.go @@ -128,55 +128,72 @@ func (*notWiredError) Error() string { return "webui: principal assembly not wir // request from its method and path. Unmapped routes read the dashboard // itself, so a new route is never wider than read until it is mapped. func accessRequest(r *http.Request) (access.Action, access.ResourceKind, string) { - action := access.ActionRead - switch r.Method { - case http.MethodPost: - action = access.ActionCreate - case http.MethodPut, http.MethodPatch: - action = access.ActionUpdate - case http.MethodDelete: - action = access.ActionDelete - } + action := actionOf(r.Method) path := r.URL.Path + if a, kind, id, ok := routeOverride(action, path); ok { + return a, kind, id + } + return action, kindOf(path), segmentValue(path, 2) +} - // Route-specific action and kind refinements. +// actionOf maps the HTTP method onto the action vocabulary. POST is create: +// the route refinements lift the routes whose write is something else. +func actionOf(method string) access.Action { + switch method { + case http.MethodPost: + return access.ActionCreate + case http.MethodPut, http.MethodPatch: + return access.ActionUpdate + case http.MethodDelete: + return access.ActionDelete + } + return access.ActionRead +} + +// routeOverride returns the action, kind and record key a specific route +// shape carries, or ok=false when the method-and-kind fallback applies. +func routeOverride(action access.Action, path string) (access.Action, access.ResourceKind, string, bool) { switch { case action == access.ActionCreate && matchSegment(path, "/api/bindings/", "/approve"): - return access.ActionApprove, access.KindBinding, segmentValue(path, 2) + return access.ActionApprove, access.KindBinding, segmentValue(path, 2), true case matchSegment(path, "/api/tasks/", "/logs"): - return access.ActionReadLogs, access.KindTask, segmentValue(path, 2) + return access.ActionReadLogs, access.KindTask, segmentValue(path, 2), true case matchPrefix(path, "/api/identities"): - return actionManage(action), access.KindIdentity, segmentValue(path, 2) + return actionManage(action), access.KindIdentity, segmentValue(path, 2), true case matchPrefix(path, "/api/control-plane/resources"): - return actionManage(action), access.KindPolicy, segmentValue(path, 3) + return actionManage(action), access.KindPolicy, segmentValue(path, 3), true case matchPrefix(path, "/api/chat"): if action == access.ActionCreate { - return access.ActionRun, access.KindWorkflow, "" + return access.ActionRun, access.KindWorkflow, "", true } - return access.ActionRead, access.KindDashboard, "" + return access.ActionRead, access.KindDashboard, "", true case matchSegment(path, "/api/sources/", "/secret"): - return access.ActionUpdate, access.KindSecret, segmentValue(path, 2) + return access.ActionUpdate, access.KindSecret, segmentValue(path, 2), true case matchPrefix(path, "/api/channels/"): - return actionManage(action), access.KindDashboard, segmentValue(path, 2) + return actionManage(action), access.KindDashboard, segmentValue(path, 2), true case matchPrefix(path, "/api/config"), matchPrefix(path, "/api/logs"): - return access.ActionRead, access.KindDashboard, "" + return access.ActionRead, access.KindDashboard, "", true } + return action, "", "", false +} +// kindOf maps a collection route onto the resource kind it addresses. +func kindOf(path string) access.ResourceKind { switch { case matchPrefix(path, "/api/tasks"): - return action, access.KindTask, segmentValue(path, 2) + return access.KindTask case matchPrefix(path, "/api/event-types"): - return action, access.KindEventType, segmentValue(path, 2) + return access.KindEventType case matchPrefix(path, "/api/mappings"): - return action, access.KindMapping, segmentValue(path, 2) + return access.KindMapping case matchPrefix(path, "/api/bindings"): - return action, access.KindBinding, segmentValue(path, 2) + return access.KindBinding case matchPrefix(path, "/api/sources"): - return action, access.KindSource, segmentValue(path, 2) + return access.KindSource case matchPrefix(path, "/api/work-requests"): - return action, access.KindTask, "" + return access.KindTask } - return action, access.KindDashboard, "" + return access.KindDashboard } // actionManage lifts a create or update on a managed surface to the manage diff --git a/internal/webui/authorize_test.go b/internal/webui/authorize_test.go index d850bc47e..a3f9e96c2 100644 --- a/internal/webui/authorize_test.go +++ b/internal/webui/authorize_test.go @@ -53,7 +53,7 @@ func TestAuthorizeNilEngineServesEverything(t *testing.T) { s := &Server{} h := s.authorize(http.HandlerFunc(handlerEcho)) rec := httptest.NewRecorder() - h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/api/tasks", nil)) + h.ServeHTTP(rec, httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/tasks", nil)) if rec.Code != http.StatusOK { t.Fatalf("nil chain served %d, want 200: the credential check stays the gate", rec.Code) } @@ -64,7 +64,7 @@ func TestAuthorizeTokenOwnerAllowed(t *testing.T) { s := newAccessServer(t, engine, nil) h := s.authorize(http.HandlerFunc(handlerEcho)) rec := httptest.NewRecorder() - h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/api/bindings", nil)) + h.ServeHTTP(rec, httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/bindings", nil)) if rec.Code != http.StatusOK { t.Fatalf("allowed request served %d, want 200", rec.Code) } @@ -84,7 +84,7 @@ func TestAuthorizeDenialIsForbiddenWithoutReason(t *testing.T) { s := newAccessServer(t, engine, denials) h := s.authorize(http.HandlerFunc(handlerEcho)) rec := httptest.NewRecorder() - h.ServeHTTP(rec, httptest.NewRequest(http.MethodDelete, "/api/bindings/b1", nil)) + h.ServeHTTP(rec, httptest.NewRequestWithContext(t.Context(), http.MethodDelete, "/api/bindings/b1", nil)) if rec.Code != http.StatusForbidden { t.Fatalf("denied request served %d, want 403", rec.Code) } @@ -108,7 +108,7 @@ func TestAuthorizeApproveRoute(t *testing.T) { engine := &fakeAuthorizer{decision: access.Allowed()} s := newAccessServer(t, engine, nil) h := s.authorize(http.HandlerFunc(handlerEcho)) - h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodPost, "/api/bindings/b1/approve", nil)) + h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/api/bindings/b1/approve", nil)) if engine.lastAct != access.ActionApprove { t.Fatalf("approve route derived action %q, want approve", engine.lastAct) } @@ -118,7 +118,7 @@ func TestAuthorizeTaskLogRouteReadsLogs(t *testing.T) { engine := &fakeAuthorizer{decision: access.Allowed()} s := newAccessServer(t, engine, nil) h := s.authorize(http.HandlerFunc(handlerEcho)) - h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/api/tasks/7/logs", nil)) + h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/tasks/7/logs", nil)) if engine.lastAct != access.ActionReadLogs || engine.last.Kind != access.KindTask || engine.last.ID != "7" { t.Fatalf("log route derived %+v %q, want read_logs on task 7", engine.lastAct, engine.last.Kind) }