diff --git a/NOTICE b/NOTICE index c9d0c8b6b..9a60de491 100644 --- a/NOTICE +++ b/NOTICE @@ -11,3 +11,9 @@ deduplication, line mapping and review-event selection. PR-AF declares the Apache License, Version 2.0 in its pyproject.toml and ships no license file. A copy of the License is available at https://www.apache.org/licenses/LICENSE-2.0 + +This product includes software from the Cedar project +(https://github.com/cedar-policy/cedar), Copyright Amazon.com, Inc. or its +affiliates, licensed under the Apache License, Version 2.0, as implemented by +github.com/cedar-policy/cedar-go, which declares the same license in its +repository. This repository links the library; it derives no source from it. diff --git a/cmd/archied/main.go b/cmd/archied/main.go index a12379d30..5955eb316 100644 --- a/cmd/archied/main.go +++ b/cmd/archied/main.go @@ -2,6 +2,7 @@ package main import ( + "context" "os" "github.com/samcharles93/archie-core/internal/app/archied" @@ -15,5 +16,10 @@ func main() { if archied.IsSetupArgs(args) { os.Exit(archied.RunSetup(args[1:], os.Stdin, os.Stdout, os.Stderr)) } + // The access recovery command runs before the daemon's flags are parsed: + // it is a State Store host operation, not a daemon run. + if archied.IsAccessResetArgs(args) { + os.Exit(archied.RunAccessReset(context.Background(), args[2:], os.Stderr)) + } os.Exit(archied.Run()) } diff --git a/go.mod b/go.mod index 195fd9297..1f5a6c899 100644 --- a/go.mod +++ b/go.mod @@ -57,8 +57,6 @@ require ( github.com/nats-io/jwt/v2 v2.8.2 // indirect github.com/nats-io/nkeys v0.4.16 // indirect github.com/nats-io/nuid v1.0.1 // indirect - github.com/opencontainers/go-digest v1.0.0 // indirect - github.com/opencontainers/image-spec v1.1.1 // indirect github.com/pjbgf/sha1cd v0.6.0 // indirect github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect github.com/power-devops/perfstat v0.0.0-20260916203055-22a1a467d9f0 // indirect @@ -90,13 +88,13 @@ require ( google.golang.org/genproto/googleapis/rpc v0.0.0-20260921155816-b14227669459 // indirect modernc.org/libc v1.77.1 // indirect modernc.org/sqlite v1.59.0 // indirect - oras.land/oras-go/v2 v2.6.2 // indirect ) require ( cel.dev/cel-go v0.32.0 code.gitea.io/sdk/gitea v0.25.1 github.com/BurntSushi/toml v1.6.0 + github.com/cedar-policy/cedar-go v1.8.0 github.com/coreos/go-oidc/v3 v3.21.0 github.com/docker/sandbox-kit-spec/v3 v3.0.0-m.6 github.com/go-git/go-billy/v6 v6.0.0-alpha.2 @@ -111,6 +109,8 @@ require ( github.com/modelcontextprotocol/go-sdk v1.8.0 github.com/nats-io/nats-server/v2 v2.15.0 github.com/nats-io/nats.go v1.54.0 + github.com/opencontainers/go-digest v1.0.0 + github.com/opencontainers/image-spec v1.1.1 github.com/pressly/goose/v3 v3.28.0 github.com/samcharles93/ai-sdk v0.1.39 github.com/testcontainers/testcontainers-go v0.44.0 @@ -125,4 +125,5 @@ require ( google.golang.org/grpc v1.85.0-dev.0.20260825072537-93e31b48545e google.golang.org/protobuf v1.36.12 gopkg.in/yaml.v3 v3.0.1 + oras.land/oras-go/v2 v2.6.2 ) diff --git a/go.sum b/go.sum index 09836e4da..9f075c6a8 100644 --- a/go.sum +++ b/go.sum @@ -26,6 +26,8 @@ github.com/antlr4-go/antlr/v4 v4.13.1 h1:SqQKkuVZ+zWkMMNkjy5FZe5mr5WURWnlpmOuzYW github.com/antlr4-go/antlr/v4 v4.13.1/go.mod h1:GKmUxMtwp6ZgGwZSva4eWPC5mS6vUAmOABFgjdkM7Nw= github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPdPJAN/hZIm0C4OItdklCFmMRWYpio= github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs= +github.com/cedar-policy/cedar-go v1.8.0 h1:9gcU7EHXwHC2RMdpph68yTAkdB3behTTssC+kt4GoS8= +github.com/cedar-policy/cedar-go v1.8.0/go.mod h1:h5+3CVW1oI5LXVskJG+my9TFCYI5yjh/+Ul3EJie6MI= github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8= github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE= github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= diff --git a/internal/app/archied/access_reset.go b/internal/app/archied/access_reset.go new file mode 100644 index 000000000..c6fa14475 --- /dev/null +++ b/internal/app/archied/access_reset.go @@ -0,0 +1,110 @@ +// The `archied access reset` command: the locked-out-org and broken-instance +// recovery surface (docs/prds/orgs-and-access.md, "Recovering from a +// locked-out org"). It restores the shipped role policies for one org and +// removes its other org-level policies, or removes the stored instance +// policies; the cross-org forbid is engine-enforced and survives any reset. +// +// It runs only on the State Store host, never over the network, and is +// recorded as an audit event. It claims the same store ownership the State +// Store holds, so a running store refuses it: stop the store, reset, start +// the store. +package archied + +import ( + "context" + "flag" + "fmt" + "io" + + "github.com/jackc/pgx/v5/pgxpool" + + "github.com/samcharles93/archie-core/internal/domain/access" + "github.com/samcharles93/archie-core/internal/domain/org" + "github.com/samcharles93/archie-core/internal/infrastructure/configuration" + "github.com/samcharles93/archie-core/internal/infrastructure/postgres" +) + +// accessResetCommand is the argv selector for the recovery command. +const accessResetCommand = "access" + +// IsAccessResetArgs reports whether args selects the access recovery command. +func IsAccessResetArgs(args []string) bool { + return len(args) > 2 && args[0] == accessResetCommand && args[1] == resetCommand +} + +const resetCommand = "reset" + +// RunAccessReset performs the reset and returns the process exit code: +// 0 reset, 1 failure, 2 usage. +func RunAccessReset(ctx context.Context, args []string, stderr io.Writer) int { + fs := flag.NewFlagSet(resetCommand, flag.ContinueOnError) + fs.SetOutput(stderr) + cfgPath := fs.String("config", configuration.DefaultConfigPath(), "path to a TOML/YAML config file or configuration directory") + overlayPath := fs.String("config-overlay", "", "path to a TOML/YAML overlay file or configuration directory applied on top of -config") + orgFlag := fs.String("org", "", "org whose access to reset; conflicts with --instance") + instance := fs.Bool("instance", false, "reset the stored instance policies") + if err := fs.Parse(args); err != nil { + return 2 + } + if fs.NArg() > 0 { + fmt.Fprintf(stderr, "reset: unexpected argument %q\n", fs.Arg(0)) + return 2 + } + if (*orgFlag != "" && *instance) || (*orgFlag == "" && !*instance) { + fmt.Fprintln(stderr, "reset: give exactly one of --org or --instance") + return 2 + } + + b := newBootstrap() + defer b.cleanup() + if err := b.loadConfig(ctx, *cfgPath, *overlayPath); err != nil { + return 1 + } + if err := b.openStateStorePool(ctx); err != nil { + // A running State Store holds the ownership claim; the reset must not + // race it. Stop the store, reset, start the store. + fmt.Fprintln(stderr, "reset: open the State Store database (stop archie-state-store first)") + return 1 + } + resetter, ok := b.st.(access.Resetter) + if !ok { + fmt.Fprintln(stderr, "reset: the State Store does not support the access reset surface") + return 1 + } + var err error + switch { + case *instance: + err = resetter.ResetInstancePolicies(ctx) + default: + err = resetter.ResetOrgPolicies(ctx, org.OrgID(*orgFlag)) + } + if err != nil { + fmt.Fprintf(stderr, "reset: %v\n", err) + return 1 + } + if err := recordResetAudit(ctx, b.pg, *orgFlag, *instance); err != nil { + fmt.Fprintf(stderr, "reset: audit: %v\n", err) + return 1 + } + fmt.Fprintf(stderr, "reset: access policies for %s restored to the shipped set\n", resetTarget(*orgFlag, *instance)) + return 0 +} + +// resetTarget names what the reset covered, for the operator's output. +func resetTarget(orgID string, instance bool) string { + if instance { + return "the instance" + } + return fmt.Sprintf("org %q", orgID) +} + +// recordResetAudit writes the one audit row the reset is recorded as. The +// policy changes themselves carry their own sys_audit rows; this names the +// recovery. +func recordResetAudit(ctx context.Context, pool *pgxpool.Pool, orgID string, instance bool) error { + key := "reset/instance" + if !instance { + key = fmt.Sprintf("reset/org/%s", orgID) + } + return postgres.New(pool).RecordResetAudit(ctx, key) +} diff --git a/internal/app/archied/access_reset_test.go b/internal/app/archied/access_reset_test.go new file mode 100644 index 000000000..3aff04081 --- /dev/null +++ b/internal/app/archied/access_reset_test.go @@ -0,0 +1,54 @@ +package archied + +import ( + "strings" + "testing" +) + +func TestIsAccessResetArgs(t *testing.T) { + tests := []struct { + name string + args []string + want bool + }{ + {name: "org reset", args: []string{"access", "reset", "--org", "acme"}, want: true}, + {name: "instance reset", args: []string{"access", "reset", "--instance"}, want: true}, + {name: "config first", args: []string{"access", "reset", "-config", "/tmp/config.toml", "--org", "acme"}, want: true}, + {name: "setup is not a reset", args: []string{"setup"}, want: false}, + {name: "bare access", args: []string{"access"}, want: false}, + {name: "other subcommand", args: []string{"access", "grant"}, want: false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := IsAccessResetArgs(tt.args); got != tt.want { + t.Fatalf("IsAccessResetArgs(%v) = %v, want %v", tt.args, got, tt.want) + } + }) + } +} + +func TestRunAccessResetUsage(t *testing.T) { + tests := []struct { + name string + args []string + wantCode int + wantText string + }{ + {name: "no target", args: nil, wantCode: 2, wantText: "exactly one of --org"}, + {name: "both targets", args: []string{"--org", "acme", "--instance"}, wantCode: 2, wantText: "exactly one of --org"}, + {name: "unexpected argument", args: []string{"--instance", "extra"}, wantCode: 2, wantText: "unexpected argument"}, + {name: "unknown flag", args: []string{"--workspace", "net"}, wantCode: 2}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var stderr strings.Builder + code := RunAccessReset(t.Context(), tt.args, &stderr) + if code != tt.wantCode { + t.Fatalf("RunAccessReset(%v) = %d, want %d (stderr: %s)", tt.args, code, tt.wantCode, stderr.String()) + } + if tt.wantText != "" && !strings.Contains(stderr.String(), tt.wantText) { + t.Fatalf("stderr = %q, want it to name %q", stderr.String(), tt.wantText) + } + }) + } +} diff --git a/internal/app/archied/bootstrap.go b/internal/app/archied/bootstrap.go index d40e45695..c65a2fa57 100644 --- a/internal/app/archied/bootstrap.go +++ b/internal/app/archied/bootstrap.go @@ -30,6 +30,7 @@ import ( "github.com/samcharles93/archie-core/internal/container" controlpb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1" "github.com/samcharles93/archie-core/internal/daemon" + "github.com/samcharles93/archie-core/internal/domain/access" "github.com/samcharles93/archie-core/internal/domain/applystatus" "github.com/samcharles93/archie-core/internal/domain/curator" "github.com/samcharles93/archie-core/internal/domain/eda/module" @@ -46,6 +47,7 @@ import ( "github.com/samcharles93/archie-core/internal/forge" forgewebhook "github.com/samcharles93/archie-core/internal/forge/webhook" "github.com/samcharles93/archie-core/internal/gateway" + infraaccess "github.com/samcharles93/archie-core/internal/infrastructure/access" "github.com/samcharles93/archie-core/internal/infrastructure/configuration" infraembedding "github.com/samcharles93/archie-core/internal/infrastructure/embedding" "github.com/samcharles93/archie-core/internal/infrastructure/eventbus/nats" @@ -124,6 +126,11 @@ type boot struct { // set. The b.st field remains solely for the standalone archie-state-store // binary, which serves the task store from Postgres. stateStore storecontract.TaskStore + // 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 + 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 @@ -435,6 +442,47 @@ 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; +// an invalid org, workspace or object policy is retained as a health problem +// and its level denies everything. +func (b *boot) openAccessChain(ctx context.Context) error { + source, ok := b.stateStore.(access.PolicySource) + if !ok { + return nil // no policy store wired: the chain is not built + } + stored, err := source.Policies(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) + } + b.accessChain = engine + b.accessProblems = engine.Problems() + for _, problem := range b.accessProblems { + 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 +} + // openChatSessions opens the conversation store on its own pool from // database_url. The daemon reads it (session curator) and the Gateway serves // it; only the Gateway claims serve ownership (claimGatewayOwnership). @@ -1387,6 +1435,18 @@ func (b *boot) buildDaemon() { if btc, ok := b.stateStore.(storecontract.BindingTaskCreator); ok { b.d.BindingTaskCreator = btc } + // Dispatch is the second Authorizer call site: the chain built by + // openAccessChain, the principal assembly over the wire, and the denial + // record -- wired together or not at all (docs/prds/orgs-and-access.md). + b.d.Access = b.accessChain + if b.accessChain != nil { + if principals, ok := b.stateStore.(access.PrincipalSource); ok { + b.d.Principals = principals + } + if denials, ok := b.stateStore.(access.DenialStore); ok { + b.d.Denials = denials + } + } b.d.PlaybookLedger = playbookLedger(b.stateStore, b.playbooks, b.log) b.setupForgeWebhook() } diff --git a/internal/app/archied/main.go b/internal/app/archied/main.go index 65ba53618..abc2f35d9 100644 --- a/internal/app/archied/main.go +++ b/internal/app/archied/main.go @@ -358,21 +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 { + // 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/readiness.go b/internal/app/archied/readiness.go index ea6b3e9bb..b23381e5d 100644 --- a/internal/app/archied/readiness.go +++ b/internal/app/archied/readiness.go @@ -44,6 +44,9 @@ func (b *boot) setupReadinessProbes() { return pingChat(ctx, b.chat) }), } + if b.accessProblems != nil { + probes = append(probes, readiness.NewProblemProbe("access_policies", b.accessProblems)) + } b.healthRegistry = health.NewRegistry(probes...) } diff --git a/internal/app/archied/state_store.go b/internal/app/archied/state_store.go index d1e76bc8c..32e8a3118 100644 --- a/internal/app/archied/state_store.go +++ b/internal/app/archied/state_store.go @@ -21,11 +21,13 @@ import ( "github.com/samcharles93/archie-core/internal/app/controlplane" "github.com/samcharles93/archie-core/internal/config" + "github.com/samcharles93/archie-core/internal/domain/access" "github.com/samcharles93/archie-core/internal/domain/health" "github.com/samcharles93/archie-core/internal/domain/identity" "github.com/samcharles93/archie-core/internal/domain/org" "github.com/samcharles93/archie-core/internal/domain/storecontract" "github.com/samcharles93/archie-core/internal/domain/storepkg" + infraaccess "github.com/samcharles93/archie-core/internal/infrastructure/access" "github.com/samcharles93/archie-core/internal/infrastructure/postgres" "github.com/samcharles93/archie-core/internal/infrastructure/readiness" "github.com/samcharles93/archie-core/internal/infrastructure/staterpc" @@ -70,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 { @@ -105,12 +107,15 @@ func RunStateStore(ctx context.Context, options StateStoreOptions) error { return fmt.Errorf("upgrade default org: %w", 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 @@ -147,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 @@ -287,6 +338,19 @@ func (b *boot) stateStoreDeps(grants *staterpc.TaskGrants) staterpc.Deps { if wc, ok := b.st.(storecontract.WorkflowCaller); ok { deps.WorkflowCalls = wc } + // The policy chain and its denial records are served from the same store + // (docs/prds/orgs-and-access.md). A store without them -- one that owns + // no tenant boundary yet -- degrades the access RPCs rather than failing + // the boot, the same pattern the other optional surfaces use. + if ps, ok := b.st.(access.PrincipalSource); ok { + deps.Principals = ps + } + if ps, ok := b.st.(access.PolicyStore); ok { + deps.Policies = ps + } + if ds, ok := b.st.(access.DenialStore); ok { + deps.Denials = ds + } if css, ok := b.st.(storecontract.ConfigSnapshotStore); ok { deps.ConfigSnapshots = css } 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/compose.go b/internal/app/archieui/compose.go index e69ff564f..1900a8e74 100644 --- a/internal/app/archieui/compose.go +++ b/internal/app/archieui/compose.go @@ -6,6 +6,7 @@ import ( "time" controlpb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1" + "github.com/samcharles93/archie-core/internal/domain/access" "github.com/samcharles93/archie-core/internal/domain/health" "github.com/samcharles93/archie-core/internal/domain/identity" "github.com/samcharles93/archie-core/internal/domain/messaging" @@ -33,6 +34,12 @@ type deps struct { // Login drives the browser sign-in flow, or nil when no provider is // configured for it. Login identity.LoginFlow + // Access evaluates the policy chain; Principals assembles the request + // principal; Denials records refusals + // (docs/prds/orgs-and-access.md). Wired together or not at all. + Access access.Authorizer + Principals access.PrincipalSource + Denials access.DenialStore } // compose builds the dashboard server for the UI process. It sets exactly the @@ -114,6 +121,11 @@ func compose(d deps) *webui.Server { // rather than opening a path (docs/prds/ui-service-boundary.md). Withholding // it would degrade a page that has an owner, and would leave the dashboard // claiming task logging was not enabled -- see wireTaskLogs. + // The policy chain: wired together or not at all + // (docs/prds/orgs-and-access.md, "Where it lives"). + srv.Access = d.Access + srv.Principals = d.Principals + srv.Denials = d.Denials wireTaskLogs(d, srv) wireCaptureSurfaces(d, srv) return srv diff --git a/internal/app/archieui/degraded_routes_test.go b/internal/app/archieui/degraded_routes_test.go index 19220eb05..7b4e3b124 100644 --- a/internal/app/archieui/degraded_routes_test.go +++ b/internal/app/archieui/degraded_routes_test.go @@ -181,6 +181,6 @@ func composeUIProcess(t *testing.T) (*webui.Server, int64) { Options: options, Log: slog.New(slog.DiscardHandler), Store: client, - Health: newReadinessRegistry(options, client, nil), + Health: newReadinessRegistry(options, client, nil, nil), }), task.ID } diff --git a/internal/app/archieui/readiness.go b/internal/app/archieui/readiness.go index 386a60e94..77c0f272d 100644 --- a/internal/app/archieui/readiness.go +++ b/internal/app/archieui/readiness.go @@ -6,6 +6,7 @@ import ( "github.com/samcharles93/archie-core/internal/domain/health" "github.com/samcharles93/archie-core/internal/domain/messaging" "github.com/samcharles93/archie-core/internal/domain/storecontract" + infraaccess "github.com/samcharles93/archie-core/internal/infrastructure/access" "github.com/samcharles93/archie-core/internal/infrastructure/readiness" ) @@ -17,8 +18,9 @@ import ( // // The component names match the daemon dashboard's, so the readiness view // reads the same whichever process serves it. -func newReadinessRegistry(o Options, tasks storecontract.TaskStore, chat messaging.ChatContract) *health.Registry { +func newReadinessRegistry(o Options, tasks storecontract.TaskStore, chat messaging.ChatContract, problems []infraaccess.Problem) *health.Registry { return health.NewRegistry( + readiness.NewProblemProbe("access_policies", problems), readiness.NewContractProbe("state_db", o.DependencyTimeout, func(ctx context.Context) error { _, err := tasks.StatusCounts(ctx) return err diff --git a/internal/app/archieui/run.go b/internal/app/archieui/run.go index ac057cc98..ab9e9ed80 100644 --- a/internal/app/archieui/run.go +++ b/internal/app/archieui/run.go @@ -10,11 +10,43 @@ import ( "os" "slices" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + "github.com/samcharles93/archie-core/internal/domain/access" + infraaccess "github.com/samcharles93/archie-core/internal/infrastructure/access" "github.com/samcharles93/archie-core/internal/infrastructure/gatewayrpc" "github.com/samcharles93/archie-core/internal/infrastructure/staterpc" "github.com/samcharles93/archie-core/internal/webui" ) +// 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. +// 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 { + log.Warn("access chain unavailable; the credential check is the gate", "err", err) + return nil, nil, nil + } + return nil, nil, err + } + engine, err := infraaccess.New(stored) + 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 +} + // Run serves the dashboard until ctx is cancelled. It resolves its own // options, dials the Gateway and State Store contracts itself, composes the // HTTP surface over them, and unwinds listener then clients in reverse order @@ -44,6 +76,15 @@ func Run(ctx context.Context, options Options) error { } cleanups = append(cleanups, closeGateway) + chain, problems, err := buildAccessChain(ctx, tasks, log) + if err != nil { + return err + } + for _, problem := range problems { + log.Error("stored access policy is invalid and denies its level", + "policy", problem.Policy.ID, "level", problem.Policy.Level, "err", problem.Err) + } + authenticate, err := dashboardAuthenticator(ctx, opts, tasks, log) if err != nil { return err @@ -58,11 +99,14 @@ func Run(ctx context.Context, options Options) error { Log: log, Store: tasks, Chat: chat, - Health: newReadinessRegistry(opts, tasks, chat), + Health: newReadinessRegistry(opts, tasks, chat, problems), ControlPlane: tasks.ControlPlane(), Identities: tasks, Authenticate: authenticate, Login: login, + Access: chain, + Principals: tasks, + Denials: tasks, }) // Live activity has no in-process bus in this process: the pump reads diff --git a/internal/app/archieui/run_test.go b/internal/app/archieui/run_test.go index 278368eb5..d404a4a73 100644 --- a/internal/app/archieui/run_test.go +++ b/internal/app/archieui/run_test.go @@ -178,7 +178,7 @@ func TestUIServesDashboardAgainstRemoteContracts(t *testing.T) { Log: slog.New(slog.DiscardHandler), Store: stateClient, Chat: chatClient, - Health: newReadinessRegistry(options, stateClient, chatClient), + Health: newReadinessRegistry(options, stateClient, chatClient, nil), }) ts := httptest.NewServer(srv.Handler()) defer ts.Close() diff --git a/internal/app/archieui/task_logs_test.go b/internal/app/archieui/task_logs_test.go index fe6390d39..ca5e9c803 100644 --- a/internal/app/archieui/task_logs_test.go +++ b/internal/app/archieui/task_logs_test.go @@ -193,7 +193,7 @@ func composeUIProcessWithLog(t *testing.T) (*webui.Server, int64, int) { Options: options, Log: slog.New(slog.DiscardHandler), Store: client, - Health: newReadinessRegistry(options, client, nil), + Health: newReadinessRegistry(options, client, nil, nil), }) return srv, task.ID, task.Attempt } diff --git a/internal/contracts/state/v1/state.pb.go b/internal/contracts/state/v1/state.pb.go index 887637d55..189fc3c35 100644 --- a/internal/contracts/state/v1/state.pb.go +++ b/internal/contracts/state/v1/state.pb.go @@ -9822,6 +9822,925 @@ func (*RemoveInstalledPackageResponse) Descriptor() ([]byte, []int) { return file_state_v1_state_proto_rawDescGZIP(), []int{182} } +type GetPrincipalRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + IdentityId string `protobuf:"bytes,1,opt,name=identity_id,json=identityId,proto3" json:"identity_id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *GetPrincipalRequest) Reset() { + *x = GetPrincipalRequest{} + mi := &file_state_v1_state_proto_msgTypes[183] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *GetPrincipalRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetPrincipalRequest) ProtoMessage() {} + +func (x *GetPrincipalRequest) ProtoReflect() protoreflect.Message { + mi := &file_state_v1_state_proto_msgTypes[183] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GetPrincipalRequest.ProtoReflect.Descriptor instead. +func (*GetPrincipalRequest) Descriptor() ([]byte, []int) { + return file_state_v1_state_proto_rawDescGZIP(), []int{183} +} + +func (x *GetPrincipalRequest) GetIdentityId() string { + if x != nil { + return x.IdentityId + } + return "" +} + +// PrincipalMembership mirrors org.Membership: an identity's role in an org, +// or in one workspace of it. +type PrincipalMembership struct { + state protoimpl.MessageState `protogen:"open.v1"` + OrgId string `protobuf:"bytes,1,opt,name=org_id,json=orgId,proto3" json:"org_id,omitempty"` + WorkspaceId string `protobuf:"bytes,2,opt,name=workspace_id,json=workspaceId,proto3" json:"workspace_id,omitempty"` + Role string `protobuf:"bytes,3,opt,name=role,proto3" json:"role,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *PrincipalMembership) Reset() { + *x = PrincipalMembership{} + mi := &file_state_v1_state_proto_msgTypes[184] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *PrincipalMembership) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*PrincipalMembership) ProtoMessage() {} + +func (x *PrincipalMembership) ProtoReflect() protoreflect.Message { + mi := &file_state_v1_state_proto_msgTypes[184] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use PrincipalMembership.ProtoReflect.Descriptor instead. +func (*PrincipalMembership) Descriptor() ([]byte, []int) { + return file_state_v1_state_proto_rawDescGZIP(), []int{184} +} + +func (x *PrincipalMembership) GetOrgId() string { + if x != nil { + return x.OrgId + } + return "" +} + +func (x *PrincipalMembership) GetWorkspaceId() string { + if x != nil { + return x.WorkspaceId + } + return "" +} + +func (x *PrincipalMembership) GetRole() string { + if x != nil { + return x.Role + } + return "" +} + +type AccessPrincipal struct { + state protoimpl.MessageState `protogen:"open.v1"` + IdentityId string `protobuf:"bytes,1,opt,name=identity_id,json=identityId,proto3" json:"identity_id,omitempty"` + OrgId string `protobuf:"bytes,2,opt,name=org_id,json=orgId,proto3" json:"org_id,omitempty"` + Memberships []*PrincipalMembership `protobuf:"bytes,3,rep,name=memberships,proto3" json:"memberships,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *AccessPrincipal) Reset() { + *x = AccessPrincipal{} + mi := &file_state_v1_state_proto_msgTypes[185] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *AccessPrincipal) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*AccessPrincipal) ProtoMessage() {} + +func (x *AccessPrincipal) ProtoReflect() protoreflect.Message { + mi := &file_state_v1_state_proto_msgTypes[185] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use AccessPrincipal.ProtoReflect.Descriptor instead. +func (*AccessPrincipal) Descriptor() ([]byte, []int) { + return file_state_v1_state_proto_rawDescGZIP(), []int{185} +} + +func (x *AccessPrincipal) GetIdentityId() string { + if x != nil { + return x.IdentityId + } + return "" +} + +func (x *AccessPrincipal) GetOrgId() string { + if x != nil { + return x.OrgId + } + return "" +} + +func (x *AccessPrincipal) GetMemberships() []*PrincipalMembership { + if x != nil { + return x.Memberships + } + return nil +} + +type GetPrincipalResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + Principal *AccessPrincipal `protobuf:"bytes,1,opt,name=principal,proto3" json:"principal,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *GetPrincipalResponse) Reset() { + *x = GetPrincipalResponse{} + mi := &file_state_v1_state_proto_msgTypes[186] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *GetPrincipalResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetPrincipalResponse) ProtoMessage() {} + +func (x *GetPrincipalResponse) ProtoReflect() protoreflect.Message { + mi := &file_state_v1_state_proto_msgTypes[186] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GetPrincipalResponse.ProtoReflect.Descriptor instead. +func (*GetPrincipalResponse) Descriptor() ([]byte, []int) { + return file_state_v1_state_proto_rawDescGZIP(), []int{186} +} + +func (x *GetPrincipalResponse) GetPrincipal() *AccessPrincipal { + if x != nil { + return x.Principal + } + return nil +} + +// AccessPolicy mirrors internal/domain/access.Policy: one Cedar policy +// document and the level-scope tuple that places it in the chain. +type AccessPolicy struct { + state protoimpl.MessageState `protogen:"open.v1"` + PolicyId string `protobuf:"bytes,1,opt,name=policy_id,json=policyId,proto3" json:"policy_id,omitempty"` + Level string `protobuf:"bytes,2,opt,name=level,proto3" json:"level,omitempty"` + OrgId string `protobuf:"bytes,3,opt,name=org_id,json=orgId,proto3" json:"org_id,omitempty"` + WorkspaceId string `protobuf:"bytes,4,opt,name=workspace_id,json=workspaceId,proto3" json:"workspace_id,omitempty"` + ObjectKind string `protobuf:"bytes,5,opt,name=object_kind,json=objectKind,proto3" json:"object_kind,omitempty"` + ObjectId string `protobuf:"bytes,6,opt,name=object_id,json=objectId,proto3" json:"object_id,omitempty"` + Text string `protobuf:"bytes,7,opt,name=text,proto3" json:"text,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *AccessPolicy) Reset() { + *x = AccessPolicy{} + mi := &file_state_v1_state_proto_msgTypes[187] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *AccessPolicy) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*AccessPolicy) ProtoMessage() {} + +func (x *AccessPolicy) ProtoReflect() protoreflect.Message { + mi := &file_state_v1_state_proto_msgTypes[187] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use AccessPolicy.ProtoReflect.Descriptor instead. +func (*AccessPolicy) Descriptor() ([]byte, []int) { + return file_state_v1_state_proto_rawDescGZIP(), []int{187} +} + +func (x *AccessPolicy) GetPolicyId() string { + if x != nil { + return x.PolicyId + } + return "" +} + +func (x *AccessPolicy) GetLevel() string { + if x != nil { + return x.Level + } + return "" +} + +func (x *AccessPolicy) GetOrgId() string { + if x != nil { + return x.OrgId + } + return "" +} + +func (x *AccessPolicy) GetWorkspaceId() string { + if x != nil { + return x.WorkspaceId + } + return "" +} + +func (x *AccessPolicy) GetObjectKind() string { + if x != nil { + return x.ObjectKind + } + return "" +} + +func (x *AccessPolicy) GetObjectId() string { + if x != nil { + return x.ObjectId + } + return "" +} + +func (x *AccessPolicy) GetText() string { + if x != nil { + return x.Text + } + return "" +} + +type ListPoliciesRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ListPoliciesRequest) Reset() { + *x = ListPoliciesRequest{} + mi := &file_state_v1_state_proto_msgTypes[188] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ListPoliciesRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ListPoliciesRequest) ProtoMessage() {} + +func (x *ListPoliciesRequest) ProtoReflect() protoreflect.Message { + mi := &file_state_v1_state_proto_msgTypes[188] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ListPoliciesRequest.ProtoReflect.Descriptor instead. +func (*ListPoliciesRequest) Descriptor() ([]byte, []int) { + return file_state_v1_state_proto_rawDescGZIP(), []int{188} +} + +type ListPoliciesResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + Policies []*AccessPolicy `protobuf:"bytes,1,rep,name=policies,proto3" json:"policies,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ListPoliciesResponse) Reset() { + *x = ListPoliciesResponse{} + mi := &file_state_v1_state_proto_msgTypes[189] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ListPoliciesResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ListPoliciesResponse) ProtoMessage() {} + +func (x *ListPoliciesResponse) ProtoReflect() protoreflect.Message { + mi := &file_state_v1_state_proto_msgTypes[189] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ListPoliciesResponse.ProtoReflect.Descriptor instead. +func (*ListPoliciesResponse) Descriptor() ([]byte, []int) { + return file_state_v1_state_proto_rawDescGZIP(), []int{189} +} + +func (x *ListPoliciesResponse) GetPolicies() []*AccessPolicy { + if x != nil { + return x.Policies + } + return nil +} + +type PutPolicyRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + Policy *AccessPolicy `protobuf:"bytes,1,opt,name=policy,proto3" json:"policy,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *PutPolicyRequest) Reset() { + *x = PutPolicyRequest{} + mi := &file_state_v1_state_proto_msgTypes[190] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *PutPolicyRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*PutPolicyRequest) ProtoMessage() {} + +func (x *PutPolicyRequest) ProtoReflect() protoreflect.Message { + mi := &file_state_v1_state_proto_msgTypes[190] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use PutPolicyRequest.ProtoReflect.Descriptor instead. +func (*PutPolicyRequest) Descriptor() ([]byte, []int) { + return file_state_v1_state_proto_rawDescGZIP(), []int{190} +} + +func (x *PutPolicyRequest) GetPolicy() *AccessPolicy { + if x != nil { + return x.Policy + } + return nil +} + +type PutPolicyResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + Version int64 `protobuf:"varint,1,opt,name=version,proto3" json:"version,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *PutPolicyResponse) Reset() { + *x = PutPolicyResponse{} + mi := &file_state_v1_state_proto_msgTypes[191] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *PutPolicyResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*PutPolicyResponse) ProtoMessage() {} + +func (x *PutPolicyResponse) ProtoReflect() protoreflect.Message { + mi := &file_state_v1_state_proto_msgTypes[191] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use PutPolicyResponse.ProtoReflect.Descriptor instead. +func (*PutPolicyResponse) Descriptor() ([]byte, []int) { + return file_state_v1_state_proto_rawDescGZIP(), []int{191} +} + +func (x *PutPolicyResponse) GetVersion() int64 { + if x != nil { + return x.Version + } + return 0 +} + +type DeletePolicyRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + Policy *AccessPolicy `protobuf:"bytes,1,opt,name=policy,proto3" json:"policy,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *DeletePolicyRequest) Reset() { + *x = DeletePolicyRequest{} + mi := &file_state_v1_state_proto_msgTypes[192] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *DeletePolicyRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*DeletePolicyRequest) ProtoMessage() {} + +func (x *DeletePolicyRequest) ProtoReflect() protoreflect.Message { + mi := &file_state_v1_state_proto_msgTypes[192] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use DeletePolicyRequest.ProtoReflect.Descriptor instead. +func (*DeletePolicyRequest) Descriptor() ([]byte, []int) { + return file_state_v1_state_proto_rawDescGZIP(), []int{192} +} + +func (x *DeletePolicyRequest) GetPolicy() *AccessPolicy { + if x != nil { + return x.Policy + } + return nil +} + +type DeletePolicyResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *DeletePolicyResponse) Reset() { + *x = DeletePolicyResponse{} + mi := &file_state_v1_state_proto_msgTypes[193] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *DeletePolicyResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*DeletePolicyResponse) ProtoMessage() {} + +func (x *DeletePolicyResponse) ProtoReflect() protoreflect.Message { + mi := &file_state_v1_state_proto_msgTypes[193] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use DeletePolicyResponse.ProtoReflect.Descriptor instead. +func (*DeletePolicyResponse) Descriptor() ([]byte, []int) { + return file_state_v1_state_proto_rawDescGZIP(), []int{193} +} + +type EnsureShippedOrgPoliciesRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + OrgId string `protobuf:"bytes,1,opt,name=org_id,json=orgId,proto3" json:"org_id,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *EnsureShippedOrgPoliciesRequest) Reset() { + *x = EnsureShippedOrgPoliciesRequest{} + mi := &file_state_v1_state_proto_msgTypes[194] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *EnsureShippedOrgPoliciesRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*EnsureShippedOrgPoliciesRequest) ProtoMessage() {} + +func (x *EnsureShippedOrgPoliciesRequest) ProtoReflect() protoreflect.Message { + mi := &file_state_v1_state_proto_msgTypes[194] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use EnsureShippedOrgPoliciesRequest.ProtoReflect.Descriptor instead. +func (*EnsureShippedOrgPoliciesRequest) Descriptor() ([]byte, []int) { + return file_state_v1_state_proto_rawDescGZIP(), []int{194} +} + +func (x *EnsureShippedOrgPoliciesRequest) GetOrgId() string { + if x != nil { + return x.OrgId + } + return "" +} + +type EnsureShippedOrgPoliciesResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *EnsureShippedOrgPoliciesResponse) Reset() { + *x = EnsureShippedOrgPoliciesResponse{} + mi := &file_state_v1_state_proto_msgTypes[195] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *EnsureShippedOrgPoliciesResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*EnsureShippedOrgPoliciesResponse) ProtoMessage() {} + +func (x *EnsureShippedOrgPoliciesResponse) ProtoReflect() protoreflect.Message { + mi := &file_state_v1_state_proto_msgTypes[195] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use EnsureShippedOrgPoliciesResponse.ProtoReflect.Descriptor instead. +func (*EnsureShippedOrgPoliciesResponse) Descriptor() ([]byte, []int) { + return file_state_v1_state_proto_rawDescGZIP(), []int{195} +} + +// AccessDenial mirrors internal/domain/access.Denial: one refusal with the +// level that decided it and the deciding policies. The store coalesces +// identical denials within a minute into one row with a count. +type AccessDenial struct { + state protoimpl.MessageState `protogen:"open.v1"` + OrgId string `protobuf:"bytes,1,opt,name=org_id,json=orgId,proto3" json:"org_id,omitempty"` + Principal string `protobuf:"bytes,2,opt,name=principal,proto3" json:"principal,omitempty"` + Action string `protobuf:"bytes,3,opt,name=action,proto3" json:"action,omitempty"` + ResourceKind string `protobuf:"bytes,4,opt,name=resource_kind,json=resourceKind,proto3" json:"resource_kind,omitempty"` + ResourceId string `protobuf:"bytes,5,opt,name=resource_id,json=resourceId,proto3" json:"resource_id,omitempty"` + Level string `protobuf:"bytes,6,opt,name=level,proto3" json:"level,omitempty"` + Policies []string `protobuf:"bytes,7,rep,name=policies,proto3" json:"policies,omitempty"` + Count int64 `protobuf:"varint,8,opt,name=count,proto3" json:"count,omitempty"` + At *timestamppb.Timestamp `protobuf:"bytes,9,opt,name=at,proto3" json:"at,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *AccessDenial) Reset() { + *x = AccessDenial{} + mi := &file_state_v1_state_proto_msgTypes[196] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *AccessDenial) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*AccessDenial) ProtoMessage() {} + +func (x *AccessDenial) ProtoReflect() protoreflect.Message { + mi := &file_state_v1_state_proto_msgTypes[196] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use AccessDenial.ProtoReflect.Descriptor instead. +func (*AccessDenial) Descriptor() ([]byte, []int) { + return file_state_v1_state_proto_rawDescGZIP(), []int{196} +} + +func (x *AccessDenial) GetOrgId() string { + if x != nil { + return x.OrgId + } + return "" +} + +func (x *AccessDenial) GetPrincipal() string { + if x != nil { + return x.Principal + } + return "" +} + +func (x *AccessDenial) GetAction() string { + if x != nil { + return x.Action + } + return "" +} + +func (x *AccessDenial) GetResourceKind() string { + if x != nil { + return x.ResourceKind + } + return "" +} + +func (x *AccessDenial) GetResourceId() string { + if x != nil { + return x.ResourceId + } + return "" +} + +func (x *AccessDenial) GetLevel() string { + if x != nil { + return x.Level + } + return "" +} + +func (x *AccessDenial) GetPolicies() []string { + if x != nil { + return x.Policies + } + return nil +} + +func (x *AccessDenial) GetCount() int64 { + if x != nil { + return x.Count + } + return 0 +} + +func (x *AccessDenial) GetAt() *timestamppb.Timestamp { + if x != nil { + return x.At + } + return nil +} + +type RecordDenialRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + Denial *AccessDenial `protobuf:"bytes,1,opt,name=denial,proto3" json:"denial,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *RecordDenialRequest) Reset() { + *x = RecordDenialRequest{} + mi := &file_state_v1_state_proto_msgTypes[197] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *RecordDenialRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*RecordDenialRequest) ProtoMessage() {} + +func (x *RecordDenialRequest) ProtoReflect() protoreflect.Message { + mi := &file_state_v1_state_proto_msgTypes[197] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use RecordDenialRequest.ProtoReflect.Descriptor instead. +func (*RecordDenialRequest) Descriptor() ([]byte, []int) { + return file_state_v1_state_proto_rawDescGZIP(), []int{197} +} + +func (x *RecordDenialRequest) GetDenial() *AccessDenial { + if x != nil { + return x.Denial + } + return nil +} + +type RecordDenialResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *RecordDenialResponse) Reset() { + *x = RecordDenialResponse{} + mi := &file_state_v1_state_proto_msgTypes[198] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *RecordDenialResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*RecordDenialResponse) ProtoMessage() {} + +func (x *RecordDenialResponse) ProtoReflect() protoreflect.Message { + mi := &file_state_v1_state_proto_msgTypes[198] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use RecordDenialResponse.ProtoReflect.Descriptor instead. +func (*RecordDenialResponse) Descriptor() ([]byte, []int) { + return file_state_v1_state_proto_rawDescGZIP(), []int{198} +} + +type ListDenialsRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + OrgId string `protobuf:"bytes,1,opt,name=org_id,json=orgId,proto3" json:"org_id,omitempty"` + Limit int32 `protobuf:"varint,2,opt,name=limit,proto3" json:"limit,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ListDenialsRequest) Reset() { + *x = ListDenialsRequest{} + mi := &file_state_v1_state_proto_msgTypes[199] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ListDenialsRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ListDenialsRequest) ProtoMessage() {} + +func (x *ListDenialsRequest) ProtoReflect() protoreflect.Message { + mi := &file_state_v1_state_proto_msgTypes[199] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ListDenialsRequest.ProtoReflect.Descriptor instead. +func (*ListDenialsRequest) Descriptor() ([]byte, []int) { + return file_state_v1_state_proto_rawDescGZIP(), []int{199} +} + +func (x *ListDenialsRequest) GetOrgId() string { + if x != nil { + return x.OrgId + } + return "" +} + +func (x *ListDenialsRequest) GetLimit() int32 { + if x != nil { + return x.Limit + } + return 0 +} + +type ListDenialsResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + Denials []*AccessDenial `protobuf:"bytes,1,rep,name=denials,proto3" json:"denials,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ListDenialsResponse) Reset() { + *x = ListDenialsResponse{} + mi := &file_state_v1_state_proto_msgTypes[200] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ListDenialsResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ListDenialsResponse) ProtoMessage() {} + +func (x *ListDenialsResponse) ProtoReflect() protoreflect.Message { + mi := &file_state_v1_state_proto_msgTypes[200] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ListDenialsResponse.ProtoReflect.Descriptor instead. +func (*ListDenialsResponse) Descriptor() ([]byte, []int) { + return file_state_v1_state_proto_rawDescGZIP(), []int{200} +} + +func (x *ListDenialsResponse) GetDenials() []*AccessDenial { + if x != nil { + return x.Denials + } + return nil +} + var File_state_v1_state_proto protoreflect.FileDescriptor const file_state_v1_state_proto_rawDesc = "" + @@ -10464,7 +11383,62 @@ const file_state_v1_state_proto_rawDesc = "" + "\x1dRemoveInstalledPackageRequest\x12\x15\n" + "\x06org_id\x18\x01 \x01(\tR\x05orgId\x12\x12\n" + "\x04name\x18\x02 \x01(\tR\x04name\" \n" + - "\x1eRemoveInstalledPackageResponse2\x8d6\n" + + "\x1eRemoveInstalledPackageResponse\"6\n" + + "\x13GetPrincipalRequest\x12\x1f\n" + + "\videntity_id\x18\x01 \x01(\tR\n" + + "identityId\"c\n" + + "\x13PrincipalMembership\x12\x15\n" + + "\x06org_id\x18\x01 \x01(\tR\x05orgId\x12!\n" + + "\fworkspace_id\x18\x02 \x01(\tR\vworkspaceId\x12\x12\n" + + "\x04role\x18\x03 \x01(\tR\x04role\"\x8a\x01\n" + + "\x0fAccessPrincipal\x12\x1f\n" + + "\videntity_id\x18\x01 \x01(\tR\n" + + "identityId\x12\x15\n" + + "\x06org_id\x18\x02 \x01(\tR\x05orgId\x12?\n" + + "\vmemberships\x18\x03 \x03(\v2\x1d.state.v1.PrincipalMembershipR\vmemberships\"O\n" + + "\x14GetPrincipalResponse\x127\n" + + "\tprincipal\x18\x01 \x01(\v2\x19.state.v1.AccessPrincipalR\tprincipal\"\xcd\x01\n" + + "\fAccessPolicy\x12\x1b\n" + + "\tpolicy_id\x18\x01 \x01(\tR\bpolicyId\x12\x14\n" + + "\x05level\x18\x02 \x01(\tR\x05level\x12\x15\n" + + "\x06org_id\x18\x03 \x01(\tR\x05orgId\x12!\n" + + "\fworkspace_id\x18\x04 \x01(\tR\vworkspaceId\x12\x1f\n" + + "\vobject_kind\x18\x05 \x01(\tR\n" + + "objectKind\x12\x1b\n" + + "\tobject_id\x18\x06 \x01(\tR\bobjectId\x12\x12\n" + + "\x04text\x18\a \x01(\tR\x04text\"\x15\n" + + "\x13ListPoliciesRequest\"J\n" + + "\x14ListPoliciesResponse\x122\n" + + "\bpolicies\x18\x01 \x03(\v2\x16.state.v1.AccessPolicyR\bpolicies\"B\n" + + "\x10PutPolicyRequest\x12.\n" + + "\x06policy\x18\x01 \x01(\v2\x16.state.v1.AccessPolicyR\x06policy\"-\n" + + "\x11PutPolicyResponse\x12\x18\n" + + "\aversion\x18\x01 \x01(\x03R\aversion\"E\n" + + "\x13DeletePolicyRequest\x12.\n" + + "\x06policy\x18\x01 \x01(\v2\x16.state.v1.AccessPolicyR\x06policy\"\x16\n" + + "\x14DeletePolicyResponse\"8\n" + + "\x1fEnsureShippedOrgPoliciesRequest\x12\x15\n" + + "\x06org_id\x18\x01 \x01(\tR\x05orgId\"\"\n" + + " EnsureShippedOrgPoliciesResponse\"\x95\x02\n" + + "\fAccessDenial\x12\x15\n" + + "\x06org_id\x18\x01 \x01(\tR\x05orgId\x12\x1c\n" + + "\tprincipal\x18\x02 \x01(\tR\tprincipal\x12\x16\n" + + "\x06action\x18\x03 \x01(\tR\x06action\x12#\n" + + "\rresource_kind\x18\x04 \x01(\tR\fresourceKind\x12\x1f\n" + + "\vresource_id\x18\x05 \x01(\tR\n" + + "resourceId\x12\x14\n" + + "\x05level\x18\x06 \x01(\tR\x05level\x12\x1a\n" + + "\bpolicies\x18\a \x03(\tR\bpolicies\x12\x14\n" + + "\x05count\x18\b \x01(\x03R\x05count\x12*\n" + + "\x02at\x18\t \x01(\v2\x1a.google.protobuf.TimestampR\x02at\"E\n" + + "\x13RecordDenialRequest\x12.\n" + + "\x06denial\x18\x01 \x01(\v2\x16.state.v1.AccessDenialR\x06denial\"\x16\n" + + "\x14RecordDenialResponse\"A\n" + + "\x12ListDenialsRequest\x12\x15\n" + + "\x06org_id\x18\x01 \x01(\tR\x05orgId\x12\x14\n" + + "\x05limit\x18\x02 \x01(\x05R\x05limit\"G\n" + + "\x13ListDenialsResponse\x120\n" + + "\adenials\x18\x01 \x03(\v2\x16.state.v1.AccessDenialR\adenials2\xce:\n" + "\x11StateStoreService\x12S\n" + "\x0eInstallPackage\x12\x1f.state.v1.InstallPackageRequest\x1a .state.v1.InstallPackageResponse\x12b\n" + "\x13GetInstalledPackage\x12$.state.v1.GetInstalledPackageRequest\x1a%.state.v1.GetInstalledPackageResponse\x12h\n" + @@ -10551,7 +11525,14 @@ const file_state_v1_state_proto_rawDesc = "" + "\x1aStreamUndispatchedCaptures\x12+.state.v1.StreamUndispatchedCapturesRequest\x1a,.state.v1.StreamUndispatchedCapturesResponse0\x01\x12_\n" + "\x12EnqueueBindingTask\x12#.state.v1.EnqueueBindingTaskRequest\x1a$.state.v1.EnqueueBindingTaskResponse\x12V\n" + "\x0fEnqueueCallTask\x12 .state.v1.EnqueueCallTaskRequest\x1a!.state.v1.EnqueueCallTaskResponse\x12_\n" + - "\x12WorkflowCallStatus\x12#.state.v1.WorkflowCallStatusRequest\x1a$.state.v1.WorkflowCallStatusResponseB\xa4\x01\n" + + "\x12WorkflowCallStatus\x12#.state.v1.WorkflowCallStatusRequest\x1a$.state.v1.WorkflowCallStatusResponse\x12M\n" + + "\fGetPrincipal\x12\x1d.state.v1.GetPrincipalRequest\x1a\x1e.state.v1.GetPrincipalResponse\x12M\n" + + "\fListPolicies\x12\x1d.state.v1.ListPoliciesRequest\x1a\x1e.state.v1.ListPoliciesResponse\x12D\n" + + "\tPutPolicy\x12\x1a.state.v1.PutPolicyRequest\x1a\x1b.state.v1.PutPolicyResponse\x12M\n" + + "\fDeletePolicy\x12\x1d.state.v1.DeletePolicyRequest\x1a\x1e.state.v1.DeletePolicyResponse\x12q\n" + + "\x18EnsureShippedOrgPolicies\x12).state.v1.EnsureShippedOrgPoliciesRequest\x1a*.state.v1.EnsureShippedOrgPoliciesResponse\x12M\n" + + "\fRecordDenial\x12\x1d.state.v1.RecordDenialRequest\x1a\x1e.state.v1.RecordDenialResponse\x12J\n" + + "\vListDenials\x12\x1c.state.v1.ListDenialsRequest\x1a\x1d.state.v1.ListDenialsResponseB\xa4\x01\n" + "\fcom.state.v1B\n" + "StateProtoP\x01ZGgithub.com/samcharles93/archie-core/internal/contracts/state/v1;statev1\xa2\x02\x03SXX\xaa\x02\bState.V1\xca\x02\bState\\V1\xe2\x02\x14State\\V1\\GPBMetadata\xea\x02\tState::V1b\x06proto3" @@ -10567,7 +11548,7 @@ func file_state_v1_state_proto_rawDescGZIP() []byte { return file_state_v1_state_proto_rawDescData } -var file_state_v1_state_proto_msgTypes = make([]protoimpl.MessageInfo, 185) +var file_state_v1_state_proto_msgTypes = make([]protoimpl.MessageInfo, 203) var file_state_v1_state_proto_goTypes = []any{ (*RegisterTaskGrantRequest)(nil), // 0: state.v1.RegisterTaskGrantRequest (*RegisterTaskGrantResponse)(nil), // 1: state.v1.RegisterTaskGrantResponse @@ -10752,13 +11733,31 @@ var file_state_v1_state_proto_goTypes = []any{ (*ListInstalledPackagesResponse)(nil), // 180: state.v1.ListInstalledPackagesResponse (*RemoveInstalledPackageRequest)(nil), // 181: state.v1.RemoveInstalledPackageRequest (*RemoveInstalledPackageResponse)(nil), // 182: state.v1.RemoveInstalledPackageResponse - nil, // 183: state.v1.EventType.SchemaEntry - nil, // 184: state.v1.StatusCountsResponse.CountsEntry - (*timestamppb.Timestamp)(nil), // 185: google.protobuf.Timestamp + (*GetPrincipalRequest)(nil), // 183: state.v1.GetPrincipalRequest + (*PrincipalMembership)(nil), // 184: state.v1.PrincipalMembership + (*AccessPrincipal)(nil), // 185: state.v1.AccessPrincipal + (*GetPrincipalResponse)(nil), // 186: state.v1.GetPrincipalResponse + (*AccessPolicy)(nil), // 187: state.v1.AccessPolicy + (*ListPoliciesRequest)(nil), // 188: state.v1.ListPoliciesRequest + (*ListPoliciesResponse)(nil), // 189: state.v1.ListPoliciesResponse + (*PutPolicyRequest)(nil), // 190: state.v1.PutPolicyRequest + (*PutPolicyResponse)(nil), // 191: state.v1.PutPolicyResponse + (*DeletePolicyRequest)(nil), // 192: state.v1.DeletePolicyRequest + (*DeletePolicyResponse)(nil), // 193: state.v1.DeletePolicyResponse + (*EnsureShippedOrgPoliciesRequest)(nil), // 194: state.v1.EnsureShippedOrgPoliciesRequest + (*EnsureShippedOrgPoliciesResponse)(nil), // 195: state.v1.EnsureShippedOrgPoliciesResponse + (*AccessDenial)(nil), // 196: state.v1.AccessDenial + (*RecordDenialRequest)(nil), // 197: state.v1.RecordDenialRequest + (*RecordDenialResponse)(nil), // 198: state.v1.RecordDenialResponse + (*ListDenialsRequest)(nil), // 199: state.v1.ListDenialsRequest + (*ListDenialsResponse)(nil), // 200: state.v1.ListDenialsResponse + nil, // 201: state.v1.EventType.SchemaEntry + nil, // 202: state.v1.StatusCountsResponse.CountsEntry + (*timestamppb.Timestamp)(nil), // 203: google.protobuf.Timestamp } var file_state_v1_state_proto_depIdxs = []int32{ - 185, // 0: state.v1.Identity.created_at:type_name -> google.protobuf.Timestamp - 185, // 1: state.v1.Identity.updated_at:type_name -> google.protobuf.Timestamp + 203, // 0: state.v1.Identity.created_at:type_name -> google.protobuf.Timestamp + 203, // 1: state.v1.Identity.updated_at:type_name -> google.protobuf.Timestamp 4, // 2: state.v1.ListIdentitiesResponse.identities:type_name -> state.v1.Identity 4, // 3: state.v1.GetIdentityResponse.identity:type_name -> state.v1.Identity 5, // 4: state.v1.CreateIdentityRequest.audit:type_name -> state.v1.IdentityAudit @@ -10774,24 +11773,24 @@ var file_state_v1_state_proto_depIdxs = []int32{ 4, // 14: state.v1.ResolveIdentitySubjectResponse.identity:type_name -> state.v1.Identity 5, // 15: state.v1.BindIdentitySubjectRequest.audit:type_name -> state.v1.IdentityAudit 4, // 16: state.v1.BindIdentitySubjectResponse.identity:type_name -> state.v1.Identity - 185, // 17: state.v1.Task.created_at:type_name -> google.protobuf.Timestamp - 185, // 18: state.v1.Task.updated_at:type_name -> google.protobuf.Timestamp - 185, // 19: state.v1.Event.at:type_name -> google.protobuf.Timestamp - 185, // 20: state.v1.CapturedEvent.received_at:type_name -> google.protobuf.Timestamp + 203, // 17: state.v1.Task.created_at:type_name -> google.protobuf.Timestamp + 203, // 18: state.v1.Task.updated_at:type_name -> google.protobuf.Timestamp + 203, // 19: state.v1.Event.at:type_name -> google.protobuf.Timestamp + 203, // 20: state.v1.CapturedEvent.received_at:type_name -> google.protobuf.Timestamp 27, // 21: state.v1.EventType.header_conditions:type_name -> state.v1.EventTypeHeaderCondition 28, // 22: state.v1.EventType.payload_conditions:type_name -> state.v1.EventTypePayloadCondition - 183, // 23: state.v1.EventType.schema:type_name -> state.v1.EventType.SchemaEntry - 185, // 24: state.v1.EventType.created_at:type_name -> google.protobuf.Timestamp - 185, // 25: state.v1.EventType.updated_at:type_name -> google.protobuf.Timestamp + 201, // 23: state.v1.EventType.schema:type_name -> state.v1.EventType.SchemaEntry + 203, // 24: state.v1.EventType.created_at:type_name -> google.protobuf.Timestamp + 203, // 25: state.v1.EventType.updated_at:type_name -> google.protobuf.Timestamp 30, // 26: state.v1.Mapping.fields:type_name -> state.v1.MappingField - 185, // 27: state.v1.Mapping.created_at:type_name -> google.protobuf.Timestamp - 185, // 28: state.v1.Mapping.updated_at:type_name -> google.protobuf.Timestamp - 185, // 29: state.v1.Mapping.last_matched_at:type_name -> google.protobuf.Timestamp + 203, // 27: state.v1.Mapping.created_at:type_name -> google.protobuf.Timestamp + 203, // 28: state.v1.Mapping.updated_at:type_name -> google.protobuf.Timestamp + 203, // 29: state.v1.Mapping.last_matched_at:type_name -> google.protobuf.Timestamp 32, // 30: state.v1.Binding.matcher:type_name -> state.v1.BindingMatcher - 185, // 31: state.v1.Binding.created_at:type_name -> google.protobuf.Timestamp - 185, // 32: state.v1.Binding.updated_at:type_name -> google.protobuf.Timestamp - 185, // 33: state.v1.Source.created_at:type_name -> google.protobuf.Timestamp - 185, // 34: state.v1.Source.updated_at:type_name -> google.protobuf.Timestamp + 203, // 31: state.v1.Binding.created_at:type_name -> google.protobuf.Timestamp + 203, // 32: state.v1.Binding.updated_at:type_name -> google.protobuf.Timestamp + 203, // 33: state.v1.Source.created_at:type_name -> google.protobuf.Timestamp + 203, // 34: state.v1.Source.updated_at:type_name -> google.protobuf.Timestamp 24, // 35: state.v1.EnqueueChatTaskResponse.task:type_name -> state.v1.Task 24, // 36: state.v1.ClaimNextResponse.task:type_name -> state.v1.Task 24, // 37: state.v1.ClaimByIssueResponse.task:type_name -> state.v1.Task @@ -10802,25 +11801,25 @@ var file_state_v1_state_proto_depIdxs = []int32{ 24, // 42: state.v1.TaskByIDResponse.task:type_name -> state.v1.Task 24, // 43: state.v1.OpenPRsResponse.tasks:type_name -> state.v1.Task 24, // 44: state.v1.TasksResponse.tasks:type_name -> state.v1.Task - 184, // 45: state.v1.StatusCountsResponse.counts:type_name -> state.v1.StatusCountsResponse.CountsEntry + 202, // 45: state.v1.StatusCountsResponse.counts:type_name -> state.v1.StatusCountsResponse.CountsEntry 25, // 46: state.v1.InsertEventRequest.event:type_name -> state.v1.Event 25, // 47: state.v1.EventsSinceResponse.events:type_name -> state.v1.Event 25, // 48: state.v1.TaskEventsResponse.events:type_name -> state.v1.Event 35, // 49: state.v1.WorkflowStatsResponse.stats:type_name -> state.v1.WorkflowStat 36, // 50: state.v1.StageStatsResponse.stats:type_name -> state.v1.StageStat 37, // 51: state.v1.TokensByDayResponse.tokens:type_name -> state.v1.DayTokens - 185, // 52: state.v1.ConfigSnapshot.published_at:type_name -> google.protobuf.Timestamp + 203, // 52: state.v1.ConfigSnapshot.published_at:type_name -> google.protobuf.Timestamp 92, // 53: state.v1.PutConfigSnapshotRequest.snapshot:type_name -> state.v1.ConfigSnapshot 92, // 54: state.v1.GetConfigSnapshotResponse.snapshot:type_name -> state.v1.ConfigSnapshot - 185, // 55: state.v1.ChannelStatus.observed_at:type_name -> google.protobuf.Timestamp + 203, // 55: state.v1.ChannelStatus.observed_at:type_name -> google.protobuf.Timestamp 97, // 56: state.v1.PutChannelStatusRequest.channels:type_name -> state.v1.ChannelStatus 97, // 57: state.v1.ListChannelStatusResponse.channels:type_name -> state.v1.ChannelStatus - 185, // 58: state.v1.ApplyStatus.reported_at:type_name -> google.protobuf.Timestamp + 203, // 58: state.v1.ApplyStatus.reported_at:type_name -> google.protobuf.Timestamp 102, // 59: state.v1.PutApplyStatusRequest.status:type_name -> state.v1.ApplyStatus 102, // 60: state.v1.ListApplyStatusResponse.statuses:type_name -> state.v1.ApplyStatus - 185, // 61: state.v1.TaskLogEntry.time:type_name -> google.protobuf.Timestamp - 185, // 62: state.v1.ReadTaskLogRequest.since:type_name -> google.protobuf.Timestamp - 185, // 63: state.v1.ReadTaskLogRequest.until:type_name -> google.protobuf.Timestamp + 203, // 61: state.v1.TaskLogEntry.time:type_name -> google.protobuf.Timestamp + 203, // 62: state.v1.ReadTaskLogRequest.since:type_name -> google.protobuf.Timestamp + 203, // 63: state.v1.ReadTaskLogRequest.until:type_name -> google.protobuf.Timestamp 107, // 64: state.v1.ReadTaskLogResponse.entries:type_name -> state.v1.TaskLogEntry 26, // 65: state.v1.InsertCaptureRequest.capture:type_name -> state.v1.CapturedEvent 26, // 66: state.v1.StreamCapturesResponse.capture:type_name -> state.v1.CapturedEvent @@ -10845,173 +11844,195 @@ var file_state_v1_state_proto_depIdxs = []int32{ 174, // 85: state.v1.InstallPackageResponse.package:type_name -> state.v1.InstalledPackage 174, // 86: state.v1.GetInstalledPackageResponse.package:type_name -> state.v1.InstalledPackage 174, // 87: state.v1.ListInstalledPackagesResponse.packages:type_name -> state.v1.InstalledPackage - 175, // 88: state.v1.StateStoreService.InstallPackage:input_type -> state.v1.InstallPackageRequest - 177, // 89: state.v1.StateStoreService.GetInstalledPackage:input_type -> state.v1.GetInstalledPackageRequest - 179, // 90: state.v1.StateStoreService.ListInstalledPackages:input_type -> state.v1.ListInstalledPackagesRequest - 181, // 91: state.v1.StateStoreService.RemoveInstalledPackage:input_type -> state.v1.RemoveInstalledPackageRequest - 0, // 92: state.v1.StateStoreService.RegisterTaskGrant:input_type -> state.v1.RegisterTaskGrantRequest - 2, // 93: state.v1.StateStoreService.RevokeTaskGrant:input_type -> state.v1.RevokeTaskGrantRequest - 6, // 94: state.v1.StateStoreService.ListIdentities:input_type -> state.v1.ListIdentitiesRequest - 8, // 95: state.v1.StateStoreService.GetIdentity:input_type -> state.v1.GetIdentityRequest - 10, // 96: state.v1.StateStoreService.CreateIdentity:input_type -> state.v1.CreateIdentityRequest - 11, // 97: state.v1.StateStoreService.RenameIdentity:input_type -> state.v1.RenameIdentityRequest - 12, // 98: state.v1.StateStoreService.SuspendIdentity:input_type -> state.v1.SuspendIdentityRequest - 13, // 99: state.v1.StateStoreService.ReactivateIdentity:input_type -> state.v1.ReactivateIdentityRequest - 14, // 100: state.v1.StateStoreService.RetireIdentity:input_type -> state.v1.RetireIdentityRequest - 20, // 101: state.v1.StateStoreService.ResolveIdentitySubject:input_type -> state.v1.ResolveIdentitySubjectRequest - 22, // 102: state.v1.StateStoreService.BindIdentitySubject:input_type -> state.v1.BindIdentitySubjectRequest - 38, // 103: state.v1.StateStoreService.EnqueueIssue:input_type -> state.v1.EnqueueIssueRequest - 40, // 104: state.v1.StateStoreService.EnqueueChatTask:input_type -> state.v1.EnqueueChatTaskRequest - 42, // 105: state.v1.StateStoreService.ClaimNext:input_type -> state.v1.ClaimNextRequest - 44, // 106: state.v1.StateStoreService.ClaimByIssue:input_type -> state.v1.ClaimByIssueRequest - 46, // 107: state.v1.StateStoreService.Transition:input_type -> state.v1.TransitionRequest - 48, // 108: state.v1.StateStoreService.Update:input_type -> state.v1.UpdateRequest - 50, // 109: state.v1.StateStoreService.Requeue:input_type -> state.v1.RequeueRequest - 52, // 110: state.v1.StateStoreService.ParkTask:input_type -> state.v1.ParkTaskRequest - 54, // 111: state.v1.StateStoreService.RecoverStale:input_type -> state.v1.RecoverStaleRequest - 56, // 112: state.v1.StateStoreService.ArchiveTask:input_type -> state.v1.ArchiveTaskRequest - 58, // 113: state.v1.StateStoreService.RetryTask:input_type -> state.v1.RetryTaskRequest - 60, // 114: state.v1.StateStoreService.BeginRemediation:input_type -> state.v1.BeginRemediationRequest - 62, // 115: state.v1.StateStoreService.UpdateReviewPayload:input_type -> state.v1.UpdateReviewPayloadRequest - 64, // 116: state.v1.StateStoreService.SetReviewCursors:input_type -> state.v1.SetReviewCursorsRequest - 66, // 117: state.v1.StateStoreService.TaskByIssue:input_type -> state.v1.TaskByIssueRequest - 68, // 118: state.v1.StateStoreService.OpenTaskByPR:input_type -> state.v1.OpenTaskByPRRequest - 70, // 119: state.v1.StateStoreService.TaskByID:input_type -> state.v1.TaskByIDRequest - 72, // 120: state.v1.StateStoreService.OpenPRs:input_type -> state.v1.OpenPRsRequest - 74, // 121: state.v1.StateStoreService.ClearTerminalTasks:input_type -> state.v1.ClearTerminalTasksRequest - 76, // 122: state.v1.StateStoreService.Tasks:input_type -> state.v1.TasksRequest - 78, // 123: state.v1.StateStoreService.StatusCounts:input_type -> state.v1.StatusCountsRequest - 80, // 124: state.v1.StateStoreService.InsertEvent:input_type -> state.v1.InsertEventRequest - 82, // 125: state.v1.StateStoreService.EventsSince:input_type -> state.v1.EventsSinceRequest - 84, // 126: state.v1.StateStoreService.TaskEvents:input_type -> state.v1.TaskEventsRequest - 86, // 127: state.v1.StateStoreService.WorkflowStats:input_type -> state.v1.WorkflowStatsRequest - 88, // 128: state.v1.StateStoreService.StageStats:input_type -> state.v1.StageStatsRequest - 90, // 129: state.v1.StateStoreService.TokensByDay:input_type -> state.v1.TokensByDayRequest - 93, // 130: state.v1.StateStoreService.PutConfigSnapshot:input_type -> state.v1.PutConfigSnapshotRequest - 95, // 131: state.v1.StateStoreService.GetConfigSnapshot:input_type -> state.v1.GetConfigSnapshotRequest - 98, // 132: state.v1.StateStoreService.PutChannelStatus:input_type -> state.v1.PutChannelStatusRequest - 100, // 133: state.v1.StateStoreService.ListChannelStatus:input_type -> state.v1.ListChannelStatusRequest - 103, // 134: state.v1.StateStoreService.PutApplyStatus:input_type -> state.v1.PutApplyStatusRequest - 105, // 135: state.v1.StateStoreService.ListApplyStatus:input_type -> state.v1.ListApplyStatusRequest - 108, // 136: state.v1.StateStoreService.ReadTaskLog:input_type -> state.v1.ReadTaskLogRequest - 110, // 137: state.v1.StateStoreService.StreamTaskLogContent:input_type -> state.v1.StreamTaskLogContentRequest - 112, // 138: state.v1.StateStoreService.InsertCapture:input_type -> state.v1.InsertCaptureRequest - 114, // 139: state.v1.StateStoreService.StreamCaptures:input_type -> state.v1.StreamCapturesRequest - 116, // 140: state.v1.StateStoreService.InsertMapping:input_type -> state.v1.InsertMappingRequest - 118, // 141: state.v1.StateStoreService.GetMapping:input_type -> state.v1.GetMappingRequest - 120, // 142: state.v1.StateStoreService.ListMappings:input_type -> state.v1.ListMappingsRequest - 122, // 143: state.v1.StateStoreService.UpdateMapping:input_type -> state.v1.UpdateMappingRequest - 124, // 144: state.v1.StateStoreService.DeleteMapping:input_type -> state.v1.DeleteMappingRequest - 126, // 145: state.v1.StateStoreService.RecordMappingMatch:input_type -> state.v1.RecordMappingMatchRequest - 128, // 146: state.v1.StateStoreService.InsertEventType:input_type -> state.v1.InsertEventTypeRequest - 130, // 147: state.v1.StateStoreService.UpdateEventType:input_type -> state.v1.UpdateEventTypeRequest - 132, // 148: state.v1.StateStoreService.DeleteEventType:input_type -> state.v1.DeleteEventTypeRequest - 134, // 149: state.v1.StateStoreService.ListEventTypes:input_type -> state.v1.ListEventTypesRequest - 136, // 150: state.v1.StateStoreService.InsertBinding:input_type -> state.v1.InsertBindingRequest - 138, // 151: state.v1.StateStoreService.GetBinding:input_type -> state.v1.GetBindingRequest - 140, // 152: state.v1.StateStoreService.ListBindings:input_type -> state.v1.ListBindingsRequest - 142, // 153: state.v1.StateStoreService.UpdateBinding:input_type -> state.v1.UpdateBindingRequest - 144, // 154: state.v1.StateStoreService.DeleteBinding:input_type -> state.v1.DeleteBindingRequest - 146, // 155: state.v1.StateStoreService.ApproveBinding:input_type -> state.v1.ApproveBindingRequest - 148, // 156: state.v1.StateStoreService.InsertSource:input_type -> state.v1.InsertSourceRequest - 150, // 157: state.v1.StateStoreService.GetSource:input_type -> state.v1.GetSourceRequest - 152, // 158: state.v1.StateStoreService.ListSources:input_type -> state.v1.ListSourcesRequest - 154, // 159: state.v1.StateStoreService.SetSourceSigning:input_type -> state.v1.SetSourceSigningRequest - 156, // 160: state.v1.StateStoreService.SetSourceSecret:input_type -> state.v1.SetSourceSecretRequest - 158, // 161: state.v1.StateStoreService.ArmedBindingsForSource:input_type -> state.v1.ArmedBindingsForSourceRequest - 160, // 162: state.v1.StateStoreService.RecordDispatch:input_type -> state.v1.RecordDispatchRequest - 162, // 163: state.v1.StateStoreService.RecordPlaybookDispatch:input_type -> state.v1.RecordPlaybookDispatchRequest - 164, // 164: state.v1.StateStoreService.DeletePlaybookDispatches:input_type -> state.v1.DeletePlaybookDispatchesRequest - 166, // 165: state.v1.StateStoreService.StreamUndispatchedCaptures:input_type -> state.v1.StreamUndispatchedCapturesRequest - 168, // 166: state.v1.StateStoreService.EnqueueBindingTask:input_type -> state.v1.EnqueueBindingTaskRequest - 170, // 167: state.v1.StateStoreService.EnqueueCallTask:input_type -> state.v1.EnqueueCallTaskRequest - 172, // 168: state.v1.StateStoreService.WorkflowCallStatus:input_type -> state.v1.WorkflowCallStatusRequest - 176, // 169: state.v1.StateStoreService.InstallPackage:output_type -> state.v1.InstallPackageResponse - 178, // 170: state.v1.StateStoreService.GetInstalledPackage:output_type -> state.v1.GetInstalledPackageResponse - 180, // 171: state.v1.StateStoreService.ListInstalledPackages:output_type -> state.v1.ListInstalledPackagesResponse - 182, // 172: state.v1.StateStoreService.RemoveInstalledPackage:output_type -> state.v1.RemoveInstalledPackageResponse - 1, // 173: state.v1.StateStoreService.RegisterTaskGrant:output_type -> state.v1.RegisterTaskGrantResponse - 3, // 174: state.v1.StateStoreService.RevokeTaskGrant:output_type -> state.v1.RevokeTaskGrantResponse - 7, // 175: state.v1.StateStoreService.ListIdentities:output_type -> state.v1.ListIdentitiesResponse - 9, // 176: state.v1.StateStoreService.GetIdentity:output_type -> state.v1.GetIdentityResponse - 15, // 177: state.v1.StateStoreService.CreateIdentity:output_type -> state.v1.CreateIdentityResponse - 16, // 178: state.v1.StateStoreService.RenameIdentity:output_type -> state.v1.RenameIdentityResponse - 17, // 179: state.v1.StateStoreService.SuspendIdentity:output_type -> state.v1.SuspendIdentityResponse - 18, // 180: state.v1.StateStoreService.ReactivateIdentity:output_type -> state.v1.ReactivateIdentityResponse - 19, // 181: state.v1.StateStoreService.RetireIdentity:output_type -> state.v1.RetireIdentityResponse - 21, // 182: state.v1.StateStoreService.ResolveIdentitySubject:output_type -> state.v1.ResolveIdentitySubjectResponse - 23, // 183: state.v1.StateStoreService.BindIdentitySubject:output_type -> state.v1.BindIdentitySubjectResponse - 39, // 184: state.v1.StateStoreService.EnqueueIssue:output_type -> state.v1.EnqueueIssueResponse - 41, // 185: state.v1.StateStoreService.EnqueueChatTask:output_type -> state.v1.EnqueueChatTaskResponse - 43, // 186: state.v1.StateStoreService.ClaimNext:output_type -> state.v1.ClaimNextResponse - 45, // 187: state.v1.StateStoreService.ClaimByIssue:output_type -> state.v1.ClaimByIssueResponse - 47, // 188: state.v1.StateStoreService.Transition:output_type -> state.v1.TransitionResponse - 49, // 189: state.v1.StateStoreService.Update:output_type -> state.v1.UpdateResponse - 51, // 190: state.v1.StateStoreService.Requeue:output_type -> state.v1.RequeueResponse - 53, // 191: state.v1.StateStoreService.ParkTask:output_type -> state.v1.ParkTaskResponse - 55, // 192: state.v1.StateStoreService.RecoverStale:output_type -> state.v1.RecoverStaleResponse - 57, // 193: state.v1.StateStoreService.ArchiveTask:output_type -> state.v1.ArchiveTaskResponse - 59, // 194: state.v1.StateStoreService.RetryTask:output_type -> state.v1.RetryTaskResponse - 61, // 195: state.v1.StateStoreService.BeginRemediation:output_type -> state.v1.BeginRemediationResponse - 63, // 196: state.v1.StateStoreService.UpdateReviewPayload:output_type -> state.v1.UpdateReviewPayloadResponse - 65, // 197: state.v1.StateStoreService.SetReviewCursors:output_type -> state.v1.SetReviewCursorsResponse - 67, // 198: state.v1.StateStoreService.TaskByIssue:output_type -> state.v1.TaskByIssueResponse - 69, // 199: state.v1.StateStoreService.OpenTaskByPR:output_type -> state.v1.OpenTaskByPRResponse - 71, // 200: state.v1.StateStoreService.TaskByID:output_type -> state.v1.TaskByIDResponse - 73, // 201: state.v1.StateStoreService.OpenPRs:output_type -> state.v1.OpenPRsResponse - 75, // 202: state.v1.StateStoreService.ClearTerminalTasks:output_type -> state.v1.ClearTerminalTasksResponse - 77, // 203: state.v1.StateStoreService.Tasks:output_type -> state.v1.TasksResponse - 79, // 204: state.v1.StateStoreService.StatusCounts:output_type -> state.v1.StatusCountsResponse - 81, // 205: state.v1.StateStoreService.InsertEvent:output_type -> state.v1.InsertEventResponse - 83, // 206: state.v1.StateStoreService.EventsSince:output_type -> state.v1.EventsSinceResponse - 85, // 207: state.v1.StateStoreService.TaskEvents:output_type -> state.v1.TaskEventsResponse - 87, // 208: state.v1.StateStoreService.WorkflowStats:output_type -> state.v1.WorkflowStatsResponse - 89, // 209: state.v1.StateStoreService.StageStats:output_type -> state.v1.StageStatsResponse - 91, // 210: state.v1.StateStoreService.TokensByDay:output_type -> state.v1.TokensByDayResponse - 94, // 211: state.v1.StateStoreService.PutConfigSnapshot:output_type -> state.v1.PutConfigSnapshotResponse - 96, // 212: state.v1.StateStoreService.GetConfigSnapshot:output_type -> state.v1.GetConfigSnapshotResponse - 99, // 213: state.v1.StateStoreService.PutChannelStatus:output_type -> state.v1.PutChannelStatusResponse - 101, // 214: state.v1.StateStoreService.ListChannelStatus:output_type -> state.v1.ListChannelStatusResponse - 104, // 215: state.v1.StateStoreService.PutApplyStatus:output_type -> state.v1.PutApplyStatusResponse - 106, // 216: state.v1.StateStoreService.ListApplyStatus:output_type -> state.v1.ListApplyStatusResponse - 109, // 217: state.v1.StateStoreService.ReadTaskLog:output_type -> state.v1.ReadTaskLogResponse - 111, // 218: state.v1.StateStoreService.StreamTaskLogContent:output_type -> state.v1.StreamTaskLogContentResponse - 113, // 219: state.v1.StateStoreService.InsertCapture:output_type -> state.v1.InsertCaptureResponse - 115, // 220: state.v1.StateStoreService.StreamCaptures:output_type -> state.v1.StreamCapturesResponse - 117, // 221: state.v1.StateStoreService.InsertMapping:output_type -> state.v1.InsertMappingResponse - 119, // 222: state.v1.StateStoreService.GetMapping:output_type -> state.v1.GetMappingResponse - 121, // 223: state.v1.StateStoreService.ListMappings:output_type -> state.v1.ListMappingsResponse - 123, // 224: state.v1.StateStoreService.UpdateMapping:output_type -> state.v1.UpdateMappingResponse - 125, // 225: state.v1.StateStoreService.DeleteMapping:output_type -> state.v1.DeleteMappingResponse - 127, // 226: state.v1.StateStoreService.RecordMappingMatch:output_type -> state.v1.RecordMappingMatchResponse - 129, // 227: state.v1.StateStoreService.InsertEventType:output_type -> state.v1.InsertEventTypeResponse - 131, // 228: state.v1.StateStoreService.UpdateEventType:output_type -> state.v1.UpdateEventTypeResponse - 133, // 229: state.v1.StateStoreService.DeleteEventType:output_type -> state.v1.DeleteEventTypeResponse - 135, // 230: state.v1.StateStoreService.ListEventTypes:output_type -> state.v1.ListEventTypesResponse - 137, // 231: state.v1.StateStoreService.InsertBinding:output_type -> state.v1.InsertBindingResponse - 139, // 232: state.v1.StateStoreService.GetBinding:output_type -> state.v1.GetBindingResponse - 141, // 233: state.v1.StateStoreService.ListBindings:output_type -> state.v1.ListBindingsResponse - 143, // 234: state.v1.StateStoreService.UpdateBinding:output_type -> state.v1.UpdateBindingResponse - 145, // 235: state.v1.StateStoreService.DeleteBinding:output_type -> state.v1.DeleteBindingResponse - 147, // 236: state.v1.StateStoreService.ApproveBinding:output_type -> state.v1.ApproveBindingResponse - 149, // 237: state.v1.StateStoreService.InsertSource:output_type -> state.v1.InsertSourceResponse - 151, // 238: state.v1.StateStoreService.GetSource:output_type -> state.v1.GetSourceResponse - 153, // 239: state.v1.StateStoreService.ListSources:output_type -> state.v1.ListSourcesResponse - 155, // 240: state.v1.StateStoreService.SetSourceSigning:output_type -> state.v1.SetSourceSigningResponse - 157, // 241: state.v1.StateStoreService.SetSourceSecret:output_type -> state.v1.SetSourceSecretResponse - 159, // 242: state.v1.StateStoreService.ArmedBindingsForSource:output_type -> state.v1.ArmedBindingsForSourceResponse - 161, // 243: state.v1.StateStoreService.RecordDispatch:output_type -> state.v1.RecordDispatchResponse - 163, // 244: state.v1.StateStoreService.RecordPlaybookDispatch:output_type -> state.v1.RecordPlaybookDispatchResponse - 165, // 245: state.v1.StateStoreService.DeletePlaybookDispatches:output_type -> state.v1.DeletePlaybookDispatchesResponse - 167, // 246: state.v1.StateStoreService.StreamUndispatchedCaptures:output_type -> state.v1.StreamUndispatchedCapturesResponse - 169, // 247: state.v1.StateStoreService.EnqueueBindingTask:output_type -> state.v1.EnqueueBindingTaskResponse - 171, // 248: state.v1.StateStoreService.EnqueueCallTask:output_type -> state.v1.EnqueueCallTaskResponse - 173, // 249: state.v1.StateStoreService.WorkflowCallStatus:output_type -> state.v1.WorkflowCallStatusResponse - 169, // [169:250] is the sub-list for method output_type - 88, // [88:169] is the sub-list for method input_type - 88, // [88:88] is the sub-list for extension type_name - 88, // [88:88] is the sub-list for extension extendee - 0, // [0:88] is the sub-list for field type_name + 184, // 88: state.v1.AccessPrincipal.memberships:type_name -> state.v1.PrincipalMembership + 185, // 89: state.v1.GetPrincipalResponse.principal:type_name -> state.v1.AccessPrincipal + 187, // 90: state.v1.ListPoliciesResponse.policies:type_name -> state.v1.AccessPolicy + 187, // 91: state.v1.PutPolicyRequest.policy:type_name -> state.v1.AccessPolicy + 187, // 92: state.v1.DeletePolicyRequest.policy:type_name -> state.v1.AccessPolicy + 203, // 93: state.v1.AccessDenial.at:type_name -> google.protobuf.Timestamp + 196, // 94: state.v1.RecordDenialRequest.denial:type_name -> state.v1.AccessDenial + 196, // 95: state.v1.ListDenialsResponse.denials:type_name -> state.v1.AccessDenial + 175, // 96: state.v1.StateStoreService.InstallPackage:input_type -> state.v1.InstallPackageRequest + 177, // 97: state.v1.StateStoreService.GetInstalledPackage:input_type -> state.v1.GetInstalledPackageRequest + 179, // 98: state.v1.StateStoreService.ListInstalledPackages:input_type -> state.v1.ListInstalledPackagesRequest + 181, // 99: state.v1.StateStoreService.RemoveInstalledPackage:input_type -> state.v1.RemoveInstalledPackageRequest + 0, // 100: state.v1.StateStoreService.RegisterTaskGrant:input_type -> state.v1.RegisterTaskGrantRequest + 2, // 101: state.v1.StateStoreService.RevokeTaskGrant:input_type -> state.v1.RevokeTaskGrantRequest + 6, // 102: state.v1.StateStoreService.ListIdentities:input_type -> state.v1.ListIdentitiesRequest + 8, // 103: state.v1.StateStoreService.GetIdentity:input_type -> state.v1.GetIdentityRequest + 10, // 104: state.v1.StateStoreService.CreateIdentity:input_type -> state.v1.CreateIdentityRequest + 11, // 105: state.v1.StateStoreService.RenameIdentity:input_type -> state.v1.RenameIdentityRequest + 12, // 106: state.v1.StateStoreService.SuspendIdentity:input_type -> state.v1.SuspendIdentityRequest + 13, // 107: state.v1.StateStoreService.ReactivateIdentity:input_type -> state.v1.ReactivateIdentityRequest + 14, // 108: state.v1.StateStoreService.RetireIdentity:input_type -> state.v1.RetireIdentityRequest + 20, // 109: state.v1.StateStoreService.ResolveIdentitySubject:input_type -> state.v1.ResolveIdentitySubjectRequest + 22, // 110: state.v1.StateStoreService.BindIdentitySubject:input_type -> state.v1.BindIdentitySubjectRequest + 38, // 111: state.v1.StateStoreService.EnqueueIssue:input_type -> state.v1.EnqueueIssueRequest + 40, // 112: state.v1.StateStoreService.EnqueueChatTask:input_type -> state.v1.EnqueueChatTaskRequest + 42, // 113: state.v1.StateStoreService.ClaimNext:input_type -> state.v1.ClaimNextRequest + 44, // 114: state.v1.StateStoreService.ClaimByIssue:input_type -> state.v1.ClaimByIssueRequest + 46, // 115: state.v1.StateStoreService.Transition:input_type -> state.v1.TransitionRequest + 48, // 116: state.v1.StateStoreService.Update:input_type -> state.v1.UpdateRequest + 50, // 117: state.v1.StateStoreService.Requeue:input_type -> state.v1.RequeueRequest + 52, // 118: state.v1.StateStoreService.ParkTask:input_type -> state.v1.ParkTaskRequest + 54, // 119: state.v1.StateStoreService.RecoverStale:input_type -> state.v1.RecoverStaleRequest + 56, // 120: state.v1.StateStoreService.ArchiveTask:input_type -> state.v1.ArchiveTaskRequest + 58, // 121: state.v1.StateStoreService.RetryTask:input_type -> state.v1.RetryTaskRequest + 60, // 122: state.v1.StateStoreService.BeginRemediation:input_type -> state.v1.BeginRemediationRequest + 62, // 123: state.v1.StateStoreService.UpdateReviewPayload:input_type -> state.v1.UpdateReviewPayloadRequest + 64, // 124: state.v1.StateStoreService.SetReviewCursors:input_type -> state.v1.SetReviewCursorsRequest + 66, // 125: state.v1.StateStoreService.TaskByIssue:input_type -> state.v1.TaskByIssueRequest + 68, // 126: state.v1.StateStoreService.OpenTaskByPR:input_type -> state.v1.OpenTaskByPRRequest + 70, // 127: state.v1.StateStoreService.TaskByID:input_type -> state.v1.TaskByIDRequest + 72, // 128: state.v1.StateStoreService.OpenPRs:input_type -> state.v1.OpenPRsRequest + 74, // 129: state.v1.StateStoreService.ClearTerminalTasks:input_type -> state.v1.ClearTerminalTasksRequest + 76, // 130: state.v1.StateStoreService.Tasks:input_type -> state.v1.TasksRequest + 78, // 131: state.v1.StateStoreService.StatusCounts:input_type -> state.v1.StatusCountsRequest + 80, // 132: state.v1.StateStoreService.InsertEvent:input_type -> state.v1.InsertEventRequest + 82, // 133: state.v1.StateStoreService.EventsSince:input_type -> state.v1.EventsSinceRequest + 84, // 134: state.v1.StateStoreService.TaskEvents:input_type -> state.v1.TaskEventsRequest + 86, // 135: state.v1.StateStoreService.WorkflowStats:input_type -> state.v1.WorkflowStatsRequest + 88, // 136: state.v1.StateStoreService.StageStats:input_type -> state.v1.StageStatsRequest + 90, // 137: state.v1.StateStoreService.TokensByDay:input_type -> state.v1.TokensByDayRequest + 93, // 138: state.v1.StateStoreService.PutConfigSnapshot:input_type -> state.v1.PutConfigSnapshotRequest + 95, // 139: state.v1.StateStoreService.GetConfigSnapshot:input_type -> state.v1.GetConfigSnapshotRequest + 98, // 140: state.v1.StateStoreService.PutChannelStatus:input_type -> state.v1.PutChannelStatusRequest + 100, // 141: state.v1.StateStoreService.ListChannelStatus:input_type -> state.v1.ListChannelStatusRequest + 103, // 142: state.v1.StateStoreService.PutApplyStatus:input_type -> state.v1.PutApplyStatusRequest + 105, // 143: state.v1.StateStoreService.ListApplyStatus:input_type -> state.v1.ListApplyStatusRequest + 108, // 144: state.v1.StateStoreService.ReadTaskLog:input_type -> state.v1.ReadTaskLogRequest + 110, // 145: state.v1.StateStoreService.StreamTaskLogContent:input_type -> state.v1.StreamTaskLogContentRequest + 112, // 146: state.v1.StateStoreService.InsertCapture:input_type -> state.v1.InsertCaptureRequest + 114, // 147: state.v1.StateStoreService.StreamCaptures:input_type -> state.v1.StreamCapturesRequest + 116, // 148: state.v1.StateStoreService.InsertMapping:input_type -> state.v1.InsertMappingRequest + 118, // 149: state.v1.StateStoreService.GetMapping:input_type -> state.v1.GetMappingRequest + 120, // 150: state.v1.StateStoreService.ListMappings:input_type -> state.v1.ListMappingsRequest + 122, // 151: state.v1.StateStoreService.UpdateMapping:input_type -> state.v1.UpdateMappingRequest + 124, // 152: state.v1.StateStoreService.DeleteMapping:input_type -> state.v1.DeleteMappingRequest + 126, // 153: state.v1.StateStoreService.RecordMappingMatch:input_type -> state.v1.RecordMappingMatchRequest + 128, // 154: state.v1.StateStoreService.InsertEventType:input_type -> state.v1.InsertEventTypeRequest + 130, // 155: state.v1.StateStoreService.UpdateEventType:input_type -> state.v1.UpdateEventTypeRequest + 132, // 156: state.v1.StateStoreService.DeleteEventType:input_type -> state.v1.DeleteEventTypeRequest + 134, // 157: state.v1.StateStoreService.ListEventTypes:input_type -> state.v1.ListEventTypesRequest + 136, // 158: state.v1.StateStoreService.InsertBinding:input_type -> state.v1.InsertBindingRequest + 138, // 159: state.v1.StateStoreService.GetBinding:input_type -> state.v1.GetBindingRequest + 140, // 160: state.v1.StateStoreService.ListBindings:input_type -> state.v1.ListBindingsRequest + 142, // 161: state.v1.StateStoreService.UpdateBinding:input_type -> state.v1.UpdateBindingRequest + 144, // 162: state.v1.StateStoreService.DeleteBinding:input_type -> state.v1.DeleteBindingRequest + 146, // 163: state.v1.StateStoreService.ApproveBinding:input_type -> state.v1.ApproveBindingRequest + 148, // 164: state.v1.StateStoreService.InsertSource:input_type -> state.v1.InsertSourceRequest + 150, // 165: state.v1.StateStoreService.GetSource:input_type -> state.v1.GetSourceRequest + 152, // 166: state.v1.StateStoreService.ListSources:input_type -> state.v1.ListSourcesRequest + 154, // 167: state.v1.StateStoreService.SetSourceSigning:input_type -> state.v1.SetSourceSigningRequest + 156, // 168: state.v1.StateStoreService.SetSourceSecret:input_type -> state.v1.SetSourceSecretRequest + 158, // 169: state.v1.StateStoreService.ArmedBindingsForSource:input_type -> state.v1.ArmedBindingsForSourceRequest + 160, // 170: state.v1.StateStoreService.RecordDispatch:input_type -> state.v1.RecordDispatchRequest + 162, // 171: state.v1.StateStoreService.RecordPlaybookDispatch:input_type -> state.v1.RecordPlaybookDispatchRequest + 164, // 172: state.v1.StateStoreService.DeletePlaybookDispatches:input_type -> state.v1.DeletePlaybookDispatchesRequest + 166, // 173: state.v1.StateStoreService.StreamUndispatchedCaptures:input_type -> state.v1.StreamUndispatchedCapturesRequest + 168, // 174: state.v1.StateStoreService.EnqueueBindingTask:input_type -> state.v1.EnqueueBindingTaskRequest + 170, // 175: state.v1.StateStoreService.EnqueueCallTask:input_type -> state.v1.EnqueueCallTaskRequest + 172, // 176: state.v1.StateStoreService.WorkflowCallStatus:input_type -> state.v1.WorkflowCallStatusRequest + 183, // 177: state.v1.StateStoreService.GetPrincipal:input_type -> state.v1.GetPrincipalRequest + 188, // 178: state.v1.StateStoreService.ListPolicies:input_type -> state.v1.ListPoliciesRequest + 190, // 179: state.v1.StateStoreService.PutPolicy:input_type -> state.v1.PutPolicyRequest + 192, // 180: state.v1.StateStoreService.DeletePolicy:input_type -> state.v1.DeletePolicyRequest + 194, // 181: state.v1.StateStoreService.EnsureShippedOrgPolicies:input_type -> state.v1.EnsureShippedOrgPoliciesRequest + 197, // 182: state.v1.StateStoreService.RecordDenial:input_type -> state.v1.RecordDenialRequest + 199, // 183: state.v1.StateStoreService.ListDenials:input_type -> state.v1.ListDenialsRequest + 176, // 184: state.v1.StateStoreService.InstallPackage:output_type -> state.v1.InstallPackageResponse + 178, // 185: state.v1.StateStoreService.GetInstalledPackage:output_type -> state.v1.GetInstalledPackageResponse + 180, // 186: state.v1.StateStoreService.ListInstalledPackages:output_type -> state.v1.ListInstalledPackagesResponse + 182, // 187: state.v1.StateStoreService.RemoveInstalledPackage:output_type -> state.v1.RemoveInstalledPackageResponse + 1, // 188: state.v1.StateStoreService.RegisterTaskGrant:output_type -> state.v1.RegisterTaskGrantResponse + 3, // 189: state.v1.StateStoreService.RevokeTaskGrant:output_type -> state.v1.RevokeTaskGrantResponse + 7, // 190: state.v1.StateStoreService.ListIdentities:output_type -> state.v1.ListIdentitiesResponse + 9, // 191: state.v1.StateStoreService.GetIdentity:output_type -> state.v1.GetIdentityResponse + 15, // 192: state.v1.StateStoreService.CreateIdentity:output_type -> state.v1.CreateIdentityResponse + 16, // 193: state.v1.StateStoreService.RenameIdentity:output_type -> state.v1.RenameIdentityResponse + 17, // 194: state.v1.StateStoreService.SuspendIdentity:output_type -> state.v1.SuspendIdentityResponse + 18, // 195: state.v1.StateStoreService.ReactivateIdentity:output_type -> state.v1.ReactivateIdentityResponse + 19, // 196: state.v1.StateStoreService.RetireIdentity:output_type -> state.v1.RetireIdentityResponse + 21, // 197: state.v1.StateStoreService.ResolveIdentitySubject:output_type -> state.v1.ResolveIdentitySubjectResponse + 23, // 198: state.v1.StateStoreService.BindIdentitySubject:output_type -> state.v1.BindIdentitySubjectResponse + 39, // 199: state.v1.StateStoreService.EnqueueIssue:output_type -> state.v1.EnqueueIssueResponse + 41, // 200: state.v1.StateStoreService.EnqueueChatTask:output_type -> state.v1.EnqueueChatTaskResponse + 43, // 201: state.v1.StateStoreService.ClaimNext:output_type -> state.v1.ClaimNextResponse + 45, // 202: state.v1.StateStoreService.ClaimByIssue:output_type -> state.v1.ClaimByIssueResponse + 47, // 203: state.v1.StateStoreService.Transition:output_type -> state.v1.TransitionResponse + 49, // 204: state.v1.StateStoreService.Update:output_type -> state.v1.UpdateResponse + 51, // 205: state.v1.StateStoreService.Requeue:output_type -> state.v1.RequeueResponse + 53, // 206: state.v1.StateStoreService.ParkTask:output_type -> state.v1.ParkTaskResponse + 55, // 207: state.v1.StateStoreService.RecoverStale:output_type -> state.v1.RecoverStaleResponse + 57, // 208: state.v1.StateStoreService.ArchiveTask:output_type -> state.v1.ArchiveTaskResponse + 59, // 209: state.v1.StateStoreService.RetryTask:output_type -> state.v1.RetryTaskResponse + 61, // 210: state.v1.StateStoreService.BeginRemediation:output_type -> state.v1.BeginRemediationResponse + 63, // 211: state.v1.StateStoreService.UpdateReviewPayload:output_type -> state.v1.UpdateReviewPayloadResponse + 65, // 212: state.v1.StateStoreService.SetReviewCursors:output_type -> state.v1.SetReviewCursorsResponse + 67, // 213: state.v1.StateStoreService.TaskByIssue:output_type -> state.v1.TaskByIssueResponse + 69, // 214: state.v1.StateStoreService.OpenTaskByPR:output_type -> state.v1.OpenTaskByPRResponse + 71, // 215: state.v1.StateStoreService.TaskByID:output_type -> state.v1.TaskByIDResponse + 73, // 216: state.v1.StateStoreService.OpenPRs:output_type -> state.v1.OpenPRsResponse + 75, // 217: state.v1.StateStoreService.ClearTerminalTasks:output_type -> state.v1.ClearTerminalTasksResponse + 77, // 218: state.v1.StateStoreService.Tasks:output_type -> state.v1.TasksResponse + 79, // 219: state.v1.StateStoreService.StatusCounts:output_type -> state.v1.StatusCountsResponse + 81, // 220: state.v1.StateStoreService.InsertEvent:output_type -> state.v1.InsertEventResponse + 83, // 221: state.v1.StateStoreService.EventsSince:output_type -> state.v1.EventsSinceResponse + 85, // 222: state.v1.StateStoreService.TaskEvents:output_type -> state.v1.TaskEventsResponse + 87, // 223: state.v1.StateStoreService.WorkflowStats:output_type -> state.v1.WorkflowStatsResponse + 89, // 224: state.v1.StateStoreService.StageStats:output_type -> state.v1.StageStatsResponse + 91, // 225: state.v1.StateStoreService.TokensByDay:output_type -> state.v1.TokensByDayResponse + 94, // 226: state.v1.StateStoreService.PutConfigSnapshot:output_type -> state.v1.PutConfigSnapshotResponse + 96, // 227: state.v1.StateStoreService.GetConfigSnapshot:output_type -> state.v1.GetConfigSnapshotResponse + 99, // 228: state.v1.StateStoreService.PutChannelStatus:output_type -> state.v1.PutChannelStatusResponse + 101, // 229: state.v1.StateStoreService.ListChannelStatus:output_type -> state.v1.ListChannelStatusResponse + 104, // 230: state.v1.StateStoreService.PutApplyStatus:output_type -> state.v1.PutApplyStatusResponse + 106, // 231: state.v1.StateStoreService.ListApplyStatus:output_type -> state.v1.ListApplyStatusResponse + 109, // 232: state.v1.StateStoreService.ReadTaskLog:output_type -> state.v1.ReadTaskLogResponse + 111, // 233: state.v1.StateStoreService.StreamTaskLogContent:output_type -> state.v1.StreamTaskLogContentResponse + 113, // 234: state.v1.StateStoreService.InsertCapture:output_type -> state.v1.InsertCaptureResponse + 115, // 235: state.v1.StateStoreService.StreamCaptures:output_type -> state.v1.StreamCapturesResponse + 117, // 236: state.v1.StateStoreService.InsertMapping:output_type -> state.v1.InsertMappingResponse + 119, // 237: state.v1.StateStoreService.GetMapping:output_type -> state.v1.GetMappingResponse + 121, // 238: state.v1.StateStoreService.ListMappings:output_type -> state.v1.ListMappingsResponse + 123, // 239: state.v1.StateStoreService.UpdateMapping:output_type -> state.v1.UpdateMappingResponse + 125, // 240: state.v1.StateStoreService.DeleteMapping:output_type -> state.v1.DeleteMappingResponse + 127, // 241: state.v1.StateStoreService.RecordMappingMatch:output_type -> state.v1.RecordMappingMatchResponse + 129, // 242: state.v1.StateStoreService.InsertEventType:output_type -> state.v1.InsertEventTypeResponse + 131, // 243: state.v1.StateStoreService.UpdateEventType:output_type -> state.v1.UpdateEventTypeResponse + 133, // 244: state.v1.StateStoreService.DeleteEventType:output_type -> state.v1.DeleteEventTypeResponse + 135, // 245: state.v1.StateStoreService.ListEventTypes:output_type -> state.v1.ListEventTypesResponse + 137, // 246: state.v1.StateStoreService.InsertBinding:output_type -> state.v1.InsertBindingResponse + 139, // 247: state.v1.StateStoreService.GetBinding:output_type -> state.v1.GetBindingResponse + 141, // 248: state.v1.StateStoreService.ListBindings:output_type -> state.v1.ListBindingsResponse + 143, // 249: state.v1.StateStoreService.UpdateBinding:output_type -> state.v1.UpdateBindingResponse + 145, // 250: state.v1.StateStoreService.DeleteBinding:output_type -> state.v1.DeleteBindingResponse + 147, // 251: state.v1.StateStoreService.ApproveBinding:output_type -> state.v1.ApproveBindingResponse + 149, // 252: state.v1.StateStoreService.InsertSource:output_type -> state.v1.InsertSourceResponse + 151, // 253: state.v1.StateStoreService.GetSource:output_type -> state.v1.GetSourceResponse + 153, // 254: state.v1.StateStoreService.ListSources:output_type -> state.v1.ListSourcesResponse + 155, // 255: state.v1.StateStoreService.SetSourceSigning:output_type -> state.v1.SetSourceSigningResponse + 157, // 256: state.v1.StateStoreService.SetSourceSecret:output_type -> state.v1.SetSourceSecretResponse + 159, // 257: state.v1.StateStoreService.ArmedBindingsForSource:output_type -> state.v1.ArmedBindingsForSourceResponse + 161, // 258: state.v1.StateStoreService.RecordDispatch:output_type -> state.v1.RecordDispatchResponse + 163, // 259: state.v1.StateStoreService.RecordPlaybookDispatch:output_type -> state.v1.RecordPlaybookDispatchResponse + 165, // 260: state.v1.StateStoreService.DeletePlaybookDispatches:output_type -> state.v1.DeletePlaybookDispatchesResponse + 167, // 261: state.v1.StateStoreService.StreamUndispatchedCaptures:output_type -> state.v1.StreamUndispatchedCapturesResponse + 169, // 262: state.v1.StateStoreService.EnqueueBindingTask:output_type -> state.v1.EnqueueBindingTaskResponse + 171, // 263: state.v1.StateStoreService.EnqueueCallTask:output_type -> state.v1.EnqueueCallTaskResponse + 173, // 264: state.v1.StateStoreService.WorkflowCallStatus:output_type -> state.v1.WorkflowCallStatusResponse + 186, // 265: state.v1.StateStoreService.GetPrincipal:output_type -> state.v1.GetPrincipalResponse + 189, // 266: state.v1.StateStoreService.ListPolicies:output_type -> state.v1.ListPoliciesResponse + 191, // 267: state.v1.StateStoreService.PutPolicy:output_type -> state.v1.PutPolicyResponse + 193, // 268: state.v1.StateStoreService.DeletePolicy:output_type -> state.v1.DeletePolicyResponse + 195, // 269: state.v1.StateStoreService.EnsureShippedOrgPolicies:output_type -> state.v1.EnsureShippedOrgPoliciesResponse + 198, // 270: state.v1.StateStoreService.RecordDenial:output_type -> state.v1.RecordDenialResponse + 200, // 271: state.v1.StateStoreService.ListDenials:output_type -> state.v1.ListDenialsResponse + 184, // [184:272] is the sub-list for method output_type + 96, // [96:184] is the sub-list for method input_type + 96, // [96:96] is the sub-list for extension type_name + 96, // [96:96] is the sub-list for extension extendee + 0, // [0:96] is the sub-list for field type_name } func init() { file_state_v1_state_proto_init() } @@ -11025,7 +12046,7 @@ func file_state_v1_state_proto_init() { GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_state_v1_state_proto_rawDesc), len(file_state_v1_state_proto_rawDesc)), NumEnums: 0, - NumMessages: 185, + NumMessages: 203, NumExtensions: 0, NumServices: 1, }, diff --git a/internal/contracts/state/v1/state_grpc.pb.go b/internal/contracts/state/v1/state_grpc.pb.go index 967633d44..6c5ae245a 100644 --- a/internal/contracts/state/v1/state_grpc.pb.go +++ b/internal/contracts/state/v1/state_grpc.pb.go @@ -100,6 +100,13 @@ const ( StateStoreService_EnqueueBindingTask_FullMethodName = "/state.v1.StateStoreService/EnqueueBindingTask" StateStoreService_EnqueueCallTask_FullMethodName = "/state.v1.StateStoreService/EnqueueCallTask" StateStoreService_WorkflowCallStatus_FullMethodName = "/state.v1.StateStoreService/WorkflowCallStatus" + StateStoreService_GetPrincipal_FullMethodName = "/state.v1.StateStoreService/GetPrincipal" + StateStoreService_ListPolicies_FullMethodName = "/state.v1.StateStoreService/ListPolicies" + StateStoreService_PutPolicy_FullMethodName = "/state.v1.StateStoreService/PutPolicy" + StateStoreService_DeletePolicy_FullMethodName = "/state.v1.StateStoreService/DeletePolicy" + StateStoreService_EnsureShippedOrgPolicies_FullMethodName = "/state.v1.StateStoreService/EnsureShippedOrgPolicies" + StateStoreService_RecordDenial_FullMethodName = "/state.v1.StateStoreService/RecordDenial" + StateStoreService_ListDenials_FullMethodName = "/state.v1.StateStoreService/ListDenials" ) // StateStoreServiceClient is the client API for StateStoreService service. @@ -252,6 +259,19 @@ type StateStoreServiceClient interface { // relation server-side, so the grant only names the caller. EnqueueCallTask(ctx context.Context, in *EnqueueCallTaskRequest, opts ...grpc.CallOption) (*EnqueueCallTaskResponse, error) WorkflowCallStatus(ctx context.Context, in *WorkflowCallStatusRequest, opts ...grpc.CallOption) (*WorkflowCallStatusResponse, error) + // Access: the stored policy chain and its denial records + // (docs/prds/orgs-and-access.md). ListPolicies is the engine's snapshot; + // the writes are administrative. RecordDenial is the dashboard's and + // dispatch's write path; ListDenials is the operator surface. + // The principal assembly the Authorizer evaluates: an identity, the org + // it serves, and its memberships (internal/domain/access). + GetPrincipal(ctx context.Context, in *GetPrincipalRequest, opts ...grpc.CallOption) (*GetPrincipalResponse, error) + ListPolicies(ctx context.Context, in *ListPoliciesRequest, opts ...grpc.CallOption) (*ListPoliciesResponse, error) + PutPolicy(ctx context.Context, in *PutPolicyRequest, opts ...grpc.CallOption) (*PutPolicyResponse, error) + DeletePolicy(ctx context.Context, in *DeletePolicyRequest, opts ...grpc.CallOption) (*DeletePolicyResponse, error) + EnsureShippedOrgPolicies(ctx context.Context, in *EnsureShippedOrgPoliciesRequest, opts ...grpc.CallOption) (*EnsureShippedOrgPoliciesResponse, error) + RecordDenial(ctx context.Context, in *RecordDenialRequest, opts ...grpc.CallOption) (*RecordDenialResponse, error) + ListDenials(ctx context.Context, in *ListDenialsRequest, opts ...grpc.CallOption) (*ListDenialsResponse, error) } type stateStoreServiceClient struct { @@ -1099,6 +1119,76 @@ func (c *stateStoreServiceClient) WorkflowCallStatus(ctx context.Context, in *Wo return out, nil } +func (c *stateStoreServiceClient) GetPrincipal(ctx context.Context, in *GetPrincipalRequest, opts ...grpc.CallOption) (*GetPrincipalResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(GetPrincipalResponse) + err := c.cc.Invoke(ctx, StateStoreService_GetPrincipal_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *stateStoreServiceClient) ListPolicies(ctx context.Context, in *ListPoliciesRequest, opts ...grpc.CallOption) (*ListPoliciesResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(ListPoliciesResponse) + err := c.cc.Invoke(ctx, StateStoreService_ListPolicies_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *stateStoreServiceClient) PutPolicy(ctx context.Context, in *PutPolicyRequest, opts ...grpc.CallOption) (*PutPolicyResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(PutPolicyResponse) + err := c.cc.Invoke(ctx, StateStoreService_PutPolicy_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *stateStoreServiceClient) DeletePolicy(ctx context.Context, in *DeletePolicyRequest, opts ...grpc.CallOption) (*DeletePolicyResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(DeletePolicyResponse) + err := c.cc.Invoke(ctx, StateStoreService_DeletePolicy_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *stateStoreServiceClient) EnsureShippedOrgPolicies(ctx context.Context, in *EnsureShippedOrgPoliciesRequest, opts ...grpc.CallOption) (*EnsureShippedOrgPoliciesResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(EnsureShippedOrgPoliciesResponse) + err := c.cc.Invoke(ctx, StateStoreService_EnsureShippedOrgPolicies_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *stateStoreServiceClient) RecordDenial(ctx context.Context, in *RecordDenialRequest, opts ...grpc.CallOption) (*RecordDenialResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(RecordDenialResponse) + err := c.cc.Invoke(ctx, StateStoreService_RecordDenial_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *stateStoreServiceClient) ListDenials(ctx context.Context, in *ListDenialsRequest, opts ...grpc.CallOption) (*ListDenialsResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(ListDenialsResponse) + err := c.cc.Invoke(ctx, StateStoreService_ListDenials_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + // StateStoreServiceServer is the server API for StateStoreService service. // All implementations must embed UnimplementedStateStoreServiceServer // for forward compatibility. @@ -1249,6 +1339,19 @@ type StateStoreServiceServer interface { // relation server-side, so the grant only names the caller. EnqueueCallTask(context.Context, *EnqueueCallTaskRequest) (*EnqueueCallTaskResponse, error) WorkflowCallStatus(context.Context, *WorkflowCallStatusRequest) (*WorkflowCallStatusResponse, error) + // Access: the stored policy chain and its denial records + // (docs/prds/orgs-and-access.md). ListPolicies is the engine's snapshot; + // the writes are administrative. RecordDenial is the dashboard's and + // dispatch's write path; ListDenials is the operator surface. + // The principal assembly the Authorizer evaluates: an identity, the org + // it serves, and its memberships (internal/domain/access). + GetPrincipal(context.Context, *GetPrincipalRequest) (*GetPrincipalResponse, error) + ListPolicies(context.Context, *ListPoliciesRequest) (*ListPoliciesResponse, error) + PutPolicy(context.Context, *PutPolicyRequest) (*PutPolicyResponse, error) + DeletePolicy(context.Context, *DeletePolicyRequest) (*DeletePolicyResponse, error) + EnsureShippedOrgPolicies(context.Context, *EnsureShippedOrgPoliciesRequest) (*EnsureShippedOrgPoliciesResponse, error) + RecordDenial(context.Context, *RecordDenialRequest) (*RecordDenialResponse, error) + ListDenials(context.Context, *ListDenialsRequest) (*ListDenialsResponse, error) mustEmbedUnimplementedStateStoreServiceServer() } @@ -1502,6 +1605,27 @@ func (UnimplementedStateStoreServiceServer) EnqueueCallTask(context.Context, *En func (UnimplementedStateStoreServiceServer) WorkflowCallStatus(context.Context, *WorkflowCallStatusRequest) (*WorkflowCallStatusResponse, error) { return nil, status.Error(codes.Unimplemented, "method WorkflowCallStatus not implemented") } +func (UnimplementedStateStoreServiceServer) GetPrincipal(context.Context, *GetPrincipalRequest) (*GetPrincipalResponse, error) { + return nil, status.Error(codes.Unimplemented, "method GetPrincipal not implemented") +} +func (UnimplementedStateStoreServiceServer) ListPolicies(context.Context, *ListPoliciesRequest) (*ListPoliciesResponse, error) { + return nil, status.Error(codes.Unimplemented, "method ListPolicies not implemented") +} +func (UnimplementedStateStoreServiceServer) PutPolicy(context.Context, *PutPolicyRequest) (*PutPolicyResponse, error) { + return nil, status.Error(codes.Unimplemented, "method PutPolicy not implemented") +} +func (UnimplementedStateStoreServiceServer) DeletePolicy(context.Context, *DeletePolicyRequest) (*DeletePolicyResponse, error) { + return nil, status.Error(codes.Unimplemented, "method DeletePolicy not implemented") +} +func (UnimplementedStateStoreServiceServer) EnsureShippedOrgPolicies(context.Context, *EnsureShippedOrgPoliciesRequest) (*EnsureShippedOrgPoliciesResponse, error) { + return nil, status.Error(codes.Unimplemented, "method EnsureShippedOrgPolicies not implemented") +} +func (UnimplementedStateStoreServiceServer) RecordDenial(context.Context, *RecordDenialRequest) (*RecordDenialResponse, error) { + return nil, status.Error(codes.Unimplemented, "method RecordDenial not implemented") +} +func (UnimplementedStateStoreServiceServer) ListDenials(context.Context, *ListDenialsRequest) (*ListDenialsResponse, error) { + return nil, status.Error(codes.Unimplemented, "method ListDenials not implemented") +} func (UnimplementedStateStoreServiceServer) mustEmbedUnimplementedStateStoreServiceServer() {} func (UnimplementedStateStoreServiceServer) testEmbeddedByValue() {} @@ -2960,6 +3084,132 @@ func _StateStoreService_WorkflowCallStatus_Handler(srv interface{}, ctx context. return interceptor(ctx, in, info, handler) } +func _StateStoreService_GetPrincipal_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(GetPrincipalRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(StateStoreServiceServer).GetPrincipal(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: StateStoreService_GetPrincipal_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(StateStoreServiceServer).GetPrincipal(ctx, req.(*GetPrincipalRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _StateStoreService_ListPolicies_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(ListPoliciesRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(StateStoreServiceServer).ListPolicies(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: StateStoreService_ListPolicies_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(StateStoreServiceServer).ListPolicies(ctx, req.(*ListPoliciesRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _StateStoreService_PutPolicy_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(PutPolicyRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(StateStoreServiceServer).PutPolicy(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: StateStoreService_PutPolicy_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(StateStoreServiceServer).PutPolicy(ctx, req.(*PutPolicyRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _StateStoreService_DeletePolicy_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(DeletePolicyRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(StateStoreServiceServer).DeletePolicy(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: StateStoreService_DeletePolicy_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(StateStoreServiceServer).DeletePolicy(ctx, req.(*DeletePolicyRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _StateStoreService_EnsureShippedOrgPolicies_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(EnsureShippedOrgPoliciesRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(StateStoreServiceServer).EnsureShippedOrgPolicies(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: StateStoreService_EnsureShippedOrgPolicies_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(StateStoreServiceServer).EnsureShippedOrgPolicies(ctx, req.(*EnsureShippedOrgPoliciesRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _StateStoreService_RecordDenial_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(RecordDenialRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(StateStoreServiceServer).RecordDenial(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: StateStoreService_RecordDenial_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(StateStoreServiceServer).RecordDenial(ctx, req.(*RecordDenialRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _StateStoreService_ListDenials_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(ListDenialsRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(StateStoreServiceServer).ListDenials(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: StateStoreService_ListDenials_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(StateStoreServiceServer).ListDenials(ctx, req.(*ListDenialsRequest)) + } + return interceptor(ctx, in, info, handler) +} + // StateStoreService_ServiceDesc is the grpc.ServiceDesc for StateStoreService service. // It's only intended for direct use with grpc.RegisterService, // and not to be introspected or modified (even as a copy) @@ -3279,6 +3529,34 @@ var StateStoreService_ServiceDesc = grpc.ServiceDesc{ MethodName: "WorkflowCallStatus", Handler: _StateStoreService_WorkflowCallStatus_Handler, }, + { + MethodName: "GetPrincipal", + Handler: _StateStoreService_GetPrincipal_Handler, + }, + { + MethodName: "ListPolicies", + Handler: _StateStoreService_ListPolicies_Handler, + }, + { + MethodName: "PutPolicy", + Handler: _StateStoreService_PutPolicy_Handler, + }, + { + MethodName: "DeletePolicy", + Handler: _StateStoreService_DeletePolicy_Handler, + }, + { + MethodName: "EnsureShippedOrgPolicies", + Handler: _StateStoreService_EnsureShippedOrgPolicies_Handler, + }, + { + MethodName: "RecordDenial", + Handler: _StateStoreService_RecordDenial_Handler, + }, + { + MethodName: "ListDenials", + Handler: _StateStoreService_ListDenials_Handler, + }, }, Streams: []grpc.StreamDesc{ { diff --git a/internal/daemon/daemon.go b/internal/daemon/daemon.go index aa071b145..94d52505f 100644 --- a/internal/daemon/daemon.go +++ b/internal/daemon/daemon.go @@ -19,6 +19,7 @@ import ( "github.com/samcharles93/archie-core/internal/agentexec" "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/container" + "github.com/samcharles93/archie-core/internal/domain/access" "github.com/samcharles93/archie-core/internal/domain/binding" "github.com/samcharles93/archie-core/internal/domain/curator" "github.com/samcharles93/archie-core/internal/domain/eda/playbook" @@ -129,10 +130,21 @@ type Daemon struct { // dispatch loop does not acquire the full task-creation contract. // Optional: nil disables the dispatch loop. BindingTaskCreator storecontract.BindingTaskCreator - Forge forge.Forge - Trees *worktree.Manager - Bus *events.Bus - Log *slog.Logger + // Access evaluates the policy chain at dispatch, the second of the two + // Authorizer call sites (docs/prds/orgs-and-access.md, "Where it + // lives"): the workflow's identity may `run` the workflow in its + // workspace. Optional: nil dispatches without the chain, which is the + // behaviour of an install that has not built it. + Access access.Authorizer + // Principals assembles the dispatch principal for the workflow's + // identity. Wired with Access or not at all. + Principals access.PrincipalSource + // Denials records dispatch refusals. Optional: nil skips the record. + Denials access.DenialStore + Forge forge.Forge + Trees *worktree.Manager + Bus *events.Bus + Log *slog.Logger // Tasks is the NATS task distribution bus: the poller publishes // discovered work over it and runViaAgent requests execution through it. // NATS startup is mandatory (there is no broker-off execution mode), so @@ -728,6 +740,21 @@ func (d *Daemon) dispatchOneBinding(ctx context.Context, b binding.Binding, c st if !ok { return } + // The chain decides dispatch: the workflow's identity may `run` this + // workflow in its workspace, and the event's signature result and + // address travel with the request (docs/prds/orgs-and-access.md, + // "Access decisions"). A denial is recorded and the dispatch is not + // claimed: the capture stays listed for the next cycle. + 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) @@ -749,6 +776,58 @@ func (d *Daemon) dispatchOneBinding(ctx context.Context, b binding.Binding, c st } } +// authorizeDispatch evaluates the policy chain for the workflow's identity +// before the dispatch is claimed: the identity may `run` the workflow in its +// workspace, with the event's signature result and source address as context. +// A denial is recorded with the level that decided it and the deciding +// policies, and reported as a binding_dispatch_failure. +func (d *Daemon) authorizeDispatch(ctx context.Context, b binding.Binding, c storecontract.CapturedEvent, target bindingTarget) bool { + if d.Access == nil || d.Principals == nil { + return true + } + principal, err := d.Principals.PrincipalFor(ctx, d.RootIdentityID) + if err != nil { + d.Log.Warn("binding dispatch: principal unavailable; dispatch parked for the next cycle", + "binding", b.ID, "capture", c.ID, "error", err) + return false + } + resource := access.Resource{ + Kind: access.KindWorkflow, ID: b.Workflow, Org: principal.Org, + } + contextValue := access.Context{Signature: signatureOf(c), Addr: c.RemoteAddr} + decision := d.Access.Authorize(principal, access.ActionRun, resource, contextValue) + if decision.Allowed { + return true + } + if d.Denials != nil { + denial := access.Denial{ + Principal: principal.IdentityID, Org: principal.Org, Action: access.ActionRun, + Kind: resource.Kind, ResourceID: resource.ID, Level: decision.Level, + Policies: decision.Policies, + } + if err := d.Denials.RecordDenial(ctx, denial); err != nil { + d.Log.Warn("binding dispatch: record denial", "binding", b.ID, "error", err) + } + } + d.recordDispatchFailure(ctx, b, c, "access denied", map[string]any{ + "level": string(decision.Level), "policies": decision.Policies, + }) + return false +} + +// signatureOf names the event's signature result as the dispatch context +// carries it: a signed event and an approved unsigned event are the two +// dispatchable shapes (storecontract.CapturedEvent.Dispatchable). +func signatureOf(c storecontract.CapturedEvent) string { + switch { + case c.Authenticated: + return "valid" + case c.Unsigned: + return "unsigned" + } + return "unverified" +} + // markUnsignedStart records on a task's timeline that an unsigned event // started it. func (d *Daemon) markUnsignedStart(ctx context.Context, taskID int64, b binding.Binding, c storecontract.CapturedEvent) { diff --git a/internal/domain/access/access.go b/internal/domain/access/access.go new file mode 100644 index 000000000..73f22c6a1 --- /dev/null +++ b/internal/domain/access/access.go @@ -0,0 +1,193 @@ +// Package access owns the policy schema, the action vocabulary, how +// principals and resources are turned into policy entities, and the +// Authorizer contract (docs/prds/orgs-and-access.md). +// +// The policy chain is +// +// instance ─▶ org ─▶ workspace ─▶ identity + workflow ─▶ object +// +// and the Cedar implementation lives in internal/infrastructure/access; +// internal/app wires it. Exactly two places call the Authorizer: the +// dashboard and API request path, and dispatch. Every other service verifies +// a credential and never evaluates policy. +// +// The chain's "identity + workflow" level is expressed with object policies: +// an identity or a workflow is one of the objects a policy can attach to +// (event source, secret, identity, binding, workflow), so the stored levels +// are instance, org, workspace and object. +package access + +import ( + "errors" + "fmt" + "slices" + "strings" + + "github.com/samcharles93/archie-core/internal/domain/org" +) + +// Level is one level of the policy chain. A level's policies govern the +// requests the levels below it see: a lower level narrows and never widens. +type Level string + +const ( + // LevelInstance holds across every org. The shipped cross-org forbid + // lives here and cannot be removed. + LevelInstance Level = "instance" + // LevelOrg is an org's policies, including the shipped role policies. + LevelOrg Level = "org" + // LevelWorkspace is one workspace's stored policies. + LevelWorkspace Level = "workspace" + // LevelObject attaches to one object: an event source, a secret, an + // identity, a binding, a workflow. + LevelObject Level = "object" +) + +// Validate reports whether l is one of the stored levels. +func (l Level) Validate() error { + switch l { + case LevelInstance, LevelOrg, LevelWorkspace, LevelObject: + return nil + } + return fmt.Errorf("%w: %q", ErrInvalidLevel, l) +} + +// Action is the access vocabulary: what a principal may do to a resource. +type Action string + +const ( + ActionRead Action = "read" + ActionCreate Action = "create" + ActionUpdate Action = "update" + ActionDelete Action = "delete" + ActionApprove Action = "approve" + ActionRun Action = "run" + ActionReadLogs Action = "read_logs" + ActionReadSecret Action = "read_secret" + ActionManageMembers Action = "manage_members" + ActionManageIdentities Action = "manage_identities" + ActionManagePolicies Action = "manage_policies" +) + +// Actions is every action, in vocabulary order. The engine and the shipped +// role policies iterate it. +func Actions() []Action { + return []Action{ + ActionRead, ActionCreate, ActionUpdate, ActionDelete, ActionApprove, + ActionRun, ActionReadLogs, ActionReadSecret, + ActionManageMembers, ActionManageIdentities, ActionManagePolicies, + } +} + +// Validate reports whether a is one of the shipped actions. +func (a Action) Validate() error { + if slices.Contains(Actions(), a) { + return nil + } + return fmt.Errorf("%w: %q", ErrInvalidAction, a) +} + +// ResourceKind is what a resource record is. The kind is the object a policy +// names and the vocabulary the dashboard's API path derives actions from. +type ResourceKind string + +const ( + KindOrg ResourceKind = "org" + KindWorkspace ResourceKind = "workspace" + KindSource ResourceKind = "source" + KindEventType ResourceKind = "event_type" + KindMapping ResourceKind = "mapping" + KindBinding ResourceKind = "binding" + KindWorkflow ResourceKind = "workflow" + KindTask ResourceKind = "task" + KindCapture ResourceKind = "capture" + KindSecret ResourceKind = "secret" + KindIdentity ResourceKind = "identity" + KindPolicy ResourceKind = "policy" + KindMember ResourceKind = "member" + KindDashboard ResourceKind = "dashboard" + KindEventIngest ResourceKind = "event" +) + +// Policy is one stored policy document. Its Text is Cedar policy language +// (one policy: an effect, a principal/action/resource scope and conditions). +// +// The scope fields say where the policy attaches. LevelInstance policies +// carry none; LevelOrg carries OrgID; LevelWorkspace adds WorkspaceID; +// LevelObject adds ObjectKind and ObjectID. +type Policy struct { + ID string `json:"id"` + Level Level `json:"level"` + + OrgID org.OrgID `json:"org_id,omitempty"` + WorkspaceID org.WorkspaceID `json:"workspace_id,omitempty"` + ObjectKind ResourceKind `json:"object_kind,omitempty"` + ObjectID string `json:"object_id,omitempty"` + + Text string `json:"text"` +} + +// Validate checks a policy's shape: a level-appropriate scope, a non-empty +// text and a non-empty ID. The text's Cedar syntax is checked by the engine +// (the Validator contract); this check is structural, so the store and the +// reset path can reject a malformed document without an engine. +func (p Policy) Validate() error { + if strings.TrimSpace(p.ID) == "" { + return fmt.Errorf("%w: no ID", ErrInvalidPolicy) + } + if err := p.Level.Validate(); err != nil { + return err + } + switch p.Level { + case LevelInstance: + case LevelOrg: + if p.OrgID == "" { + return fmt.Errorf("%w: org policy carries no org", ErrInvalidPolicy) + } + case LevelWorkspace: + if p.OrgID == "" || p.WorkspaceID == "" { + return fmt.Errorf("%w: workspace policy carries no org or workspace", ErrInvalidPolicy) + } + case LevelObject: + if p.OrgID == "" || p.WorkspaceID == "" || p.ObjectKind == "" || p.ObjectID == "" { + return fmt.Errorf("%w: object policy carries no org, workspace, kind or ID", ErrInvalidPolicy) + } + } + if strings.TrimSpace(p.Text) == "" { + return fmt.Errorf("%w: no text", ErrInvalidPolicy) + } + return nil +} + +// Governs reports whether the policy attaches to the level and scope of the +// given resource. An instance policy governs everything; an org policy +// governs the resources of its org; a workspace policy its workspace; an +// object policy the one record it names. +func (p Policy) Governs(r Resource) bool { + if p.Level != LevelInstance && p.OrgID != r.Org { + return false + } + switch p.Level { + case LevelWorkspace, LevelObject: + if p.WorkspaceID != r.Workspace { + return false + } + } + if p.Level == LevelObject && (p.ObjectKind != r.Kind || p.ObjectID != r.ID) { + return false + } + return true +} + +// Sentinel errors. The message strings are part of the store's wire +// contract: staterpc's mapError/unmapError matches them by (code, canonical +// message), so they must never change. +var ( + ErrInvalidLevel = errors.New("access: invalid level") + ErrInvalidAction = errors.New("access: invalid action") + ErrInvalidPolicy = errors.New("access: invalid policy") + // ErrPolicyNotFound is returned when a policy ID does not exist. + ErrPolicyNotFound = errors.New("access: policy not found") + // ErrPolicyInvalidText is returned when a policy's text does not parse. + ErrPolicyInvalidText = errors.New("access: policy text does not parse") +) diff --git a/internal/domain/access/access_test.go b/internal/domain/access/access_test.go new file mode 100644 index 000000000..cac3cf4d4 --- /dev/null +++ b/internal/domain/access/access_test.go @@ -0,0 +1,197 @@ +package access + +import ( + "errors" + "testing" + + "github.com/samcharles93/archie-core/internal/domain/identity" + "github.com/samcharles93/archie-core/internal/domain/org" +) + +func TestPolicyValidate(t *testing.T) { + tests := []struct { + name string + policy Policy + wantErr error + }{ + { + name: "instance policy with no scope", + policy: Policy{ID: "p1", Level: LevelInstance, Text: "permit(principal, action, resource);"}, + }, + { + name: "instance policy without text", + policy: Policy{ID: "p1", Level: LevelInstance}, + wantErr: ErrInvalidPolicy, + }, + { + name: "org policy without org", + policy: Policy{ID: "p1", Level: LevelOrg, Text: "permit(principal, action, resource);"}, + wantErr: ErrInvalidPolicy, + }, + { + name: "workspace policy without workspace", + policy: Policy{ID: "p1", Level: LevelWorkspace, OrgID: "acme", Text: "permit(principal, action, resource);"}, + wantErr: ErrInvalidPolicy, + }, + { + name: "object policy with full scope", + policy: Policy{ + ID: "p1", Level: LevelObject, OrgID: "acme", WorkspaceID: "net", + ObjectKind: KindSecret, ObjectID: "firewall-api", + Text: "forbid(principal, action == Archie::Action::\"read_secret\", resource);", + }, + }, + { + name: "object policy without kind", + policy: Policy{ID: "p1", Level: LevelObject, OrgID: "acme", WorkspaceID: "net", ObjectID: "firewall-api", Text: "forbid(principal, action, resource);"}, + wantErr: ErrInvalidPolicy, + }, + { + name: "unknown level", + policy: Policy{ID: "p1", Level: "galaxy", Text: "permit(principal, action, resource);"}, + wantErr: ErrInvalidLevel, + }, + { + name: "no ID", + policy: Policy{Level: LevelInstance, Text: "permit(principal, action, resource);"}, + wantErr: ErrInvalidPolicy, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := tt.policy.Validate() + if tt.wantErr == nil { + if err != nil { + t.Fatalf("Validate() = %v, want nil", err) + } + return + } + if !errors.Is(err, tt.wantErr) { + t.Fatalf("Validate() = %v, want %v", err, tt.wantErr) + } + }) + } +} + +func TestPolicyGoverns(t *testing.T) { + res := Resource{Kind: KindBinding, ID: "b1", Org: "acme", Workspace: "net"} + + tests := []struct { + name string + policy Policy + want bool + }{ + { + name: "instance governs everything", + policy: Policy{Level: LevelInstance}, + want: true, + }, + { + name: "org policy for the same org", + policy: Policy{Level: LevelOrg, OrgID: "acme"}, + want: true, + }, + { + name: "org policy for another org never governs", + policy: Policy{Level: LevelOrg, OrgID: "other"}, + want: false, + }, + { + name: "workspace policy for the resource's workspace", + policy: Policy{Level: LevelWorkspace, OrgID: "acme", WorkspaceID: "net"}, + want: true, + }, + { + name: "workspace policy for another workspace", + policy: Policy{Level: LevelWorkspace, OrgID: "acme", WorkspaceID: "desk"}, + want: false, + }, + { + name: "object policy for the same object", + policy: Policy{Level: LevelObject, OrgID: "acme", WorkspaceID: "net", ObjectKind: KindBinding, ObjectID: "b1"}, + want: true, + }, + { + name: "object policy for another object", + policy: Policy{Level: LevelObject, OrgID: "acme", WorkspaceID: "net", ObjectKind: KindBinding, ObjectID: "b2"}, + want: false, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := tt.policy.Governs(res); got != tt.want { + t.Fatalf("Governs() = %v, want %v", got, tt.want) + } + }) + } +} + +func TestPrincipalRole(t *testing.T) { + id := identity.IdentityID("11111111-1111-5111-8111-111111111111") + p := Principal{ + IdentityID: id, + Org: "acme", + Memberships: []org.Membership{ + {IdentityID: id, OrgID: "acme", Role: org.RoleDeveloper}, + {IdentityID: id, OrgID: "acme", WorkspaceID: "net", Role: org.RoleViewer}, + {IdentityID: id, OrgID: "other", Role: org.RoleOwner}, // not this org's + }, + } + + tests := []struct { + name string + ws org.WorkspaceID + want org.Role + }{ + {name: "workspace membership wins", ws: "net", want: org.RoleViewer}, + {name: "org-wide role otherwise", ws: "desk", want: org.RoleDeveloper}, + {name: "org-wide role with no workspace", ws: "", want: org.RoleDeveloper}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := p.Role(tt.ws); got != tt.want { + t.Fatalf("Role(%q) = %q, want %q", tt.ws, got, tt.want) + } + }) + } + + noRole := Principal{IdentityID: id, Org: "acme"} + if got := noRole.Role("net"); got != "" { + t.Fatalf("roleless principal Role() = %q, want empty", got) + } +} + +func TestActionValidate(t *testing.T) { + for _, a := range Actions() { + if err := a.Validate(); err != nil { + t.Fatalf("Action(%q).Validate() = %v, want nil", a, err) + } + } + if err := Action("reboot").Validate(); !errors.Is(err, ErrInvalidAction) { + t.Fatalf("unknown action Validate() = %v, want ErrInvalidAction", err) + } +} + +func TestShippedOrgPolicies(t *testing.T) { + policies := ShippedOrgPolicies("acme") + if len(policies) != 4 { + t.Fatalf("len(ShippedOrgPolicies) = %d, want 4", len(policies)) + } + for _, p := range policies { + if p.Level != LevelOrg || p.OrgID != "acme" { + t.Fatalf("%s: level %q org %q, want org-level policy for acme", p.ID, p.Level, p.OrgID) + } + if err := p.Validate(); err != nil { + t.Fatalf("%s: Validate() = %v, want nil", p.ID, err) + } + } + ids := make(map[string]bool, len(policies)) + for _, p := range policies { + ids[p.ID] = true + } + for _, want := range []string{PolicyOrgRead, PolicyOrgEdit, PolicyOrgAdmin, PolicyOrgOwner} { + if !ids[want] { + t.Fatalf("ShippedOrgPolicies missing %q", want) + } + } +} diff --git a/internal/domain/access/authorizer.go b/internal/domain/access/authorizer.go new file mode 100644 index 000000000..708696369 --- /dev/null +++ b/internal/domain/access/authorizer.go @@ -0,0 +1,39 @@ +// The contracts callers depend on: the Authorizer the dashboard/API path and +// dispatch call, the Validator policy changes are checked against, and the +// policy source the engine is built from. +package access + +import "context" + +// Authorizer evaluates the policy chain for one request. Exactly two places +// call it (docs/prds/orgs-and-access.md, "Where it lives"): the dashboard and +// API request path, and dispatch. The implementation is the Cedar engine in +// internal/infrastructure/access. +// +// Authorize never fails open: a stored policy the engine cannot parse makes +// its level deny everything and the decision carries the error; an invalid +// instance policy is a boot failure, not a denial the request path sees. +type Authorizer interface { + // Authorize evaluates instance, org, workspace and object policies for + // the request. A request is allowed only if every level with policies + // for it permits it; a forbid at any level wins; with no permit the + // request is denied. + Authorize(p Principal, a Action, r Resource, c Context) Decision +} + +// Validator checks one policy against the current schema: Cedar syntax plus +// the entity vocabulary this package defines. A policy naming an unknown +// entity type, action or attribute is refused. Every stored policy is +// checked again when archie starts (the engine's construction reports the +// invalid ones). +type Validator interface { + Validate(p Policy) error +} + +// PolicySource hands the engine its snapshot. The State Store owns the +// stored policies; a process loads them once at boot (a policy change takes +// effect when the process reloads, which the policy-editing surface ships +// with its own refresh). +type PolicySource interface { + Policies(ctx context.Context) ([]Policy, error) +} diff --git a/internal/domain/access/request.go b/internal/domain/access/request.go new file mode 100644 index 000000000..a5f2ee23f --- /dev/null +++ b/internal/domain/access/request.go @@ -0,0 +1,157 @@ +// The entities a decision is made about. The domain owns their shape and the +// Cedar vocabulary they are built from (the schema); the engine in +// internal/infrastructure/access turns them into engine entities. This file +// carries no Cedar dependency: the vocabulary is plain constants so the +// domain never links the engine. +package access + +import ( + "context" + "time" + + "github.com/samcharles93/archie-core/internal/domain/identity" + "github.com/samcharles93/archie-core/internal/domain/org" +) + +// The Cedar vocabulary every policy and every assembled entity shares. A +// policy naming an unknown type, action or attribute is refused when it is +// saved and denied at every start (the engine's validation). +const ( + // Namespace prefixes every Cedar entity type the engine assembles. + Namespace = "Archie" + + // EntityTypeIdentity is the principal: an Archie identity. + EntityTypeIdentity = Namespace + "::Identity" + // EntityTypeOrg is the org a resource belongs to. + EntityTypeOrg = Namespace + "::Org" + // EntityTypeWorkspace is the workspace a resource belongs to. + EntityTypeWorkspace = Namespace + "::Workspace" + // EntityTypeObject is the resource acted on. Every record -- source, + // binding, workflow, secret, task, the org itself -- is one Object + // entity carrying its kind, so a policy can scope on + // `resource.kind == Archie::Kind::"binding"` without a type per record. + EntityTypeObject = Namespace + "::Object" + // EntityTypeAction is the action entity of a request, one per Action. + EntityTypeAction = Namespace + "::Action" + + // AttributeOrg is the org ID an identity or object carries. + AttributeOrg = "org" + // AttributeRole is the principal's effective role for the resource + // (workspace membership role when one exists, else its org-wide role). + AttributeRole = "role" + // AttributeKind is an object's resource kind. + AttributeKind = "kind" + // AttributeOwner is the ID of the identity that owns an object. + AttributeOwner = "owner" + // AttributeState is an object's state (binding's draft/armed, task's + // status, and so on), as the caller that assembles the request sees it. + AttributeState = "state" +) + +// Principal is who acts: an identity, with the memberships that give it +// roles. The org is the one the identity serves (org.Repository's +// OrgForIdentity); Memberships carries its org-wide and workspace roles. +type Principal struct { + IdentityID identity.IdentityID + Kind identity.Kind + Org org.OrgID + Memberships []org.Membership +} + +// Role returns the principal's effective role for a resource: the role of +// its membership in the resource's workspace when it holds one, else the +// role of its org-wide membership, else the empty string (no role, which +// the shipped role policies never permit). +func (p Principal) Role(ws org.WorkspaceID) org.Role { + var orgRole org.Role + for _, m := range p.Memberships { + if m.OrgID != p.Org { + continue + } + if m.WorkspaceID == "" { + orgRole = m.Role + } + if m.WorkspaceID == ws { + return m.Role + } + } + return orgRole +} + +// Resource is the record acted on: its type, its workspace and org as +// parents, its owner and its state. +type Resource struct { + Kind ResourceKind + // ID is the record's caller-facing key: a source's path, a binding's + // ID, an org's ID, a workflow's name. + ID string + // Org is the org the record belongs to. Empty means the principal's own + // org, which is how a create request names a resource that does not + // exist yet. + Org org.OrgID + // Workspace is the workspace the record belongs to, empty for + // org-owned records. + Workspace org.WorkspaceID + Owner identity.IdentityID + State string +} + +// Context is what was going on when the decision was asked for. +type Context struct { + // Signature is the event's signature result ("valid", "unsigned", ...). + Signature string + // Addr is the address the event came from. + Addr string + // Time is when the request was made; zero means now. + Time time.Time + // Run and Step identify the run and step when the principal is an agent. + Run string + Step string +} + +// Decision is the outcome of one Authorize call. When the request is denied, +// Level names the level that decided and Policies the IDs of the deciding +// policies at that level, so a denial record can name them. +type Decision struct { + Allowed bool + Level Level + Policies []string + // Err carries the engine failure behind a deny-all level: a stored + // policy that no longer parses. A denied request with Err set was never + // evaluated -- the level refuses everything rather than decide. + Err error +} + +// Allowed is the shared permit decision: no level denied. +func Allowed() Decision { return Decision{Allowed: true} } + +// DeniedAt records a denial decided at a level by the given policies. +func DeniedAt(level Level, policies []string) Decision { + return Decision{Level: level, Policies: policies} +} + +// PrincipalSource assembles the principal for one identity: the org it +// serves and its memberships. The State Store implements it (the memberships +// live in the State Store); the dashboard and dispatch call it over the wire. +type PrincipalSource interface { + // PrincipalFor returns the assembled principal. An identity in no org + // resolves to the default org, a principal with no role, which no + // shipped policy permits. + PrincipalFor(ctx context.Context, id identity.IdentityID) (Principal, error) +} + +// Denial is one recorded refusal: who was refused, doing what, to what, by +// which level and which policies (docs/prds/orgs-and-access.md, "Denials"). +type Denial struct { + Principal identity.IdentityID `json:"principal"` + Org org.OrgID `json:"org"` + Action Action `json:"action"` + Kind ResourceKind `json:"kind"` + ResourceID string `json:"resource"` + Level Level `json:"level"` + Policies []string `json:"policies"` + At time.Time `json:"at"` + // Count is how many identical denials this record stands for. The store + // coalesces identical denials within a minute into one row with a count. + Count int64 `json:"count"` +} diff --git a/internal/domain/access/roles.go b/internal/domain/access/roles.go new file mode 100644 index 000000000..2b5497de1 --- /dev/null +++ b/internal/domain/access/roles.go @@ -0,0 +1,86 @@ +// The shipped policies: the four org roles every org carries, and the +// cross-org forbid the engine always enforces +// (docs/prds/orgs-and-access.md, "The policy chain" and "Roles"). +// +// The role policies are Cedar policy text because that is what the engine +// evaluates. They live in the domain so the store seeds them, the reset +// command restores them, and the engine ships the same words regardless of +// which process builds it. +package access + +import "github.com/samcharles93/archie-core/internal/domain/org" + +// Role names as the shipped role policies test them: org.Role's lowercase +// vocabulary, carried in the principal's `role` attribute. +const ( + roleOwner string = string(org.RoleOwner) + roleAdmin string = string(org.RoleAdmin) + roleDeveloper string = string(org.RoleDeveloper) + roleViewer string = string(org.RoleViewer) +) + +// Shipped policy IDs. A stored policy must not reuse one: the store's +// seeding and the reset command overwrite these IDs with the shipped text. +const ( + PolicyOrgRead = "org-role-read" + PolicyOrgEdit = "org-role-edit" + PolicyOrgAdmin = "org-role-admin" + PolicyOrgOwner = "org-role-owner" + PolicyCrossOrgID = "instance-cross-org" +) + +// orgReadPolicy is every role's floor: read everything in the org, and its +// logs, but not a secret's value. +const orgReadPolicy = `permit(principal, action, resource) when { + resource.org == principal.org && + ["` + roleViewer + `", "` + roleDeveloper + `", "` + roleAdmin + `", "` + roleOwner + `"].contains(principal.role) && + action in [Archie::Action::"read", Archie::Action::"read_logs"] +};` + +// orgEditPolicy is a developer's grant: create and edit workspace resources +// and org workflows, and run them. +const orgEditPolicy = `permit(principal, action, resource) when { + resource.org == principal.org && + ["` + roleDeveloper + `", "` + roleAdmin + `", "` + roleOwner + `"].contains(principal.role) && + action in [Archie::Action::"create", Archie::Action::"update", Archie::Action::"run"] +};` + +// orgAdminPolicy is an admin's grant: approve, secret values, member and +// identity management, policy management, and deletion of every record that +// is not the org itself. +const orgAdminPolicy = `permit(principal, action, resource) when { + resource.org == principal.org && + ["` + roleAdmin + `", "` + roleOwner + `"].contains(principal.role) && + (action != Archie::Action::"delete" || resource.kind != "org") +};` + +// orgOwnerPolicy is the owner's grant: everything in the org, including +// deleting it. +const orgOwnerPolicy = `permit(principal, action, resource) when { + resource.org == principal.org && + principal.role == "` + roleOwner + `" +};` + +// ShippedOrgPolicies returns the four shipped role policies for one org, as +// the store seeds them and `archied access reset --org` restores them. +func ShippedOrgPolicies(orgID org.OrgID) []Policy { + return []Policy{ + {ID: PolicyOrgRead, Level: LevelOrg, OrgID: orgID, Text: orgReadPolicy}, + {ID: PolicyOrgEdit, Level: LevelOrg, OrgID: orgID, Text: orgEditPolicy}, + {ID: PolicyOrgAdmin, Level: LevelOrg, OrgID: orgID, Text: orgAdminPolicy}, + {ID: PolicyOrgOwner, Level: LevelOrg, OrgID: orgID, Text: orgOwnerPolicy}, + } +} + +// CrossOrgForbidID is the ID the shipped cross-org forbid is known by in +// denial records. The forbid is engine-enforced, never stored, so it cannot +// be edited away or removed by `archied access reset --instance`. +const CrossOrgForbidID = PolicyCrossOrgID + +// The cross-org forbid's semantics, carried as text for the policy surface +// and the reset command's audit trail. The engine enforces it structurally +// (a principal never reaches a resource outside its org) before any Cedar +// runs, which is what makes it non-removable. +const CrossOrgForbidText = `forbid(principal, action, resource) when { + resource.org != principal.org; +};` diff --git a/internal/domain/access/store.go b/internal/domain/access/store.go new file mode 100644 index 000000000..a4fb9c844 --- /dev/null +++ b/internal/domain/access/store.go @@ -0,0 +1,53 @@ +// The persistence contracts for policies and denial records. The State Store +// implements them (internal/infrastructure/postgres); composition wires them +// like org.Repository. +package access + +import ( + "context" + + "github.com/samcharles93/archie-core/internal/domain/org" +) + +// PolicyStore persists stored policies. Versioned per level: PutPolicy +// returns the level's new version, so a policy change is one version bump +// the engine's next load can detect. Every change is an audit event naming +// who made it. +type PolicyStore interface { + // ListPolicies returns every stored policy across levels. + ListPolicies(ctx context.Context) ([]Policy, error) + // PutPolicy stores or replaces one policy by its (level, scope, ID) + // key, and returns the level's new version. + PutPolicy(ctx context.Context, p Policy) (int64, error) + // DeletePolicy removes one stored policy; an unknown key is + // ErrPolicyNotFound. + DeletePolicy(ctx context.Context, p Policy) error + // EnsureShippedOrgPolicies seeds an org's shipped role policies when it + // has none; an org that already carries them is left untouched, so a + // restart never overwrites an edited role policy. + EnsureShippedOrgPolicies(ctx context.Context, orgID org.OrgID) error +} + +// Resetter restores access for a locked-out org or a broken instance policy +// (docs/prds/orgs-and-access.md, "Recovering from a locked-out org"). It +// runs only on the State Store host, never over the network, and the reset +// command records it as an audit event. +type Resetter interface { + // ResetOrgPolicies restores the shipped role policies for one org and + // removes its other org-level policies. + ResetOrgPolicies(ctx context.Context, orgID org.OrgID) error + // ResetInstancePolicies removes every stored instance policy. The + // cross-org forbid is engine-enforced and survives any reset. + ResetInstancePolicies(ctx context.Context) error +} + +// DenialStore records and lists denial records. The store coalesces +// identical denials within a minute into one row with a count, so a retry +// storm does not flood the surface. +type DenialStore interface { + // RecordDenial records one refusal with the level that decided it and + // the deciding policies. + RecordDenial(ctx context.Context, d Denial) error + // ListDenials returns an org's most recent denials, newest first. + ListDenials(ctx context.Context, orgID org.OrgID, limit int) ([]Denial, error) +} diff --git a/internal/infrastructure/access/engine.go b/internal/infrastructure/access/engine.go new file mode 100644 index 000000000..460b8c3de --- /dev/null +++ b/internal/infrastructure/access/engine.go @@ -0,0 +1,280 @@ +// Package access implements internal/domain/access's Authorizer with +// github.com/cedar-policy/cedar-go. The engine owns policy parsing and +// validation against the shipped Cedar schema, and the chain evaluation: +// instance ▶ org ▶ workspace ▶ object, where a level with policies must +// permit, a forbid at any level wins, and with no permit the request is +// denied (docs/prds/orgs-and-access.md). +// +// The cross-org forbid is enforced here, structurally, before any Cedar +// runs: a principal never reaches a resource outside its org. It is not a +// stored policy, so it cannot be edited away or removed by +// `archied access reset`. +package access + +import ( + "fmt" + + cedar "github.com/cedar-policy/cedar-go" + "github.com/cedar-policy/cedar-go/types" + expast "github.com/cedar-policy/cedar-go/x/exp/ast" + schema "github.com/cedar-policy/cedar-go/x/exp/schema" + validate "github.com/cedar-policy/cedar-go/x/exp/schema/validate" + + "github.com/samcharles93/archie-core/internal/domain/access" + "github.com/samcharles93/archie-core/internal/domain/org" +) + +// schemaText is the Cedar schema the engine validates every policy against. +// It names the entity vocabulary internal/domain/access defines: an +// Identity principal carrying its org and effective role, the org and +// workspace parents, one Object entity per record, and one Action per +// action. Context carries the event's signature result, the address it came +// from, and the run and step of an agent's request. +const schemaText = `namespace Archie { + entity Identity in [Org] = {"org": String, "role": String}; + entity Org; + entity Workspace in [Org] = {"org": String}; + entity Object in [Org, Workspace] = {"org": String, "workspace": String, "kind": String, "owner": String, "state": String}; + action read appliesTo { principal: Identity, resource: Object, context: {signature: String, addr: ipaddr, time: datetime, run: String, step: String} }; + action create appliesTo { principal: Identity, resource: Object, context: {signature: String, addr: ipaddr, time: datetime, run: String, step: String} }; + action update appliesTo { principal: Identity, resource: Object, context: {signature: String, addr: ipaddr, time: datetime, run: String, step: String} }; + action delete appliesTo { principal: Identity, resource: Object, context: {signature: String, addr: ipaddr, time: datetime, run: String, step: String} }; + action approve appliesTo { principal: Identity, resource: Object, context: {signature: String, addr: ipaddr, time: datetime, run: String, step: String} }; + action run appliesTo { principal: Identity, resource: Object, context: {signature: String, addr: ipaddr, time: datetime, run: String, step: String} }; + action read_logs appliesTo { principal: Identity, resource: Object, context: {signature: String, addr: ipaddr, time: datetime, run: String, step: String} }; + action read_secret appliesTo { principal: Identity, resource: Object, context: {signature: String, addr: ipaddr, time: datetime, run: String, step: String} }; + action manage_members appliesTo { principal: Identity, resource: Object, context: {signature: String, addr: ipaddr, time: datetime, run: String, step: String} }; + action manage_identities appliesTo { principal: Identity, resource: Object, context: {signature: String, addr: ipaddr, time: datetime, run: String, step: String} }; + action manage_policies appliesTo { principal: Identity, resource: Object, context: {signature: String, addr: ipaddr, time: datetime, run: String, step: String} }; +}` + +// Problem is one stored policy the engine could not validate. It is what a +// health issue names: the policy and the error +// (docs/prds/orgs-and-access.md, "Storing and changing policies"). +type Problem struct { + Policy access.Policy + Err error +} + +// levelSet is one chain level's parsed policies. invalid is non-nil when +// any of the level's policies failed to compile: the level then refuses +// every request and none of its policies is evaluated. +type levelSet struct { + at access.Level + ids []string + set *cedar.PolicySet + invalid error +} + +// active reports whether the level carries policies at all: a level whose +// policies failed to compile is active too, because it refuses everything. +func (l *levelSet) active() bool { return l != nil && (len(l.ids) > 0 || l.invalid != nil) } + +// Engine evaluates the chain. It is immutable after construction: a policy +// change rebuilds it from a fresh snapshot of the store. +type Engine struct { + instance *levelSet + orgs map[org.OrgID]*levelSet + spaces map[spaceKey]*levelSet + objects map[objectKey]*levelSet + problems []Problem +} + +type ( + spaceKey struct { + org org.OrgID + ws org.WorkspaceID + } + objectKey struct { + org org.OrgID + ws org.WorkspaceID + kind access.ResourceKind + id string + } +) + +// The engine satisfies the domain contracts. +var ( + _ access.Authorizer = (*Engine)(nil) + _ access.Validator = (*Engine)(nil) +) + +// New builds an engine over one snapshot of the stored policies. An invalid +// instance policy is a boot failure: it returns (nil, err) and archie stops +// serving until the policy is fixed. An invalid org, workspace or object +// policy becomes a Problem and makes its level deny everything -- the other +// levels still serve, and the health surface reports the problem by name. +func New(policies []access.Policy) (*Engine, error) { + e := &Engine{ + orgs: map[org.OrgID]*levelSet{}, + spaces: map[spaceKey]*levelSet{}, + objects: map[objectKey]*levelSet{}, + } + for _, p := range policies { + lvl := e.level(p) + policy, err := compile(p) + if err != nil { + if p.Level == access.LevelInstance { + return nil, fmt.Errorf("access: instance policy %q: %w", p.ID, err) + } + // The refusal must name the policy that poisoned the level. + lvl.ids = append(lvl.ids, p.ID) + lvl.invalid = err + e.problems = append(e.problems, Problem{Policy: p, Err: err}) + continue + } + lvl.ids = append(lvl.ids, p.ID) + lvl.set.Add(types.PolicyID(p.ID), policy) + } + return e, nil +} + +// Problems reports every stored policy the engine could not compile. Empty +// when every stored policy is valid. +func (e *Engine) Problems() []Problem { return e.problems } + +// key locates the level set the policy belongs to, creating it on first use. +func (e *Engine) level(p access.Policy) *levelSet { + switch p.Level { + case access.LevelInstance: + if e.instance == nil { + e.instance = &levelSet{at: p.Level, set: cedar.NewPolicySet()} + } + return e.instance + case access.LevelOrg: + id := p.OrgID + if lvl, ok := e.orgs[id]; ok { + return lvl + } + lvl := &levelSet{at: p.Level, set: cedar.NewPolicySet()} + e.orgs[id] = lvl + return lvl + case access.LevelWorkspace: + id := spaceKey{p.OrgID, p.WorkspaceID} + if lvl, ok := e.spaces[id]; ok { + return lvl + } + lvl := &levelSet{at: p.Level, set: cedar.NewPolicySet()} + e.spaces[id] = lvl + return lvl + case access.LevelObject: + id := objectKey{p.OrgID, p.WorkspaceID, p.ObjectKind, p.ObjectID} + if lvl, ok := e.objects[id]; ok { + return lvl + } + lvl := &levelSet{at: p.Level, set: cedar.NewPolicySet()} + e.objects[id] = lvl + return lvl + } + return nil +} + +// Validate checks one policy against the schema: the save-time check the +// domain's Validator contract requires, and the re-check every start of +// archie performs by rebuilding the engine from the store. +func (e *Engine) Validate(p access.Policy) error { + _, err := compile(p) + return err +} + +// compile parses and validates one policy: structural shape, Cedar syntax, +// then the schema. +func compile(p access.Policy) (*cedar.Policy, error) { + if err := p.Validate(); err != nil { + return nil, err + } + pls, err := cedar.NewPolicyListFromBytes(p.ID, []byte(p.Text)) + if err != nil { + return nil, fmt.Errorf("%w: %w", access.ErrPolicyInvalidText, err) + } + if len(pls) != 1 { + return nil, fmt.Errorf("%w: %s carries %d policies, want exactly one", access.ErrPolicyInvalidText, p.ID, len(pls)) + } + v, err := schemaValidator() + if err != nil { + return nil, err + } + if err := v.Policy(p.ID, (*expast.Policy)(pls[0].AST())); err != nil { + return nil, fmt.Errorf("%w: %w", access.ErrPolicyInvalidText, err) + } + return pls[0], nil +} + +// Authorize evaluates the chain for one request. +func (e *Engine) Authorize(p access.Principal, a access.Action, r access.Resource, c access.Context) access.Decision { + // The cross-org forbid, enforced structurally: a principal's requests + // only ever reach its own org. An unset resource org means the + // principal's org (a create request names a record that does not exist + // yet); an org-less principal is denied everything. + resOrg := r.Org + if resOrg == "" { + resOrg = p.Org + } + if p.Org == "" || resOrg != p.Org { + return access.DeniedAt(access.LevelInstance, []string{access.CrossOrgForbidID}) + } + + request := buildRequest(p, a, r, c) + entities := buildEntities(p, r) + + for _, lvl := range e.chain(r) { + if !lvl.active() { + continue + } + if lvl.invalid != nil { + decision := access.DeniedAt(lvl.at, lvl.ids) + decision.Err = lvl.invalid + return decision + } + decision, diag := cedar.Authorize(lvl.set, entities, request) + if decision == cedar.Allow { + continue + } + ids := make([]string, 0, len(diag.Reasons)) + for _, reason := range diag.Reasons { + ids = append(ids, string(reason.PolicyID)) + } + if len(ids) == 0 { + // No permit at a level with policies: the level denied by + // default, not through any one policy. Name the level's + // policies so the denial record still says what stood between + // the principal and the record. + ids = lvl.ids + } + return access.DeniedAt(lvl.at, ids) + } + return access.Allowed() +} + +// chain returns the level sets the request passes through, in order. +func (e *Engine) chain(r access.Resource) []*levelSet { + out := []*levelSet{e.instance} + if l, ok := e.orgs[r.Org]; ok { + out = append(out, l) + } + if r.Workspace != "" { + if l, ok := e.spaces[spaceKey{r.Org, r.Workspace}]; ok { + out = append(out, l) + } + } + if r.Org != "" && r.ID != "" { + if l, ok := e.objects[objectKey{r.Org, r.Workspace, r.Kind, r.ID}]; ok { + out = append(out, l) + } + } + return out +} + +// schemaValidator returns the resolved schema, building it once. The schema +// is part of the shipped vocabulary and cannot change at runtime. +func schemaValidator() (*validate.Validator, error) { + var sch schema.Schema + if err := sch.UnmarshalCedar([]byte(schemaText)); err != nil { + return nil, err + } + resolved, err := sch.Resolve() + if err != nil { + return nil, err + } + return validate.New(resolved), nil +} diff --git a/internal/infrastructure/access/engine_test.go b/internal/infrastructure/access/engine_test.go new file mode 100644 index 000000000..c852ff4ed --- /dev/null +++ b/internal/infrastructure/access/engine_test.go @@ -0,0 +1,250 @@ +package access + +import ( + "errors" + "testing" + + "github.com/samcharles93/archie-core/internal/domain/access" + "github.com/samcharles93/archie-core/internal/domain/identity" + "github.com/samcharles93/archie-core/internal/domain/org" +) + +const acme = "acme" + +func principal(role org.Role) access.Principal { + return access.Principal{ + IdentityID: identity.IdentityID("11111111-1111-5111-8111-111111111111"), + Kind: identity.KindUser, + Org: acme, + Memberships: []org.Membership{ + {IdentityID: identity.IdentityID("11111111-1111-5111-8111-111111111111"), OrgID: acme, Role: role}, + }, + } +} + +func resource(kind access.ResourceKind, id string) access.Resource { + return access.Resource{Kind: kind, ID: id, Org: acme, Workspace: "net"} +} + +func newEngine(t *testing.T, policies ...access.Policy) *Engine { + t.Helper() + e, err := New(policies) + if err != nil { + t.Fatalf("New() = %v, want nil", err) + } + return e +} + +func TestShippedRoleMatrix(t *testing.T) { + shipped := access.ShippedOrgPolicies(acme) + e := newEngine(t, shipped...) + + tests := []struct { + name string + role org.Role + action access.Action + kind access.ResourceKind + id string + wantAllow bool + }{ + // Viewer: read everything except secret values. + {name: "viewer reads a binding", role: org.RoleViewer, action: access.ActionRead, kind: access.KindBinding, id: "b1", wantAllow: true}, + {name: "viewer reads logs", role: org.RoleViewer, action: access.ActionReadLogs, kind: access.KindTask, id: "1", wantAllow: true}, + {name: "viewer cannot read a secret", role: org.RoleViewer, action: access.ActionReadSecret, kind: access.KindSecret, id: "firewall-api"}, + {name: "viewer cannot create", role: org.RoleViewer, action: access.ActionCreate, kind: access.KindBinding, id: "b1"}, + {name: "viewer cannot run", role: org.RoleViewer, action: access.ActionRun, kind: access.KindWorkflow, id: "implement"}, + // Developer: create and edit, run, read logs -- no approve, no delete, + // no secret values. + {name: "developer creates a binding", role: org.RoleDeveloper, action: access.ActionCreate, kind: access.KindBinding, id: "b1", wantAllow: true}, + {name: "developer edits a mapping", role: org.RoleDeveloper, action: access.ActionUpdate, kind: access.KindMapping, id: "m1", wantAllow: true}, + {name: "developer runs a workflow", role: org.RoleDeveloper, action: access.ActionRun, kind: access.KindWorkflow, id: "implement", wantAllow: true}, + {name: "developer cannot approve", role: org.RoleDeveloper, action: access.ActionApprove, kind: access.KindBinding, id: "b1"}, + {name: "developer cannot delete", role: org.RoleDeveloper, action: access.ActionDelete, kind: access.KindBinding, id: "b1"}, + {name: "developer cannot read a secret", role: org.RoleDeveloper, action: access.ActionReadSecret, kind: access.KindSecret, id: "firewall-api"}, + {name: "developer cannot manage members", role: org.RoleDeveloper, action: access.ActionManageMembers, kind: access.KindMember, id: "u2"}, + // Admin: everything except deleting the org. + {name: "admin approves a binding", role: org.RoleAdmin, action: access.ActionApprove, kind: access.KindBinding, id: "b1", wantAllow: true}, + {name: "admin deletes a binding", role: org.RoleAdmin, action: access.ActionDelete, kind: access.KindBinding, id: "b1", wantAllow: true}, + {name: "admin deletes the org is denied", role: org.RoleAdmin, action: access.ActionDelete, kind: access.KindOrg, id: acme}, + {name: "admin reads a secret", role: org.RoleAdmin, action: access.ActionReadSecret, kind: access.KindSecret, id: "firewall-api", wantAllow: true}, + {name: "admin manages policies", role: org.RoleAdmin, action: access.ActionManagePolicies, kind: access.KindPolicy, id: "p1", wantAllow: true}, + // Owner: everything in the org, including deleting it. + {name: "owner deletes the org", role: org.RoleOwner, action: access.ActionDelete, kind: access.KindOrg, id: acme, wantAllow: true}, + {name: "owner manages identities", role: org.RoleOwner, action: access.ActionManageIdentities, kind: access.KindIdentity, id: "u2", wantAllow: true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := e.Authorize(principal(tt.role), tt.action, resource(tt.kind, tt.id), access.Context{}) + if got.Allowed != tt.wantAllow { + t.Fatalf("Authorize(%s, %s, %s/%s) allowed=%v level=%v policies=%v, want allow=%v", + tt.role, tt.action, tt.kind, tt.id, got.Allowed, got.Level, got.Policies, tt.wantAllow) + } + }) + } +} + +func TestCrossOrgForbid(t *testing.T) { + e := newEngine(t, access.ShippedOrgPolicies(acme)...) + p := access.Principal{ + IdentityID: identity.IdentityID("11111111-1111-5111-8111-111111111111"), + Org: acme, + Memberships: []org.Membership{ + {IdentityID: identity.IdentityID("11111111-1111-5111-8111-111111111111"), OrgID: acme, Role: org.RoleOwner}, + }, + } + got := e.Authorize(p, access.ActionRead, access.Resource{Kind: access.KindBinding, ID: "b1", Org: "other", Workspace: "net"}, access.Context{}) + if got.Allowed { + t.Fatal("owner read of another org's binding was allowed; the cross-org forbid must win") + } + if got.Level != access.LevelInstance || len(got.Policies) != 1 || got.Policies[0] != access.CrossOrgForbidID { + t.Fatalf("denial = level %v policies %v, want instance level with %q", got.Level, got.Policies, access.CrossOrgForbidID) + } + + // An org-less principal is denied everything. + agentless := p + agentless.Org = "" + if got := e.Authorize(agentless, access.ActionRead, resource(access.KindBinding, "b1"), access.Context{}); got.Allowed { + t.Fatal("org-less principal was allowed") + } + + // A create request with no resource org is the principal's own org. + create := resource(access.KindBinding, "b1") + create.Org = "" + if got := e.Authorize(principal(org.RoleDeveloper), access.ActionCreate, create, access.Context{}); !got.Allowed { + t.Fatalf("create in own org denied: level=%v policies=%v", got.Level, got.Policies) + } +} + +func TestWorkspacePolicyCannotWidenOrg(t *testing.T) { + // The org forbids run where the workspace is production; a workspace + // policy permitting run has no effect. + orgPolicies := access.ShippedOrgPolicies(acme) + orgPolicies = append(orgPolicies, access.Policy{ + ID: "org-no-run-production", Level: access.LevelOrg, OrgID: acme, + Text: `forbid(principal, action == Archie::Action::"run", resource) when { resource.workspace == "production" };`, + }) + workspace := access.Policy{ + ID: "ws-allow-run", Level: access.LevelWorkspace, OrgID: acme, WorkspaceID: "production", + Text: `permit(principal, action, resource) when { action == Archie::Action::"run" };`, + } + e := newEngine(t, append(orgPolicies, workspace)...) + r := resource(access.KindWorkflow, "implement") + r.Workspace = "production" + got := e.Authorize(principal(org.RoleDeveloper), access.ActionRun, r, access.Context{}) + if got.Allowed { + t.Fatal("workspace policy widened an org forbid") + } + if got.Level != access.LevelOrg || got.Policies[0] != "org-no-run-production" { + t.Fatalf("denial decided at %v by %v, want the org policy", got.Level, got.Policies) + } +} + +func TestObjectPolicyNarrows(t *testing.T) { + // Only one identity may read the firewall-api secret. + socID := identity.IdentityID("33333333-3333-5333-8333-333333333333") + object := access.Policy{ + ID: "secret-soc-only", Level: access.LevelObject, OrgID: acme, WorkspaceID: "net", + ObjectKind: access.KindSecret, ObjectID: "firewall-api", + Text: `permit(principal, action == Archie::Action::"read_secret", resource) when { + principal == Archie::Identity::"` + string(socID) + `" +};`, + } + e := newEngine(t, append(access.ShippedOrgPolicies(acme), object)...) + + // An admin would otherwise read it, but the object level narrows: the + // object policy has no permit for this principal, so the level denies. + admin := principal(org.RoleAdmin) + admin.IdentityID = identity.IdentityID("22222222-2222-5222-8222-222222222222") + got := e.Authorize(admin, access.ActionReadSecret, resource(access.KindSecret, "firewall-api"), access.Context{}) + if got.Allowed { + t.Fatal("admin read a secret the object policy narrows away") + } + if got.Level != access.LevelObject { + t.Fatalf("denial decided at %v, want object level", got.Level) + } + + soc := admin + soc.IdentityID = socID + if got := e.Authorize(soc, access.ActionReadSecret, resource(access.KindSecret, "firewall-api"), access.Context{}); !got.Allowed { + t.Fatalf("permitted identity denied: level=%v policies=%v", got.Level, got.Policies) + } +} + +func TestInvalidPolicyDeniesItsLevel(t *testing.T) { + invalid := access.Policy{ + ID: "broken-workspace", Level: access.LevelWorkspace, OrgID: acme, WorkspaceID: "net", + Text: `permit(principal, action, resource) when { principal.bogus == "x" };`, + } + e := newEngine(t, append(access.ShippedOrgPolicies(acme), invalid)...) + problems := e.Problems() + if len(problems) != 1 || problems[0].Policy.ID != "broken-workspace" { + t.Fatalf("Problems() = %+v, want one entry for broken-workspace", problems) + } + if !errors.Is(problems[0].Err, access.ErrPolicyInvalidText) { + t.Fatalf("problem err = %v, want ErrPolicyInvalidText", problems[0].Err) + } + // The workspace level denies everything, even what the org permits. + got := e.Authorize(principal(org.RoleOwner), access.ActionRead, resource(access.KindBinding, "b1"), access.Context{}) + if got.Allowed || got.Level != access.LevelWorkspace { + t.Fatalf("level with an invalid policy did not refuse: %+v", got) + } + if !errors.Is(got.Err, access.ErrPolicyInvalidText) { + t.Fatalf("decision err = %v, want ErrPolicyInvalidText", got.Err) + } + // The denial record names the level's policies. + if len(got.Policies) == 0 || got.Policies[0] != "broken-workspace" { + t.Fatalf("refusal named %v, want the level's policy", got.Policies) + } +} + +func TestInvalidInstancePolicyStopsServing(t *testing.T) { + if _, err := New([]access.Policy{ + {ID: "broken-instance", Level: access.LevelInstance, Text: `permit(principal, action, resource) when { resource.nope == 1 };`}, + }); err == nil { + t.Fatal("New() accepted an invalid instance policy; archie must stop serving") + } +} + +func TestValidateRefusesUnknownVocabulary(t *testing.T) { + e := newEngine(t) + bad := access.Policy{ID: "p1", Level: access.LevelOrg, OrgID: acme, Text: `permit(principal, action, resource) when { resource.wat == "x" };`} + if err := e.Validate(bad); !errors.Is(err, access.ErrPolicyInvalidText) { + t.Fatalf("Validate(unknown attribute) = %v, want ErrPolicyInvalidText", err) + } + badText := access.Policy{ID: "p2", Level: access.LevelOrg, OrgID: acme, Text: `permit(principal, action, resource) when { principal.org == 42 };`} + if err := e.Validate(badText); !errors.Is(err, access.ErrPolicyInvalidText) { + t.Fatalf("Validate(type error) = %v, want ErrPolicyInvalidText", err) + } + multi := access.Policy{ID: "p3", Level: access.LevelOrg, OrgID: acme, Text: `permit(principal, action, resource); permit(principal, action, resource);`} + if err := e.Validate(multi); !errors.Is(err, access.ErrPolicyInvalidText) { + t.Fatalf("Validate(multiple policies) = %v, want ErrPolicyInvalidText", err) + } +} + +func TestWorkspaceRoleNarrowsTheOrgRole(t *testing.T) { + // A developer org-wide, viewer in the net workspace: read-only there. + p := principal(org.RoleDeveloper) + p.Memberships = append(p.Memberships, org.Membership{IdentityID: p.IdentityID, OrgID: acme, WorkspaceID: "net", Role: org.RoleViewer}) + e := newEngine(t, access.ShippedOrgPolicies(acme)...) + if got := e.Authorize(p, access.ActionRead, resource(access.KindBinding, "b1"), access.Context{}); !got.Allowed { + t.Fatalf("viewer-in-workspace denied a read: %+v", got) + } + if got := e.Authorize(p, access.ActionCreate, resource(access.KindBinding, "b1"), access.Context{}); got.Allowed { + t.Fatal("workspace viewer role did not narrow the org-wide developer role") + } +} + +func TestDenialNamesDecidingPolicies(t *testing.T) { + e := newEngine(t, access.ShippedOrgPolicies(acme)...) + // A viewer denied create is decided by the org level, whose only + // policies are the shipped role set. + got := e.Authorize(principal(org.RoleViewer), access.ActionCreate, resource(access.KindBinding, "b1"), access.Context{}) + if got.Level != access.LevelOrg { + t.Fatalf("level = %v, want org", got.Level) + } + for _, id := range got.Policies { + if id != access.PolicyOrgRead && id != access.PolicyOrgEdit && id != access.PolicyOrgAdmin && id != access.PolicyOrgOwner { + t.Fatalf("denial names an unknown policy %q", id) + } + } +} diff --git a/internal/infrastructure/access/entities.go b/internal/infrastructure/access/entities.go new file mode 100644 index 000000000..e79bcbfef --- /dev/null +++ b/internal/infrastructure/access/entities.go @@ -0,0 +1,106 @@ +// Entity assembly: the engine's view of internal/domain/access's Principal, +// Resource and Context. The vocabulary (entity types, attributes) is the +// domain's; the shape is what the shipped schema declares. +package access + +import ( + "time" + + cedar "github.com/cedar-policy/cedar-go" + "github.com/cedar-policy/cedar-go/types" + + "github.com/samcharles93/archie-core/internal/domain/access" +) + +// buildRequest turns the assembled request into the engine's shape. The +// context record carries only the fields that were set: a policy testing a +// field the caller did not supply cannot match, which is the fail-closed +// reading of "context: the event's signature result, the address it came +// from, the time, and the run and step when the principal is an agent". +func buildRequest(p access.Principal, a access.Action, r access.Resource, c access.Context) types.Request { + record := types.RecordMap{} + if c.Signature != "" { + record["signature"] = types.String(c.Signature) + } + if c.Addr != "" { + if addr, err := types.ParseIPAddr(c.Addr); err == nil { + record["addr"] = addr + } + } + if c.Run != "" { + record["run"] = types.String(c.Run) + } + if c.Step != "" { + record["step"] = types.String(c.Step) + } + // The context always carries a time: the zero Time resolves to now. + at := c.Time + if at.IsZero() { + at = time.Now().UTC() + } + record["time"] = types.NewDatetime(at) + + return types.Request{ + Principal: types.NewEntityUID(access.EntityTypeIdentity, types.String(p.IdentityID)), + Action: types.NewEntityUID(access.EntityTypeAction, types.String(string(a))), + Resource: types.NewEntityUID(access.EntityTypeObject, types.String(r.ID)), + Context: types.NewRecord(record), + } +} + +// buildEntities assembles the entity graph policies may walk: the principal +// (its org and effective role), the resource (its kind, org, workspace, +// owner and state), and the org and workspace parents the resource hangs +// from. A policy naming a parent the request does not supply simply does +// not match. +func buildEntities(p access.Principal, r access.Resource) cedar.EntityMap { + resOrg := r.Org + if resOrg == "" { + resOrg = p.Org + } + entities := cedar.EntityMap{} + orgUID := types.NewEntityUID(access.EntityTypeOrg, types.String(resOrg)) + entities[orgUID] = cedar.Entity{UID: orgUID} + + principalUID := types.NewEntityUID(access.EntityTypeIdentity, types.String(p.IdentityID)) + entities[principalUID] = cedar.Entity{ + UID: principalUID, + // The principal's parent chain is its org; a policy may write + // `principal in Archie::Org::"acme"`. + Parents: cedar.NewEntityUIDSet(orgUID), + Attributes: types.NewRecord(types.RecordMap{ + "org": types.String(resOrg), + "role": types.String(string(p.Role(r.Workspace))), + }), + } + + parents := []types.EntityUID{orgUID} + if r.Workspace != "" { + wsUID := types.NewEntityUID(access.EntityTypeWorkspace, types.String(r.Workspace)) + entities[wsUID] = cedar.Entity{ + UID: wsUID, + Parents: cedar.NewEntityUIDSet(orgUID), + Attributes: types.NewRecord(types.RecordMap{"org": types.String(resOrg)}), + } + parents = append(parents, wsUID) + } + + resUID := types.NewEntityUID(access.EntityTypeObject, types.String(r.ID)) + attrs := types.RecordMap{ + "org": types.String(resOrg), + "workspace": types.String(string(r.Workspace)), + "kind": types.String(string(r.Kind)), + } + if r.Owner != "" { + attrs["owner"] = types.String(string(r.Owner)) + } + if r.State != "" { + attrs["state"] = types.String(r.State) + } + entities[resUID] = cedar.Entity{ + UID: resUID, + Parents: cedar.NewEntityUIDSet(parents...), + Attributes: types.NewRecord(attrs), + } + return entities +} diff --git a/internal/infrastructure/postgres/access.go b/internal/infrastructure/postgres/access.go new file mode 100644 index 000000000..f002e8465 --- /dev/null +++ b/internal/infrastructure/postgres/access.go @@ -0,0 +1,239 @@ +// Access policies and denial records: the Postgres implementation of +// internal/domain/access's PolicyStore, Resetter and DenialStore +// (docs/prds/orgs-and-access.md). Policy changes are versioned per level +// scope and audited as one sys_audit row per change naming who made it. +package postgres + +import ( + "context" + "encoding/json" + "fmt" + "strings" + + "github.com/jackc/pgx/v5" + + "github.com/samcharles93/archie-core/internal/domain/access" + "github.com/samcharles93/archie-core/internal/domain/identity" + "github.com/samcharles93/archie-core/internal/domain/org" + "github.com/samcharles93/archie-core/internal/infrastructure/postgres/postgresdb" +) + +var ( + _ access.PolicyStore = (*Store)(nil) + _ access.Resetter = (*Store)(nil) + _ access.DenialStore = (*Store)(nil) +) + +// shippedOrgPolicyIDs lists an org's shipped role policy IDs: the seed's +// conflict keys, and what an org reset keeps. +func shippedOrgPolicyIDs() []string { + ids := make([]string, 0, 4) + for _, p := range access.ShippedOrgPolicies("") { + ids = append(ids, p.ID) + } + return ids +} + +// accessScopeOf is the scope tuple every access query carries. +func accessScopeOf(p access.Policy) (string, string, string, string, string, string) { + return string(p.Level), string(p.OrgID), string(p.WorkspaceID), + string(p.ObjectKind), p.ObjectID, p.ID +} + +// auditKey is the sys_audit record_key for one policy: its scope and ID, so +// an operator can trace one policy document's changes. +func auditKey(p access.Policy) string { + joined := strings.Join([]string{ + string(p.Level), string(p.OrgID), string(p.WorkspaceID), + string(p.ObjectKind), p.ObjectID, p.ID, + }, "/") + return strings.Trim(joined, "/") +} + +// textJSON wraps a policy text as the JSON string sys_audit stores. +func textJSON(text string) []byte { + out, _ := json.Marshal(text) + return out +} + +// ListPolicies returns every stored policy across levels. +func (s *Store) ListPolicies(ctx context.Context) ([]access.Policy, error) { + rows, err := s.queries().ListAccessPolicies(ctx) + if err != nil { + return nil, err + } + out := make([]access.Policy, 0, len(rows)) + for _, r := range rows { + out = append(out, access.Policy{ + ID: r.PolicyID, + Level: access.Level(r.Level), + OrgID: org.OrgID(r.OrgID), + WorkspaceID: org.WorkspaceID(r.WorkspaceID), + ObjectKind: access.ResourceKind(r.ObjectKind), + ObjectID: r.ObjectID, + Text: r.Text, + }) + } + return out, nil +} + +// PutPolicy stores or replaces one policy by its scope+ID key, bumps the +// level's version, and writes the audit row -- in one transaction, so a +// version that never moved cannot advertise a change that half-landed. +func (s *Store) PutPolicy(ctx context.Context, p access.Policy) (int64, error) { + if err := p.Validate(); err != nil { + return 0, err + } + q := s.queries() + level, orgID, wsID, kind, id, policyID := accessScopeOf(p) + var version int64 + err := pgx.BeginFunc(ctx, s.pool, func(tx pgx.Tx) error { + q := q.WithTx(tx) + if err := q.UpsertAccessPolicy(ctx, postgresdb.UpsertAccessPolicyParams{ + Level: level, OrgID: orgID, WorkspaceID: wsID, + ObjectKind: kind, ObjectID: id, + PolicyID: policyID, Text: p.Text, + }); err != nil { + return err + } + v, err := q.UpsertAccessPolicyVersion(ctx, postgresdb.UpsertAccessPolicyVersionParams{ + Level: level, OrgID: orgID, WorkspaceID: wsID, + }) + if err != nil { + return err + } + version = v + return q.InsertAccessPolicyAudit(ctx, postgresdb.InsertAccessPolicyAuditParams{ + RecordKey: auditKey(p), + NewValue: textJSON(p.Text), + RecordVersion: version, + Actor: "archied", + Source: "archied", + RequestID: "", + }) + }) + if err != nil { + return 0, err + } + return version, nil +} + +// DeletePolicy removes one stored policy; an unknown key is +// ErrPolicyNotFound. +func (s *Store) DeletePolicy(ctx context.Context, p access.Policy) error { + if err := p.Validate(); err != nil { + return err + } + level, orgID, wsID, kind, id, policyID := accessScopeOf(p) + deleted, err := s.queries().DeleteAccessPolicy(ctx, postgresdb.DeleteAccessPolicyParams{ + Level: level, OrgID: orgID, WorkspaceID: wsID, + ObjectKind: kind, ObjectID: id, PolicyID: policyID, + }) + if err != nil { + return err + } + if deleted == 0 { + return access.ErrPolicyNotFound + } + if _, err := s.queries().UpsertAccessPolicyVersion(ctx, postgresdb.UpsertAccessPolicyVersionParams{ + Level: level, OrgID: orgID, WorkspaceID: wsID, + }); err != nil { + return err + } + // A level-scope with no policies left keeps no version row. + return s.queries().DeleteAccessPolicyVersion(ctx, postgresdb.DeleteAccessPolicyVersionParams{ + Level: level, OrgID: orgID, WorkspaceID: wsID, + }) +} + +// EnsureShippedOrgPolicies seeds an org's shipped role policies when it +// carries none of them, so a restart never overwrites an edited role policy. +func (s *Store) EnsureShippedOrgPolicies(ctx context.Context, orgID org.OrgID) error { + shipped := access.ShippedOrgPolicies(orgID) + count, err := s.queries().CountShippedOrgPolicies(ctx, postgresdb.CountShippedOrgPoliciesParams{ + OrgID: string(orgID), Column2: shippedOrgPolicyIDs(), + }) + if err != nil { + return err + } + if count > 0 { + return nil + } + for _, p := range shipped { + if _, err := s.PutPolicy(ctx, p); err != nil { + return err + } + } + return nil +} + +// ResetOrgPolicies restores the shipped role policies for one org and +// removes its other org-level policies. It is the store-side half of +// `archied access reset --org`, which runs on this host and records the +// reset as an audit event. +func (s *Store) ResetOrgPolicies(ctx context.Context, orgID org.OrgID) error { + if orgID == "" { + return fmt.Errorf("%w: no org", access.ErrInvalidPolicy) + } + if err := s.queries().DeleteOrgPoliciesNotShipped(ctx, postgresdb.DeleteOrgPoliciesNotShippedParams{ + OrgID: string(orgID), Column2: shippedOrgPolicyIDs(), + }); err != nil { + return err + } + for _, p := range access.ShippedOrgPolicies(orgID) { + if _, err := s.PutPolicy(ctx, p); err != nil { + return err + } + } + return nil +} + +// ResetInstancePolicies removes every stored instance policy. The +// cross-org forbid is engine-enforced and survives any reset. +func (s *Store) ResetInstancePolicies(ctx context.Context) error { + return s.queries().ResetInstancePolicies(ctx) +} + +// RecordResetAudit records the one audit row a reset is written as. +func (s *Store) RecordResetAudit(ctx context.Context, key string) error { + return s.queries().InsertAccessResetAudit(ctx, key) +} + +// RecordDenial records one refusal The store coalesces identical denials +// within a minute into one row with a count, so a retry storm does not +// flood the surface. +func (s *Store) RecordDenial(ctx context.Context, d access.Denial) error { + if d.Org == "" || d.Principal == "" { + return fmt.Errorf("%w: org and principal are required", access.ErrInvalidPolicy) + } + return s.queries().RecordDenial(ctx, postgresdb.RecordDenialParams{ + OrgID: string(d.Org), Principal: string(d.Principal), Action: string(d.Action), + ResourceKind: string(d.Kind), ResourceID: d.ResourceID, Level: string(d.Level), + Policies: d.Policies, + }) +} + +// ListDenials returns an org's most recent denials, newest first. +func (s *Store) ListDenials(ctx context.Context, orgID org.OrgID, limit int) ([]access.Denial, error) { + rows, err := s.queries().ListDenials(ctx, postgresdb.ListDenialsParams{ + OrgID: string(orgID), Limit: int32(limit), + }) + if err != nil { + return nil, err + } + out := make([]access.Denial, 0, len(rows)) + for _, r := range rows { + out = append(out, access.Denial{ + Principal: identity.IdentityID(r.Principal), + Org: org.OrgID(r.OrgID), + Action: access.Action(r.Action), + Kind: access.ResourceKind(r.ResourceKind), + ResourceID: r.ResourceID, + Level: access.Level(r.Level), + Policies: r.Policies, + At: r.CreatedAt, + Count: r.Count, + }) + } + return out, nil +} diff --git a/internal/infrastructure/postgres/access_test.go b/internal/infrastructure/postgres/access_test.go new file mode 100644 index 000000000..807fceaed --- /dev/null +++ b/internal/infrastructure/postgres/access_test.go @@ -0,0 +1,225 @@ +package postgres + +import ( + "errors" + "testing" + + "github.com/samcharles93/archie-core/internal/domain/access" + "github.com/samcharles93/archie-core/internal/domain/identity" +) + +func newStoreForAccess(t *testing.T) *Store { + t.Helper() + pool, _ := migrated(t) + return New(pool) +} + +func TestAccessPolicyStore(t *testing.T) { + s := newStoreForAccess(t) + ctx := t.Context() + + // PutPolicy stores one policy and reports a versioned level. + p := access.Policy{ + ID: "test-policy", Level: access.LevelOrg, OrgID: "soc", + Text: `permit(principal, action, resource) when { resource.kind == "binding" };`, + } + v1, err := s.PutPolicy(ctx, p) + if err != nil { + t.Fatalf("PutPolicy: %v", err) + } + if v1 != 2 { // the counter starts at 1; the first write bumps it + t.Fatalf("PutPolicy version = %d, want 2", v1) + } + v2, err := s.PutPolicy(ctx, p) + if err != nil { + t.Fatalf("second PutPolicy: %v", err) + } + if v2 <= v1 { + t.Fatalf("second PutPolicy version = %d, want > %d", v2, v1) + } + + // A malformed policy is refused by the store's own structural check. + bad := access.Policy{ID: "bad", Level: access.LevelOrg, OrgID: "soc"} + if _, err := s.PutPolicy(ctx, bad); !errors.Is(err, access.ErrInvalidPolicy) { + t.Fatalf("PutPolicy(structurally invalid) = %v, want ErrInvalidPolicy", err) + } + + // ListPolicies round-trips the scope tuple. + list, err := s.ListPolicies(ctx) + if err != nil { + t.Fatalf("ListPolicies: %v", err) + } + if len(list) != 1 { + t.Fatalf("ListPolicies = %d policies, want 1", len(list)) + } + if list[0].ID != "test-policy" || list[0].OrgID != "soc" { + t.Fatalf("ListPolicies[0] = %+v, want the stored policy", list[0]) + } + + // DeletePolicy removes it and reports an unknown key as a sentinel. + if err := s.DeletePolicy(ctx, p); err != nil { + t.Fatalf("DeletePolicy: %v", err) + } + if err := s.DeletePolicy(ctx, p); !errors.Is(err, access.ErrPolicyNotFound) { + t.Fatalf("second DeletePolicy = %v, want ErrPolicyNotFound", err) + } +} + +func TestEnsureShippedOrgPolicies(t *testing.T) { + s := newStoreForAccess(t) + ctx := t.Context() + + if err := s.EnsureShippedOrgPolicies(ctx, "soc"); err != nil { + t.Fatalf("EnsureShippedOrgPolicies: %v", err) + } + list, err := s.ListPolicies(ctx) + if err != nil { + t.Fatalf("ListPolicies: %v", err) + } + if len(list) != 4 { + t.Fatalf("seeding produced %d policies, want the 4 shipped roles", len(list)) + } + + // An edited role policy survives a re-seed: an org that already carries + // the shipped IDs is left untouched. + edited := list[0] + edited.Text = `permit(principal, action, resource) when { resource.kind == "edited" };` + if _, err := s.PutPolicy(ctx, edited); err != nil { + t.Fatalf("PutPolicy(edit): %v", err) + } + if err := s.EnsureShippedOrgPolicies(ctx, "soc"); err != nil { + t.Fatalf("re-seed: %v", err) + } + after, err := s.ListPolicies(ctx) + if err != nil { + t.Fatalf("ListPolicies after re-seed: %v", err) + } + for _, p := range after { + if p.ID == edited.ID && p.Text != edited.Text { + t.Fatalf("re-seed overwrote an edited role policy %s", p.ID) + } + } +} + +func TestResetPolicies(t *testing.T) { + s := newStoreForAccess(t) + ctx := t.Context() + + if err := s.ResetOrgPolicies(ctx, "soc"); err != nil { + t.Fatalf("ResetOrgPolicies: %v", err) + } + // An operator's custom org policy on top of the shipped set. + custom := access.Policy{ + ID: "org-lockdown", Level: access.LevelOrg, OrgID: "soc", + Text: `forbid(principal, action, resource) when { resource.kind == "source" };`, + } + if _, err := s.PutPolicy(ctx, custom); err != nil { + t.Fatalf("PutPolicy(custom): %v", err) + } + // A workspace policy must survive an org reset. + ws := access.Policy{ + ID: "ws-rule", Level: access.LevelWorkspace, OrgID: "soc", WorkspaceID: "net", + Text: `permit(principal, action, resource) when { resource.kind == "binding" };`, + } + if _, err := s.PutPolicy(ctx, ws); err != nil { + t.Fatalf("PutPolicy(ws): %v", err) + } + // And an instance policy must survive an org reset but not an instance + // reset. + instance := access.Policy{ + ID: "instance-rule", Level: access.LevelInstance, + Text: `forbid(principal, action, resource) when { resource.kind == "secret" };`, + } + if _, err := s.PutPolicy(ctx, instance); err != nil { + t.Fatalf("PutPolicy(instance): %v", err) + } + + if err := s.ResetOrgPolicies(ctx, "soc"); err != nil { + t.Fatalf("org reset: %v", err) + } + after, err := s.ListPolicies(ctx) + if err != nil { + t.Fatalf("ListPolicies: %v", err) + } + orgPolicies := 0 + for _, p := range after { + switch { + case p.Level == access.LevelOrg && p.OrgID == "soc": + orgPolicies++ + case p.Level == access.LevelOrg: + t.Fatalf("org reset touched policy %s of another org", p.ID) + } + } + if orgPolicies != 4 { + t.Fatalf("org-level policies after reset = %d, want the 4 shipped roles", orgPolicies) + } + + if err := s.ResetInstancePolicies(ctx); err != nil { + t.Fatalf("ResetInstancePolicies: %v", err) + } + after, err = s.ListPolicies(ctx) + if err != nil { + t.Fatalf("ListPolicies after instance reset: %v", err) + } + for _, p := range after { + if p.Level == access.LevelInstance { + t.Fatalf("instance reset left policy %s", p.ID) + } + } + if len(after) == 0 { + t.Fatal("instance reset removed non-instance policies") + } +} + +func TestDenialStore(t *testing.T) { + s := newStoreForAccess(t) + ctx := t.Context() + + denial := access.Denial{ + Principal: identity.IdentityID("11111111-1111-5111-8111-111111111111"), + Org: "soc", Action: access.ActionRead, Kind: access.KindBinding, + ResourceID: "b1", Level: access.LevelOrg, + Policies: []string{access.PolicyOrgRead, access.PolicyOrgEdit}, + } + if err := s.RecordDenial(ctx, denial); err != nil { + t.Fatalf("RecordDenial: %v", err) + } + if err := s.RecordDenial(ctx, denial); err != nil { + t.Fatalf("repeat RecordDenial: %v", err) + } + // A different action is a separate row. + other := denial + other.Action = access.ActionDelete + if err := s.RecordDenial(ctx, other); err != nil { + t.Fatalf("RecordDenial(other action): %v", err) + } + + rows, err := s.ListDenials(ctx, "soc", 10) + if err != nil { + t.Fatalf("ListDenials: %v", err) + } + if len(rows) != 2 { + t.Fatalf("ListDenials = %d rows, want 2", len(rows)) + } + if rows[0].Action != access.ActionDelete { + t.Fatalf("newest denial = %v, want the delete denial", rows[0].Action) + } + for _, r := range rows { + if r.Action == access.ActionRead { + if r.Count != 2 { + t.Fatalf("repeated denial count = %d, want 2 (coalesced within the minute)", r.Count) + } + if len(r.Policies) != 2 { + t.Fatalf("denial policies = %v, want the deciding policies", r.Policies) + } + } + } + // Another org sees none of these. + if rows, err := s.ListDenials(ctx, "other", 10); err != nil || len(rows) != 0 { + t.Fatalf("ListDenials(other org) = %d rows %v, want none", len(rows), err) + } + // An org-less denial is refused at the producer. + if err := s.RecordDenial(ctx, access.Denial{Action: access.ActionRead}); err == nil { + t.Fatal("RecordDenial accepted a denial with no org or principal") + } +} diff --git a/internal/infrastructure/postgres/migrations/0016_access_policies.sql b/internal/infrastructure/postgres/migrations/0016_access_policies.sql new file mode 100644 index 000000000..55be2cd45 --- /dev/null +++ b/internal/infrastructure/postgres/migrations/0016_access_policies.sql @@ -0,0 +1,60 @@ +-- Access policies and denial records: the stored half of the policy chain +-- (docs/prds/orgs-and-access.md, "Storing and changing policies" and +-- "Denials"). The shipped cross-org forbid is engine-enforced and has no row +-- here; the shipped role policies are seeded per org as ordinary rows with +-- the shipped IDs, so a reset overwrites them and an edit sticks until reset. +-- +-- The scope tuple (level, org_id, workspace_id, object_kind, object_id) is +-- the policy's place in the chain; policy_id names the document inside it. +-- The version counter is per level-scope: PutPolicy bumps it and returns it, +-- so the engine's next load can detect a change. + +-- +goose Up + +CREATE TABLE access_policies ( + level text NOT NULL CHECK (level IN ('instance', 'org', 'workspace', 'object')), + org_id text NOT NULL DEFAULT '', + workspace_id text NOT NULL DEFAULT '', + object_kind text NOT NULL DEFAULT '', + object_id text NOT NULL DEFAULT '', + policy_id text NOT NULL, + text text NOT NULL, + updated_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY (level, org_id, workspace_id, object_kind, object_id, policy_id) +); + +CREATE TABLE access_policy_versions ( + level text NOT NULL CHECK (level IN ('instance', 'org', 'workspace', 'object')), + org_id text NOT NULL DEFAULT '', + workspace_id text NOT NULL DEFAULT '', + version bigint NOT NULL DEFAULT 1, + updated_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY (level, org_id, workspace_id) +); + +-- One denial row per (principal, action, resource, level, policies, minute): +-- a retry storm inside one minute is a count bump, not a row flood +-- (docs/prds/orgs-and-access.md, "Audit retention"). +CREATE TABLE access_denials ( + id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, + org_id text NOT NULL, + principal text NOT NULL, + action text NOT NULL, + resource_kind text NOT NULL, + resource_id text NOT NULL, + level text NOT NULL, + policies text[] NOT NULL DEFAULT '{}', + minute_at timestamptz NOT NULL DEFAULT date_trunc('minute', now()), + count bigint NOT NULL DEFAULT 1, + created_at timestamptz NOT NULL DEFAULT now(), + updated_at timestamptz NOT NULL DEFAULT now() +); +CREATE UNIQUE INDEX idx_access_denials_dedup ON access_denials + (org_id, principal, action, resource_kind, resource_id, level, policies, minute_at); + +-- +goose Down + +DROP INDEX idx_access_denials_dedup; +DROP TABLE access_denials; +DROP TABLE access_policy_versions; +DROP TABLE access_policies; \ No newline at end of file diff --git a/internal/infrastructure/postgres/orgs.go b/internal/infrastructure/postgres/orgs.go index 0bfc91240..c0bfc59ea 100644 --- a/internal/infrastructure/postgres/orgs.go +++ b/internal/infrastructure/postgres/orgs.go @@ -17,6 +17,7 @@ import ( "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgtype" + "github.com/samcharles93/archie-core/internal/domain/access" "github.com/samcharles93/archie-core/internal/domain/identity" "github.com/samcharles93/archie-core/internal/domain/org" "github.com/samcharles93/archie-core/internal/infrastructure/postgres/postgresdb" @@ -150,6 +151,43 @@ func (s *Store) AssignAgent(ctx context.Context, value org.AgentAssignment) erro }) } +// EnsureAgentOrgMembership grants every agent identity the shipped developer +// role in the org it serves. It runs at the State Store's boot, after the +// default-org upgrade, so dispatch's chain has a principal to evaluate. +// Idempotent: an existing membership (any role) is left alone. +func (s *Store) EnsureAgentOrgMembership(ctx context.Context) error { + return s.queries().EnsureAgentOrgMembership(ctx) +} + +// PrincipalFor assembles the access principal for one identity: the org it +// serves and its memberships (internal/domain/access). An identity in no org +// is the default org with no role, which the shipped role policies never +// permit. +func (s *Store) PrincipalFor(ctx context.Context, id identity.IdentityID) (access.Principal, error) { + resolved, err := s.OrgForIdentity(ctx, id) + if err != nil { + return access.Principal{}, err + } + rows, err := s.queries().ListMembershipsByIdentity(ctx, string(id)) + if err != nil { + return access.Principal{}, err + } + memberships := make([]org.Membership, 0, len(rows)) + for _, r := range rows { + var ws org.WorkspaceID + if r.WorkspaceID.Valid { + ws = org.WorkspaceID(r.WorkspaceID.String) + } + memberships = append(memberships, org.Membership{ + IdentityID: id, + OrgID: org.OrgID(r.OrgID), + WorkspaceID: ws, + Role: org.Role(r.Role), + }) + } + return access.Principal{IdentityID: id, Org: resolved, Memberships: memberships}, nil +} + // OrgForIdentity returns the org an identity serves: the assigned org for an // agent, the org of one of its memberships for a person, and the default org // for an identity in no org. diff --git a/internal/infrastructure/postgres/postgresdb/access.sql.go b/internal/infrastructure/postgres/postgresdb/access.sql.go new file mode 100644 index 000000000..67be055d2 --- /dev/null +++ b/internal/infrastructure/postgres/postgresdb/access.sql.go @@ -0,0 +1,341 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: access.sql + +package postgresdb + +import ( + "context" +) + +const countShippedOrgPolicies = `-- name: CountShippedOrgPolicies :one +SELECT count(*) FROM access_policies +WHERE level = 'org' AND org_id = $1 AND policy_id = ANY($2::text[]) +` + +type CountShippedOrgPoliciesParams struct { + OrgID string + Column2 []string +} + +// How many of an org's shipped role policies are stored. The seeding runs +// only when the org carries none of them, so a restart never overwrites an +// edited role policy (the shipped IDs are reserved for the shipped text). +func (q *Queries) CountShippedOrgPolicies(ctx context.Context, arg CountShippedOrgPoliciesParams) (int64, error) { + row := q.db.QueryRow(ctx, countShippedOrgPolicies, arg.OrgID, arg.Column2) + var count int64 + err := row.Scan(&count) + return count, err +} + +const deleteAccessPolicy = `-- name: DeleteAccessPolicy :execrows +DELETE FROM access_policies +WHERE level = $1 AND org_id = $2 AND workspace_id = $3 AND object_kind = $4 + AND object_id = $5 AND policy_id = $6 +` + +type DeleteAccessPolicyParams struct { + Level string + OrgID string + WorkspaceID string + ObjectKind string + ObjectID string + PolicyID string +} + +func (q *Queries) DeleteAccessPolicy(ctx context.Context, arg DeleteAccessPolicyParams) (int64, error) { + result, err := q.db.Exec(ctx, deleteAccessPolicy, + arg.Level, + arg.OrgID, + arg.WorkspaceID, + arg.ObjectKind, + arg.ObjectID, + arg.PolicyID, + ) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} + +const deleteAccessPolicyVersion = `-- name: DeleteAccessPolicyVersion :exec +DELETE FROM access_policy_versions v +WHERE v.level = $1 AND v.org_id = $2 AND v.workspace_id = $3 + AND NOT EXISTS (SELECT 1 FROM access_policies p + WHERE p.level = v.level AND p.org_id = v.org_id AND p.workspace_id = v.workspace_id) +` + +type DeleteAccessPolicyVersionParams struct { + Level string + OrgID string + WorkspaceID string +} + +// Tidy a level-scope with no policies left: its version row has no reader. +func (q *Queries) DeleteAccessPolicyVersion(ctx context.Context, arg DeleteAccessPolicyVersionParams) error { + _, err := q.db.Exec(ctx, deleteAccessPolicyVersion, arg.Level, arg.OrgID, arg.WorkspaceID) + return err +} + +const deleteOrgPoliciesNotShipped = `-- name: DeleteOrgPoliciesNotShipped :exec +DELETE FROM access_policies +WHERE level = 'org' AND org_id = $1 AND NOT (policy_id = ANY($2::text[])) +` + +type DeleteOrgPoliciesNotShippedParams struct { + OrgID string + Column2 []string +} + +// The org reset's removal half: every org-level policy except the shipped +// role set. +func (q *Queries) DeleteOrgPoliciesNotShipped(ctx context.Context, arg DeleteOrgPoliciesNotShippedParams) error { + _, err := q.db.Exec(ctx, deleteOrgPoliciesNotShipped, arg.OrgID, arg.Column2) + return err +} + +const getAccessPolicy = `-- name: GetAccessPolicy :one +SELECT text FROM access_policies +WHERE level = $1 AND org_id = $2 AND workspace_id = $3 AND object_kind = $4 + AND object_id = $5 AND policy_id = $6 +` + +type GetAccessPolicyParams struct { + Level string + OrgID string + WorkspaceID string + ObjectKind string + ObjectID string + PolicyID string +} + +func (q *Queries) GetAccessPolicy(ctx context.Context, arg GetAccessPolicyParams) (string, error) { + row := q.db.QueryRow(ctx, getAccessPolicy, + arg.Level, + arg.OrgID, + arg.WorkspaceID, + arg.ObjectKind, + arg.ObjectID, + arg.PolicyID, + ) + var text string + err := row.Scan(&text) + return text, err +} + +const insertAccessPolicyAudit = `-- name: InsertAccessPolicyAudit :exec +INSERT INTO sys_audit (at, table_name, record_key, field, old_value, new_value, record_version, actor, source, request_id) +VALUES (now(), 'access_policies', $1, 'text', $2, $3, $4, $5, $6, $7) +` + +type InsertAccessPolicyAuditParams struct { + RecordKey string + OldValue []byte + NewValue []byte + RecordVersion int64 + Actor string + Source string + RequestID string +} + +// One audit row per policy change: the policy's old and new text +// (docs/prds/orgs-and-access.md, "Storing and changing policies"). +func (q *Queries) InsertAccessPolicyAudit(ctx context.Context, arg InsertAccessPolicyAuditParams) error { + _, err := q.db.Exec(ctx, insertAccessPolicyAudit, + arg.RecordKey, + arg.OldValue, + arg.NewValue, + arg.RecordVersion, + arg.Actor, + arg.Source, + arg.RequestID, + ) + return err +} + +const insertAccessResetAudit = `-- name: InsertAccessResetAudit :exec +INSERT INTO sys_audit (at, table_name, record_key, field, record_version, actor, source, request_id) +VALUES (now(), 'access_policies', $1, 'reset', 1, 'archied access reset', 'archied', '') +` + +// The one audit row a reset is recorded as; the reset's policy changes +// carry their own rows (docs/prds/orgs-and-access.md, "Recovering from a +// locked-out org"). +func (q *Queries) InsertAccessResetAudit(ctx context.Context, recordKey string) error { + _, err := q.db.Exec(ctx, insertAccessResetAudit, recordKey) + return err +} + +const listAccessPolicies = `-- name: ListAccessPolicies :many + +SELECT level, org_id, workspace_id, object_kind, object_id, policy_id, text, updated_at +FROM access_policies ORDER BY level, org_id, workspace_id, object_kind, object_id, policy_id +` + +// Access policies and denial records (internal/domain/access): the durable +// half of the policy-chain contract. Versioning is per level-scope; every +// policy change writes one sys_audit row naming who made it. +func (q *Queries) ListAccessPolicies(ctx context.Context) ([]AccessPolicy, error) { + rows, err := q.db.Query(ctx, listAccessPolicies) + if err != nil { + return nil, err + } + defer rows.Close() + var items []AccessPolicy + for rows.Next() { + var i AccessPolicy + if err := rows.Scan( + &i.Level, + &i.OrgID, + &i.WorkspaceID, + &i.ObjectKind, + &i.ObjectID, + &i.PolicyID, + &i.Text, + &i.UpdatedAt, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const listDenials = `-- name: ListDenials :many +SELECT id, org_id, principal, action, resource_kind, resource_id, level, policies, minute_at, count, created_at, updated_at +FROM access_denials WHERE org_id = $1 ORDER BY id DESC LIMIT $2 +` + +type ListDenialsParams struct { + OrgID string + Limit int32 +} + +func (q *Queries) ListDenials(ctx context.Context, arg ListDenialsParams) ([]AccessDenial, error) { + rows, err := q.db.Query(ctx, listDenials, arg.OrgID, arg.Limit) + if err != nil { + return nil, err + } + defer rows.Close() + var items []AccessDenial + for rows.Next() { + var i AccessDenial + if err := rows.Scan( + &i.ID, + &i.OrgID, + &i.Principal, + &i.Action, + &i.ResourceKind, + &i.ResourceID, + &i.Level, + &i.Policies, + &i.MinuteAt, + &i.Count, + &i.CreatedAt, + &i.UpdatedAt, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const recordDenial = `-- name: RecordDenial :exec +INSERT INTO access_denials (org_id, principal, action, resource_kind, resource_id, level, policies) +VALUES ($1, $2, $3, $4, $5, $6, $7) +ON CONFLICT (org_id, principal, action, resource_kind, resource_id, level, policies, minute_at) +DO UPDATE SET count = access_denials.count + 1, updated_at = now() +` + +type RecordDenialParams struct { + OrgID string + Principal string + Action string + ResourceKind string + ResourceID string + Level string + Policies []string +} + +// One row per (principal, action, resource, level, policies, minute); +// a repeat inside the minute bumps the count (docs/prds/orgs-and-access.md, +// "Audit retention"). +func (q *Queries) RecordDenial(ctx context.Context, arg RecordDenialParams) error { + _, err := q.db.Exec(ctx, recordDenial, + arg.OrgID, + arg.Principal, + arg.Action, + arg.ResourceKind, + arg.ResourceID, + arg.Level, + arg.Policies, + ) + return err +} + +const resetInstancePolicies = `-- name: ResetInstancePolicies :exec +DELETE FROM access_policies WHERE level = 'instance' +` + +func (q *Queries) ResetInstancePolicies(ctx context.Context) error { + _, err := q.db.Exec(ctx, resetInstancePolicies) + return err +} + +const upsertAccessPolicy = `-- name: UpsertAccessPolicy :exec +INSERT INTO access_policies (level, org_id, workspace_id, object_kind, object_id, policy_id, text) +VALUES ($1, $2, $3, $4, $5, $6, $7) +ON CONFLICT (level, org_id, workspace_id, object_kind, object_id, policy_id) +DO UPDATE SET text = excluded.text, updated_at = now() +` + +type UpsertAccessPolicyParams struct { + Level string + OrgID string + WorkspaceID string + ObjectKind string + ObjectID string + PolicyID string + Text string +} + +func (q *Queries) UpsertAccessPolicy(ctx context.Context, arg UpsertAccessPolicyParams) error { + _, err := q.db.Exec(ctx, upsertAccessPolicy, + arg.Level, + arg.OrgID, + arg.WorkspaceID, + arg.ObjectKind, + arg.ObjectID, + arg.PolicyID, + arg.Text, + ) + return err +} + +const upsertAccessPolicyVersion = `-- name: UpsertAccessPolicyVersion :one +INSERT INTO access_policy_versions (level, org_id, workspace_id, version) VALUES ($1, $2, $3, 2) +ON CONFLICT (level, org_id, workspace_id) +DO UPDATE SET version = access_policy_versions.version + 1, updated_at = now() +RETURNING version +` + +type UpsertAccessPolicyVersionParams struct { + Level string + OrgID string + WorkspaceID string +} + +func (q *Queries) UpsertAccessPolicyVersion(ctx context.Context, arg UpsertAccessPolicyVersionParams) (int64, error) { + row := q.db.QueryRow(ctx, upsertAccessPolicyVersion, arg.Level, arg.OrgID, arg.WorkspaceID) + var version int64 + err := row.Scan(&version) + return version, err +} diff --git a/internal/infrastructure/postgres/postgresdb/models.go b/internal/infrastructure/postgres/postgresdb/models.go index 06e7999ec..002a7774d 100644 --- a/internal/infrastructure/postgres/postgresdb/models.go +++ b/internal/infrastructure/postgres/postgresdb/models.go @@ -10,6 +10,40 @@ import ( "github.com/jackc/pgx/v5/pgtype" ) +type AccessDenial struct { + ID int64 + OrgID string + Principal string + Action string + ResourceKind string + ResourceID string + Level string + Policies []string + MinuteAt time.Time + Count int64 + CreatedAt time.Time + UpdatedAt time.Time +} + +type AccessPolicy struct { + Level string + OrgID string + WorkspaceID string + ObjectKind string + ObjectID string + PolicyID string + Text string + UpdatedAt time.Time +} + +type AccessPolicyVersion struct { + Level string + OrgID string + WorkspaceID string + Version int64 + UpdatedAt time.Time +} + type ApplyStatus struct { Process string Kind string diff --git a/internal/infrastructure/postgres/postgresdb/orgs.sql.go b/internal/infrastructure/postgres/postgresdb/orgs.sql.go index e1e1cc4ac..f67643b44 100644 --- a/internal/infrastructure/postgres/postgresdb/orgs.sql.go +++ b/internal/infrastructure/postgres/postgresdb/orgs.sql.go @@ -11,6 +11,22 @@ import ( "github.com/jackc/pgx/v5/pgtype" ) +const ensureAgentOrgMembership = `-- name: EnsureAgentOrgMembership :exec +INSERT INTO memberships (identity_id, org_id, role) +SELECT a.identity_id, a.org_id, 'developer' FROM org_agents a +ON CONFLICT (identity_id, org_id, COALESCE(workspace_id, '')) DO NOTHING +` + +// Every agent identity serves its org with the shipped developer role: an +// agent is granted access the way a user is +// (docs/prds/orgs-and-access.md, "Identity"). Idempotent, so an operator's +// later role change survives a restart, and the shipped seed never +// overwrites it. +func (q *Queries) EnsureAgentOrgMembership(ctx context.Context) error { + _, err := q.db.Exec(ctx, ensureAgentOrgMembership) + return err +} + const ensureMembership = `-- name: EnsureMembership :exec INSERT INTO memberships (identity_id, org_id, workspace_id, role) VALUES ($1, $2, $3, $4) diff --git a/internal/infrastructure/postgres/queries/access.sql b/internal/infrastructure/postgres/queries/access.sql new file mode 100644 index 000000000..6788796fd --- /dev/null +++ b/internal/infrastructure/postgres/queries/access.sql @@ -0,0 +1,77 @@ +-- Access policies and denial records (internal/domain/access): the durable +-- half of the policy-chain contract. Versioning is per level-scope; every +-- policy change writes one sys_audit row naming who made it. + +-- name: ListAccessPolicies :many +SELECT level, org_id, workspace_id, object_kind, object_id, policy_id, text, updated_at +FROM access_policies ORDER BY level, org_id, workspace_id, object_kind, object_id, policy_id; + +-- name: UpsertAccessPolicy :exec +INSERT INTO access_policies (level, org_id, workspace_id, object_kind, object_id, policy_id, text) +VALUES ($1, $2, $3, $4, $5, $6, $7) +ON CONFLICT (level, org_id, workspace_id, object_kind, object_id, policy_id) +DO UPDATE SET text = excluded.text, updated_at = now(); + +-- name: GetAccessPolicy :one +SELECT text FROM access_policies +WHERE level = $1 AND org_id = $2 AND workspace_id = $3 AND object_kind = $4 + AND object_id = $5 AND policy_id = $6; + +-- name: DeleteAccessPolicy :execrows +DELETE FROM access_policies +WHERE level = $1 AND org_id = $2 AND workspace_id = $3 AND object_kind = $4 + AND object_id = $5 AND policy_id = $6; + +-- name: CountShippedOrgPolicies :one +-- How many of an org's shipped role policies are stored. The seeding runs +-- only when the org carries none of them, so a restart never overwrites an +-- edited role policy (the shipped IDs are reserved for the shipped text). +SELECT count(*) FROM access_policies +WHERE level = 'org' AND org_id = $1 AND policy_id = ANY($2::text[]); + +-- name: DeleteOrgPoliciesNotShipped :exec +-- The org reset's removal half: every org-level policy except the shipped +-- role set. +DELETE FROM access_policies +WHERE level = 'org' AND org_id = $1 AND NOT (policy_id = ANY($2::text[])); + +-- name: ResetInstancePolicies :exec +DELETE FROM access_policies WHERE level = 'instance'; + +-- name: UpsertAccessPolicyVersion :one +INSERT INTO access_policy_versions (level, org_id, workspace_id, version) VALUES ($1, $2, $3, 2) +ON CONFLICT (level, org_id, workspace_id) +DO UPDATE SET version = access_policy_versions.version + 1, updated_at = now() +RETURNING version; + +-- name: DeleteAccessPolicyVersion :exec +-- Tidy a level-scope with no policies left: its version row has no reader. +DELETE FROM access_policy_versions v +WHERE v.level = $1 AND v.org_id = $2 AND v.workspace_id = $3 + AND NOT EXISTS (SELECT 1 FROM access_policies p + WHERE p.level = v.level AND p.org_id = v.org_id AND p.workspace_id = v.workspace_id); + +-- name: InsertAccessPolicyAudit :exec +-- One audit row per policy change: the policy's old and new text +-- (docs/prds/orgs-and-access.md, "Storing and changing policies"). +INSERT INTO sys_audit (at, table_name, record_key, field, old_value, new_value, record_version, actor, source, request_id) +VALUES (now(), 'access_policies', $1, 'text', $2, $3, $4, $5, $6, $7); + +-- name: RecordDenial :exec +-- One row per (principal, action, resource, level, policies, minute); +-- a repeat inside the minute bumps the count (docs/prds/orgs-and-access.md, +-- "Audit retention"). +INSERT INTO access_denials (org_id, principal, action, resource_kind, resource_id, level, policies) +VALUES ($1, $2, $3, $4, $5, $6, $7) +ON CONFLICT (org_id, principal, action, resource_kind, resource_id, level, policies, minute_at) +DO UPDATE SET count = access_denials.count + 1, updated_at = now(); + +-- name: ListDenials :many +SELECT id, org_id, principal, action, resource_kind, resource_id, level, policies, minute_at, count, created_at, updated_at +FROM access_denials WHERE org_id = $1 ORDER BY id DESC LIMIT $2; +-- name: InsertAccessResetAudit :exec +-- The one audit row a reset is recorded as; the reset's policy changes +-- carry their own rows (docs/prds/orgs-and-access.md, "Recovering from a +-- locked-out org"). +INSERT INTO sys_audit (at, table_name, record_key, field, record_version, actor, source, request_id) +VALUES (now(), 'access_policies', $1, 'reset', 1, 'archied access reset', 'archied', ''); diff --git a/internal/infrastructure/postgres/queries/orgs.sql b/internal/infrastructure/postgres/queries/orgs.sql index 6665de881..42bc601d8 100644 --- a/internal/infrastructure/postgres/queries/orgs.sql +++ b/internal/infrastructure/postgres/queries/orgs.sql @@ -40,4 +40,13 @@ SELECT COALESCE( (SELECT m.org_id FROM memberships m WHERE m.identity_id = $1 ORDER BY m.created_at, m.org_id, m.workspace_id NULLS LAST LIMIT 1), 'default' -)::text AS org_id; \ No newline at end of file +)::text AS org_id; +-- name: EnsureAgentOrgMembership :exec +-- Every agent identity serves its org with the shipped developer role: an +-- agent is granted access the way a user is +-- (docs/prds/orgs-and-access.md, "Identity"). Idempotent, so an operator's +-- later role change survives a restart, and the shipped seed never +-- overwrites it. +INSERT INTO memberships (identity_id, org_id, role) +SELECT a.identity_id, a.org_id, 'developer' FROM org_agents a +ON CONFLICT (identity_id, org_id, COALESCE(workspace_id, '')) DO NOTHING; diff --git a/internal/infrastructure/readiness/probes.go b/internal/infrastructure/readiness/probes.go index a8c94d152..1b281889b 100644 --- a/internal/infrastructure/readiness/probes.go +++ b/internal/infrastructure/readiness/probes.go @@ -21,6 +21,7 @@ import ( "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/domain/health" + "github.com/samcharles93/archie-core/internal/infrastructure/access" ) // --- state_db --- @@ -93,6 +94,51 @@ func (p *ContractProbe) Check(ctx context.Context) health.Result { return health.Result{Status: health.StatusOK} } +// --- access policies --- + +// PolicyProblems reports the stored access policies this process's engine +// could not validate. The policy chain is the source; a policy that failed +// startup re-validation denies its level and must be named here with its +// error (docs/prds/orgs-and-access.md, "Storing and changing policies"). +type PolicyProblems interface { + Problems() []access.Problem +} + +// ProblemProbe reports the stored policies the engine could not validate. +// It is a static probe: the engine is immutable for the life of the process, +// so the problems it names do not change under it. +type ProblemProbe struct { + ProbeName string + Source PolicyProblems +} + +// NewProblemProbe returns an access_policies probe over a problem source. +// A nil source degrades the probe rather than lying about the chain. +func NewProblemProbe(name string, problems []access.Problem) *ProblemProbe { + return &ProblemProbe{ProbeName: name, Source: staticProblemSource(problems)} +} + +type staticProblemSource []access.Problem + +func (s staticProblemSource) Problems() []access.Problem { return s } + +func (p *ProblemProbe) Name() string { return p.ProbeName } + +func (p *ProblemProbe) Check(ctx context.Context) health.Result { + if p.Source == nil { + return health.Result{Status: health.StatusDegraded, Detail: "access engine not wired"} + } + problems := p.Source.Problems() + if len(problems) == 0 { + return health.Result{Status: health.StatusOK} + } + details := make([]string, 0, len(problems)) + for _, problem := range problems { + details = append(details, problem.Policy.ID+": "+problem.Err.Error()) + } + return health.Result{Status: health.StatusDegraded, Detail: strings.Join(details, "; ")} +} + // --- config --- // ConfigProbe validates the running configuration. It is the same check the diff --git a/internal/infrastructure/staterpc/access.go b/internal/infrastructure/staterpc/access.go new file mode 100644 index 000000000..d8c3edec8 --- /dev/null +++ b/internal/infrastructure/staterpc/access.go @@ -0,0 +1,177 @@ +// Access: the policy-chain and denial-record RPCs (docs/prds/orgs-and-access.md). +// The policies surface is the engine's snapshot plus the administrative +// writes; the denials surface is the two callers' write path and the +// operator's read. +package staterpc + +import ( + "context" + "errors" + + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + pb "github.com/samcharles93/archie-core/internal/contracts/state/v1" + "github.com/samcharles93/archie-core/internal/domain/access" + "github.com/samcharles93/archie-core/internal/domain/identity" + "github.com/samcharles93/archie-core/internal/domain/org" +) + +var ( + errPoliciesUnavailable = status.Error(codes.Unavailable, "access policy store unavailable") + errDenialsUnavailable = status.Error(codes.Unavailable, "access denial store unavailable") +) + +func accessPolicyProto(p access.Policy) *pb.AccessPolicy { + return &pb.AccessPolicy{ + PolicyId: p.ID, Level: string(p.Level), OrgId: string(p.OrgID), + WorkspaceId: string(p.WorkspaceID), ObjectKind: string(p.ObjectKind), + ObjectId: p.ObjectID, Text: p.Text, + } +} + +func accessPolicyValue(p *pb.AccessPolicy) access.Policy { + return access.Policy{ + ID: p.GetPolicyId(), Level: access.Level(p.GetLevel()), + OrgID: org.OrgID(p.GetOrgId()), WorkspaceID: org.WorkspaceID(p.GetWorkspaceId()), + ObjectKind: access.ResourceKind(p.GetObjectKind()), ObjectID: p.GetObjectId(), + Text: p.GetText(), + } +} + +func accessDenialProto(d access.Denial) *pb.AccessDenial { + out := &pb.AccessDenial{ + OrgId: string(d.Org), Principal: string(d.Principal), Action: string(d.Action), + ResourceKind: string(d.Kind), ResourceId: d.ResourceID, Level: string(d.Level), + Policies: d.Policies, Count: d.Count, + } + if !d.At.IsZero() { + out.At = timestamp(d.At) + } + return out +} + +func accessDenialValue(d *pb.AccessDenial) access.Denial { + value := access.Denial{ + Org: org.OrgID(d.GetOrgId()), + Principal: identity.IdentityID(d.GetPrincipal()), + Action: access.Action(d.GetAction()), + Kind: access.ResourceKind(d.GetResourceKind()), + ResourceID: d.GetResourceId(), + Level: access.Level(d.GetLevel()), + Policies: d.GetPolicies(), + Count: d.GetCount(), + } + if d.GetAt() != nil { + value.At = d.GetAt().AsTime() + } + return value +} + +func (s *server) GetPrincipal(ctx context.Context, request *pb.GetPrincipalRequest) (*pb.GetPrincipalResponse, error) { + if s.deps.Principals == nil { + return nil, status.Error(codes.Unavailable, "identity store unavailable") + } + value, err := s.deps.Principals.PrincipalFor(ctx, identity.IdentityID(request.IdentityId)) + if err != nil { + return nil, identityStatus(err) + } + memberships := make([]*pb.PrincipalMembership, len(value.Memberships)) + for i := range value.Memberships { + m := value.Memberships[i] + memberships[i] = &pb.PrincipalMembership{ + OrgId: string(m.OrgID), WorkspaceId: string(m.WorkspaceID), Role: string(m.Role), + } + } + return &pb.GetPrincipalResponse{Principal: &pb.AccessPrincipal{ + IdentityId: string(value.IdentityID), + OrgId: string(value.Org), + Memberships: memberships, + }}, nil +} + +func (s *server) ListPolicies(ctx context.Context, _ *pb.ListPoliciesRequest) (*pb.ListPoliciesResponse, error) { + if s.deps.Policies == nil { + return nil, errPoliciesUnavailable + } + values, err := s.deps.Policies.ListPolicies(ctx) + if err != nil { + return nil, accessStatus(err) + } + out := make([]*pb.AccessPolicy, len(values)) + for i := range values { + out[i] = accessPolicyProto(values[i]) + } + return &pb.ListPoliciesResponse{Policies: out}, nil +} + +func (s *server) PutPolicy(ctx context.Context, request *pb.PutPolicyRequest) (*pb.PutPolicyResponse, error) { + if s.deps.Policies == nil { + return nil, errPoliciesUnavailable + } + version, err := s.deps.Policies.PutPolicy(ctx, accessPolicyValue(request.Policy)) + if err != nil { + return nil, accessStatus(err) + } + return &pb.PutPolicyResponse{Version: version}, nil +} + +func (s *server) DeletePolicy(ctx context.Context, request *pb.DeletePolicyRequest) (*pb.DeletePolicyResponse, error) { + if s.deps.Policies == nil { + return nil, errPoliciesUnavailable + } + if err := s.deps.Policies.DeletePolicy(ctx, accessPolicyValue(request.Policy)); err != nil { + return nil, accessStatus(err) + } + return &pb.DeletePolicyResponse{}, nil +} + +func (s *server) EnsureShippedOrgPolicies(ctx context.Context, request *pb.EnsureShippedOrgPoliciesRequest) (*pb.EnsureShippedOrgPoliciesResponse, error) { + if s.deps.Policies == nil { + return nil, errPoliciesUnavailable + } + if err := s.deps.Policies.EnsureShippedOrgPolicies(ctx, org.OrgID(request.OrgId)); err != nil { + return nil, accessStatus(err) + } + return &pb.EnsureShippedOrgPoliciesResponse{}, nil +} + +func (s *server) RecordDenial(ctx context.Context, request *pb.RecordDenialRequest) (*pb.RecordDenialResponse, error) { + if s.deps.Denials == nil { + return nil, errDenialsUnavailable + } + if err := s.deps.Denials.RecordDenial(ctx, accessDenialValue(request.Denial)); err != nil { + return nil, accessStatus(err) + } + return &pb.RecordDenialResponse{}, nil +} + +func (s *server) ListDenials(ctx context.Context, request *pb.ListDenialsRequest) (*pb.ListDenialsResponse, error) { + if s.deps.Denials == nil { + return nil, errDenialsUnavailable + } + limit := int(request.GetLimit()) + if limit <= 0 || limit > 1000 { + limit = 100 + } + values, err := s.deps.Denials.ListDenials(ctx, org.OrgID(request.OrgId), limit) + if err != nil { + return nil, accessStatus(err) + } + out := make([]*pb.AccessDenial, len(values)) + for i := range values { + out[i] = accessDenialProto(values[i]) + } + return &pb.ListDenialsResponse{Denials: out}, nil +} + +// accessStatus maps an access sentinel to its gRPC status. +func accessStatus(err error) error { + if errors.Is(err, access.ErrPolicyNotFound) { + return status.Error(codes.NotFound, access.ErrPolicyNotFound.Error()) + } + if errors.Is(err, access.ErrInvalidPolicy) { + return status.Error(codes.InvalidArgument, access.ErrInvalidPolicy.Error()) + } + return mapError(err) +} diff --git a/internal/infrastructure/staterpc/access_client.go b/internal/infrastructure/staterpc/access_client.go new file mode 100644 index 000000000..a6fa18d43 --- /dev/null +++ b/internal/infrastructure/staterpc/access_client.go @@ -0,0 +1,90 @@ +// Access: the client half of the policy-chain and denial-record RPCs +// (docs/prds/orgs-and-access.md). The reset surface is deliberately absent: +// `archied access reset` runs on the State Store host, never over the wire. +package staterpc + +import ( + "context" + + pb "github.com/samcharles93/archie-core/internal/contracts/state/v1" + "github.com/samcharles93/archie-core/internal/domain/access" + "github.com/samcharles93/archie-core/internal/domain/identity" + "github.com/samcharles93/archie-core/internal/domain/org" +) + +// The Client satisfies the access contracts the two callers depend on. +var ( + _ access.PolicyStore = (*Client)(nil) + _ access.DenialStore = (*Client)(nil) + _ access.PrincipalSource = (*Client)(nil) +) + +func (c *Client) PrincipalFor(ctx context.Context, id identity.IdentityID) (access.Principal, error) { + r, err := c.client.GetPrincipal(ctx, &pb.GetPrincipalRequest{IdentityId: string(id)}) + if err != nil { + return access.Principal{}, unmapError(err) + } + value := r.GetPrincipal() + memberships := make([]org.Membership, len(value.GetMemberships())) + for i := range value.GetMemberships() { + m := value.GetMemberships()[i] + memberships[i] = org.Membership{ + IdentityID: id, + OrgID: org.OrgID(m.GetOrgId()), + WorkspaceID: org.WorkspaceID(m.GetWorkspaceId()), + Role: org.Role(m.GetRole()), + } + } + return access.Principal{ + IdentityID: identity.IdentityID(value.GetIdentityId()), + Org: org.OrgID(value.GetOrgId()), + Memberships: memberships, + }, nil +} + +func (c *Client) ListPolicies(ctx context.Context) ([]access.Policy, error) { + r, err := c.client.ListPolicies(ctx, &pb.ListPoliciesRequest{}) + if err != nil { + return nil, unmapError(err) + } + out := make([]access.Policy, len(r.Policies)) + for i := range r.Policies { + out[i] = accessPolicyValue(r.Policies[i]) + } + return out, nil +} + +func (c *Client) PutPolicy(ctx context.Context, p access.Policy) (int64, error) { + r, err := c.client.PutPolicy(ctx, &pb.PutPolicyRequest{Policy: accessPolicyProto(p)}) + if err != nil { + return 0, unmapError(err) + } + return r.Version, nil +} + +func (c *Client) DeletePolicy(ctx context.Context, p access.Policy) error { + _, err := c.client.DeletePolicy(ctx, &pb.DeletePolicyRequest{Policy: accessPolicyProto(p)}) + return unmapError(err) +} + +func (c *Client) EnsureShippedOrgPolicies(ctx context.Context, orgID org.OrgID) error { + _, err := c.client.EnsureShippedOrgPolicies(ctx, &pb.EnsureShippedOrgPoliciesRequest{OrgId: string(orgID)}) + return unmapError(err) +} + +func (c *Client) RecordDenial(ctx context.Context, d access.Denial) error { + _, err := c.client.RecordDenial(ctx, &pb.RecordDenialRequest{Denial: accessDenialProto(d)}) + return unmapError(err) +} + +func (c *Client) ListDenials(ctx context.Context, orgID org.OrgID, limit int) ([]access.Denial, error) { + r, err := c.client.ListDenials(ctx, &pb.ListDenialsRequest{OrgId: string(orgID), Limit: int32(limit)}) + if err != nil { + return nil, unmapError(err) + } + out := make([]access.Denial, len(r.Denials)) + for i := range r.Denials { + out[i] = accessDenialValue(r.Denials[i]) + } + return out, nil +} diff --git a/internal/infrastructure/staterpc/server.go b/internal/infrastructure/staterpc/server.go index cb3a76bb6..5b71e72be 100644 --- a/internal/infrastructure/staterpc/server.go +++ b/internal/infrastructure/staterpc/server.go @@ -17,6 +17,7 @@ import ( controlpb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1" pb "github.com/samcharles93/archie-core/internal/contracts/state/v1" + "github.com/samcharles93/archie-core/internal/domain/access" "github.com/samcharles93/archie-core/internal/domain/binding" "github.com/samcharles93/archie-core/internal/domain/identity" "github.com/samcharles93/archie-core/internal/domain/mapping" @@ -99,6 +100,18 @@ type Deps struct { // (docs/prds/eda-playbook-engine.md gap 2). Optional: nil disables the // two playbook dispatch RPCs with codes.Unavailable. PlaybookDispatcher storecontract.PlaybookDispatcher + // Principals assembles the access principal for one identity: the org it + // serves and its memberships. Optional: nil answers GetPrincipal with + // codes.Unavailable. + Principals access.PrincipalSource + // Policies is the stored policy chain (docs/prds/orgs-and-access.md). + // Optional: nil answers the access RPCs with codes.Unavailable. The reset + // surface is deliberately not an RPC: `archied access reset` runs on the + // State Store host, never over the network. + Policies access.PolicyStore + // Denials records and lists denial records. Optional: nil disables the + // pair with codes.Unavailable. + Denials access.DenialStore // TaskLogs reads one task attempt's persisted log out of the state // directory this process owns. Optional, and nil is the honest default for // a store service that shares no state directory with the daemon: diff --git a/internal/webui/authorize.go b/internal/webui/authorize.go new file mode 100644 index 000000000..d3fabe915 --- /dev/null +++ b/internal/webui/authorize.go @@ -0,0 +1,241 @@ +// The access chain at the dashboard and API request path: the second of the +// two places that call the Authorizer (docs/prds/orgs-and-access.md, "Where +// it lives"). A request that carries an identity is assembled into a +// principal; the action and resource kind are derived from the route; the +// chain decides; a denial is recorded with the level that decided it and +// reported as forbidden without the reason. +// +// The shared token is the single-operator install's owner of the default org +// (docs/prds/orgs-and-access.md, "Credentials"): the token principal is +// assembled here, not looked up, until principal credentials exist. +package webui + +import ( + "context" + "log/slog" + "net/http" + "strings" + + "github.com/samcharles93/archie-core/internal/domain/access" + "github.com/samcharles93/archie-core/internal/domain/identity" + "github.com/samcharles93/archie-core/internal/domain/org" +) + +// TokenOwnerPrincipal is the principal the shared token acts as: the owner +// of the default org, per the single-operator credential rule. +func TokenOwnerPrincipal() access.Principal { + return access.Principal{ + IdentityID: identity.SystemID, + Kind: identity.KindSystem, + Org: org.DefaultOrgID, + Memberships: []org.Membership{ + {IdentityID: identity.SystemID, OrgID: org.DefaultOrgID, Role: org.RoleOwner}, + }, + } +} + +// principalContextKey carries the assembled principal of a request. +type principalContextKey struct{} + +// WithRequestPrincipal attaches the principal a request was authorized for. +func WithPrincipal(ctx context.Context, p access.Principal) context.Context { + return context.WithValue(ctx, principalContextKey{}, p) +} + +// RequestPrincipal returns the principal a request was authorized as. +func RequestPrincipal(ctx context.Context) (access.Principal, bool) { + value, ok := ctx.Value(principalContextKey{}).(access.Principal) + return value, ok +} + +// authorize wraps h with the policy chain. Optional: a server with no +// Authorizer keeps the credential check as the whole gate, which is the +// documented behaviour of an install that has not built the chain. +func (s *Server) authorize(h http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if s.Access == nil { + h.ServeHTTP(w, r) + return + } + principal, err := s.requestPrincipal(r.Context()) + if err != nil { + if wantsDocument(r) { + s.authPage(w, "Sign-in could not resolve your org.") + return + } + http.Error(w, "principal unavailable", http.StatusServiceUnavailable) + return + } + action, kind, id := accessRequest(r) + // The record's org is not loaded here: org-filtered lookups keep a + // record of another org from ever being fetched, and this request's + // record (when it has an ID) belongs to the caller's org. The + // workspace is likewise the record's, not the route's. + resource := access.Resource{Kind: kind, ID: id, Org: principal.Org} + decision := s.Access.Authorize(principal, action, resource, access.Context{}) + if !decision.Allowed { + s.recordDenial(r.Context(), principal, action, resource, decision) + if wantsDocument(r) { + s.authPage(w, "You do not have permission to do that.") + return + } + // A denial inside the caller's org is forbidden, without the + // reason (docs/prds/orgs-and-access.md, "Denials"). + http.Error(w, "forbidden", http.StatusForbidden) + return + } + h.ServeHTTP(w, r.WithContext(WithPrincipal(r.Context(), principal))) + }) +} + +// requestPrincipal assembles the principal a request acts as. With no acting +// identity (the shared token), it is the token owner; with one, it is the +// identity's org and memberships, read over the wire. +func (s *Server) requestPrincipal(ctx context.Context) (access.Principal, error) { + if acting, ok := ActingIdentity(ctx); ok { + if s.Principals == nil { + return access.Principal{}, errPrincipalsUnavailable + } + return s.Principals.PrincipalFor(ctx, acting.ID) + } + return TokenOwnerPrincipal(), nil +} + +func (s *Server) recordDenial(ctx context.Context, p access.Principal, action access.Action, r access.Resource, decision access.Decision) { + if s.Denials == nil { + return + } + denial := access.Denial{ + Principal: p.IdentityID, Org: p.Org, Action: action, + Kind: r.Kind, ResourceID: r.ID, Level: decision.Level, + Policies: decision.Policies, + } + if err := s.Denials.RecordDenial(ctx, denial); err != nil && s.Log != nil { + s.Log.Error("record access denial", "err", err) + } +} + +// errPrincipalsUnavailable is the answer of a dashboard wired with the chain +// but without the principal assembly, which is a composition error: the two +// are wired together or not at all. +var errPrincipalsUnavailable = ¬WiredError{} + +type notWiredError struct{} + +func (*notWiredError) Error() string { return "webui: principal assembly not wired" } + +// accessRequest derives the action, resource kind and record key of one API +// 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 := 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) +} + +// 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), true + case matchSegment(path, "/api/tasks/", "/logs"): + return access.ActionReadLogs, access.KindTask, segmentValue(path, 2), true + case matchPrefix(path, "/api/identities"): + return actionManage(action), access.KindIdentity, segmentValue(path, 2), true + case matchPrefix(path, "/api/control-plane/resources"): + return actionManage(action), access.KindPolicy, segmentValue(path, 3), true + case matchPrefix(path, "/api/chat"): + if action == access.ActionCreate { + return access.ActionRun, access.KindWorkflow, "", true + } + return access.ActionRead, access.KindDashboard, "", true + case matchSegment(path, "/api/sources/", "/secret"): + return access.ActionUpdate, access.KindSecret, segmentValue(path, 2), true + case matchPrefix(path, "/api/channels/"): + return actionManage(action), access.KindDashboard, segmentValue(path, 2), true + case matchPrefix(path, "/api/config"), matchPrefix(path, "/api/logs"): + 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 access.KindTask + case matchPrefix(path, "/api/event-types"): + return access.KindEventType + case matchPrefix(path, "/api/mappings"): + return access.KindMapping + case matchPrefix(path, "/api/bindings"): + return access.KindBinding + case matchPrefix(path, "/api/sources"): + return access.KindSource + case matchPrefix(path, "/api/work-requests"): + return access.KindTask + } + return access.KindDashboard +} + +// actionManage lifts a create or update on a managed surface to the manage +// action the role vocabulary carries. +func actionManage(action access.Action) access.Action { + switch action { + case access.ActionCreate, access.ActionUpdate: + return access.ActionManageIdentities + case access.ActionDelete: + return access.ActionDelete + } + return action +} + +// segmentValue returns the value of the n-th (0-based) segment of an API +// path, or "" when the path is shorter: /api/tasks/7/changes -> 7 is segment +// 2. +func segmentValue(path string, n int) string { + segments := splitPath(path) + if n < len(segments) { + return segments[n] + } + return "" +} + +func splitPath(path string) []string { + var out []string + for segment := range strings.SplitSeq(path, "/") { + if segment != "" { + out = append(out, segment) + } + } + return out +} + +func matchPrefix(path, prefix string) bool { + return strings.HasPrefix(path, prefix+"/") || path == prefix +} + +func matchSegment(path, prefix, suffix string) bool { + return strings.HasPrefix(path, prefix) && strings.HasSuffix(path, suffix) +} + +// The log the authorize wrapper reports assembly failures with. +var _ = slog.Default //nolint:unused // logging stays on s.Log diff --git a/internal/webui/authorize_test.go b/internal/webui/authorize_test.go new file mode 100644 index 000000000..a3f9e96c2 --- /dev/null +++ b/internal/webui/authorize_test.go @@ -0,0 +1,125 @@ +package webui + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "testing" + + "github.com/samcharles93/archie-core/internal/domain/access" + "github.com/samcharles93/archie-core/internal/domain/identity" + "github.com/samcharles93/archie-core/internal/domain/org" +) + +// fakeAuthorizer records the request it evaluated and answers with a fixed +// decision. It is the chain stand-in the webui tests run against. +type fakeAuthorizer struct { + decision access.Decision + last access.Resource + lastAct access.Action +} + +func (f *fakeAuthorizer) Authorize(_ access.Principal, a access.Action, r access.Resource, _ access.Context) access.Decision { + f.lastAct, f.last = a, r + return f.decision +} + +type recordingDenials struct{ recorded []access.Denial } + +func (r *recordingDenials) RecordDenial(_ context.Context, d access.Denial) error { + r.recorded = append(r.recorded, d) + return nil +} + +func (r *recordingDenials) ListDenials(_ context.Context, _ org.OrgID, _ int) ([]access.Denial, error) { + return nil, errors.New("not needed") +} + +func handlerEcho(w http.ResponseWriter, r *http.Request) { + principal, ok := RequestPrincipal(r.Context()) + if ok { + w.Header().Set("X-Principal-Org", string(principal.Org)) + } + w.WriteHeader(http.StatusOK) +} + +func newAccessServer(t *testing.T, engine access.Authorizer, denials access.DenialStore) *Server { + t.Helper() + return &Server{Access: engine, Principals: nil, Denials: denials, Token: ""} +} + +func TestAuthorizeNilEngineServesEverything(t *testing.T) { + s := &Server{} + h := s.authorize(http.HandlerFunc(handlerEcho)) + rec := httptest.NewRecorder() + 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) + } +} + +func TestAuthorizeTokenOwnerAllowed(t *testing.T) { + engine := &fakeAuthorizer{decision: access.Allowed()} + s := newAccessServer(t, engine, nil) + h := s.authorize(http.HandlerFunc(handlerEcho)) + rec := httptest.NewRecorder() + 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) + } + // The token owner is the owner of the default org, and the route + // derived a read on the binding surface. + if rec.Header().Get("X-Principal-Org") != string(org.DefaultOrgID) { + t.Fatalf("principal org = %q, want the default org", rec.Header().Get("X-Principal-Org")) + } + if engine.lastAct != access.ActionRead || engine.last.Kind != access.KindBinding { + t.Fatalf("derived action %q kind %q, want read on bindings", engine.lastAct, engine.last.Kind) + } +} + +func TestAuthorizeDenialIsForbiddenWithoutReason(t *testing.T) { + engine := &fakeAuthorizer{decision: access.DeniedAt(access.LevelOrg, []string{access.PolicyOrgRead})} + denials := &recordingDenials{} + s := newAccessServer(t, engine, denials) + h := s.authorize(http.HandlerFunc(handlerEcho)) + rec := httptest.NewRecorder() + 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) + } + if rec.Body != nil && rec.Body.String() != "forbidden\n" { + t.Fatalf("denial body = %q, want no reason", rec.Body.String()) + } + if engine.lastAct != access.ActionDelete { + t.Fatalf("derived action = %q, want delete", engine.lastAct) + } + if len(denials.recorded) != 1 { + t.Fatalf("recorded %d denials, want 1", len(denials.recorded)) + } + recorded := denials.recorded[0] + if recorded.Principal != identity.SystemID || recorded.Action != access.ActionDelete || + recorded.Level != access.LevelOrg || len(recorded.Policies) != 1 { + t.Fatalf("denial record = %+v, want principal, action, level and policies", recorded) + } +} + +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.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) + } +} + +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.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) + } +} diff --git a/internal/webui/server.go b/internal/webui/server.go index 79430ee1f..7e3e4a80c 100644 --- a/internal/webui/server.go +++ b/internal/webui/server.go @@ -11,6 +11,7 @@ import ( "time" controlpb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1" + "github.com/samcharles93/archie-core/internal/domain/access" "github.com/samcharles93/archie-core/internal/domain/health" "github.com/samcharles93/archie-core/internal/domain/identity" "github.com/samcharles93/archie-core/internal/domain/messaging" @@ -108,6 +109,16 @@ type Server struct { // through a browser -- an agent does exactly that. Login identity.LoginFlow + // Access evaluates the policy chain for each request + // (docs/prds/orgs-and-access.md). Optional: nil keeps the credential + // check as the whole gate -- the documented behaviour of an install that + // has not built the chain. Principals assembles the request principal + // from the acting identity; Denials records refusals. All three are + // wired together at composition or not at all. + Access access.Authorizer + Principals access.PrincipalSource + Denials access.DenialStore + // Events publishes operator actions so they reach the task timeline and // the live activity stream. Optional: nil means the action is recorded // in the store but invisible to anyone watching. @@ -329,7 +340,10 @@ func (s *Server) Handler() http.Handler { if s.CaptureIntake != nil { top.Handle(captureIntakeRoute, s.CaptureIntake) } - top.Handle("/", s.requireToken(mux)) + // The chain runs after the credential check and before any handler: the + // principal exists only once the credential resolved + // (docs/prds/orgs-and-access.md, "Where it lives"). + top.Handle("/", s.requireToken(s.authorize(mux))) return top } diff --git a/proto/state/v1/state.proto b/proto/state/v1/state.proto index 48fb14798..2db3d049d 100644 --- a/proto/state/v1/state.proto +++ b/proto/state/v1/state.proto @@ -165,6 +165,20 @@ service StateStoreService { // relation server-side, so the grant only names the caller. rpc EnqueueCallTask(EnqueueCallTaskRequest) returns (EnqueueCallTaskResponse); rpc WorkflowCallStatus(WorkflowCallStatusRequest) returns (WorkflowCallStatusResponse); + + // Access: the stored policy chain and its denial records + // (docs/prds/orgs-and-access.md). ListPolicies is the engine's snapshot; + // the writes are administrative. RecordDenial is the dashboard's and + // dispatch's write path; ListDenials is the operator surface. + // The principal assembly the Authorizer evaluates: an identity, the org + // it serves, and its memberships (internal/domain/access). + rpc GetPrincipal(GetPrincipalRequest) returns (GetPrincipalResponse); + rpc ListPolicies(ListPoliciesRequest) returns (ListPoliciesResponse); + rpc PutPolicy(PutPolicyRequest) returns (PutPolicyResponse); + rpc DeletePolicy(DeletePolicyRequest) returns (DeletePolicyResponse); + rpc EnsureShippedOrgPolicies(EnsureShippedOrgPoliciesRequest) returns (EnsureShippedOrgPoliciesResponse); + rpc RecordDenial(RecordDenialRequest) returns (RecordDenialResponse); + rpc ListDenials(ListDenialsRequest) returns (ListDenialsResponse); } message RegisterTaskGrantRequest { @@ -923,3 +937,56 @@ message RemoveInstalledPackageRequest { string org_id = 1; string name = 2; } message RemoveInstalledPackageResponse {} // Task mirrors internal/domain/workflow.Task. + +message GetPrincipalRequest { string identity_id = 1; } +// PrincipalMembership mirrors org.Membership: an identity's role in an org, +// or in one workspace of it. +message PrincipalMembership { + string org_id = 1; + string workspace_id = 2; + string role = 3; +} +message AccessPrincipal { + string identity_id = 1; + string org_id = 2; + repeated PrincipalMembership memberships = 3; +} +message GetPrincipalResponse { AccessPrincipal principal = 1; } + +// AccessPolicy mirrors internal/domain/access.Policy: one Cedar policy +// document and the level-scope tuple that places it in the chain. +message AccessPolicy { + string policy_id = 1; + string level = 2; + string org_id = 3; + string workspace_id = 4; + string object_kind = 5; + string object_id = 6; + string text = 7; +} +message ListPoliciesRequest {} +message ListPoliciesResponse { repeated AccessPolicy policies = 1; } +message PutPolicyRequest { AccessPolicy policy = 1; } +message PutPolicyResponse { int64 version = 1; } +message DeletePolicyRequest { AccessPolicy policy = 1; } +message DeletePolicyResponse {} +message EnsureShippedOrgPoliciesRequest { string org_id = 1; } +message EnsureShippedOrgPoliciesResponse {} +// AccessDenial mirrors internal/domain/access.Denial: one refusal with the +// level that decided it and the deciding policies. The store coalesces +// identical denials within a minute into one row with a count. +message AccessDenial { + string org_id = 1; + string principal = 2; + string action = 3; + string resource_kind = 4; + string resource_id = 5; + string level = 6; + repeated string policies = 7; + int64 count = 8; + google.protobuf.Timestamp at = 9; +} +message RecordDenialRequest { AccessDenial denial = 1; } +message RecordDenialResponse {} +message ListDenialsRequest { string org_id = 1; int32 limit = 2; } +message ListDenialsResponse { repeated AccessDenial denials = 1; }