Merge crew/qc8p: archie-core-qc8p
This commit is contained in:
commit
0219aee5ad
46 files changed
+5150
-243
No files matched your search
@@ -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.
|
||||
@@ -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())
|
||||
}
|
||||
@@ -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
|
||||
)
|
||||
@@ -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=
|
||||
|
||||
@@ -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 <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)
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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...)
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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
|
||||
}
|
||||
+1218
-197
File diff suppressed because it is too large.
Load diff
@@ -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{
|
||||
{
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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")
|
||||
)
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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"`
|
||||
}
|
||||
@@ -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;
|
||||
};`
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
@@ -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.
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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', '');
|
||||
@@ -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;
|
||||
)::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;
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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:
|
||||
|
||||
@@ -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
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -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; }
|
||||
Reference in new issue
Block a user