feat(access): the chain at the dashboard, API and dispatch, with denial records and health reporting (archie-core-qc8p)

This commit is contained in:
sam committed 2026-09-26 15:23:32 +10:00
1 parent 7c765dad9d
commit c2cb5ddfaf
14 files changed
+613 -10

No files matched your search

+48
View File
@@ -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,13 @@ 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
accessPrincipals access.PrincipalSource
accessDenials access.DenialStore
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 +444,33 @@ func (b *boot) openStateStoreAdapter() error {
return nil
}
// 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 +1423,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()
}
+6
View File
@@ -375,6 +375,12 @@ func Run() int { //nolint:cyclop,funlen // the composition root's setup sequence
if err := b.openDaemonStateSurfaces(); err != nil {
return 1
}
// The policy chain the dispatch loop evaluates, built once from the
// stored policies (docs/prds/orgs-and-access.md). It runs after the
// state surfaces exist and before the daemon is built.
if err := b.openAccessChain(ctx); err != nil {
return 1
}
if err := b.loadRuntimeConfig(ctx); err != nil {
b.log.Error("runtime settings unavailable", "err", err)
return 1
+3
View File
@@ -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...)
}
+12
View File
@@ -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
}
+3 -1
View File
@@ -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
+52 -1
View File
@@ -10,11 +10,38 @@ 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"
)
// errAccessStoreUnavailable reports that no policy store is wired. The
// dashboard degrades to the credential check rather than refusing to serve.
var errAccessStoreUnavailable = errors.New("access policy store unavailable")
// buildAccessChain loads the stored policies over the wire and builds the
// engine. The wire client satisfies the two access contracts the dashboard
// needs alongside the engine.
func buildAccessChain(ctx context.Context, store *staterpc.Client) (access.Authorizer, []infraaccess.Problem, error) {
stored, err := store.ListPolicies(ctx)
if err != nil {
if status.Code(err) == codes.Unavailable {
return nil, nil, errAccessStoreUnavailable
}
return nil, nil, err
}
engine, err := infraaccess.New(stored)
if err != nil {
return nil, nil, 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 +71,27 @@ func Run(ctx context.Context, options Options) error {
}
cleanups = append(cleanups, closeGateway)
// The access chain is built here, from the stored policies over the
// wire: an invalid instance policy stops this process serving until it
// is fixed; an invalid org, workspace or object policy is reported as a
// health issue naming the policy and the error, and its level denies
// everything (docs/prds/orgs-and-access.md, "Storing and changing
// policies").
chain, problems, err := buildAccessChain(ctx, tasks)
if err != nil {
if errors.Is(err, errAccessStoreUnavailable) {
// A State Store serving no policies has no chain to evaluate:
// the dashboard keeps the credential check as the whole gate.
log.Warn("access chain unavailable; the credential check is the gate", "err", err)
} else {
return err
}
}
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 +106,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
+1 -1
View File
@@ -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()
+1 -1
View File
@@ -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
}
+76 -4
View File
@@ -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,14 @@ 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
}
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 +769,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) {
@@ -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
+224
View File
@@ -0,0 +1,224 @@
// 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 = &notWiredError{}
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 := access.ActionRead
switch r.Method {
case http.MethodPost:
action = access.ActionCreate
case http.MethodPut, http.MethodPatch:
action = access.ActionUpdate
case http.MethodDelete:
action = access.ActionDelete
}
path := r.URL.Path
// Route-specific action and kind refinements.
switch {
case action == access.ActionCreate && matchSegment(path, "/api/bindings/", "/approve"):
return access.ActionApprove, access.KindBinding, segmentValue(path, 2)
case matchSegment(path, "/api/tasks/", "/logs"):
return access.ActionReadLogs, access.KindTask, segmentValue(path, 2)
case matchPrefix(path, "/api/identities"):
return actionManage(action), access.KindIdentity, segmentValue(path, 2)
case matchPrefix(path, "/api/control-plane/resources"):
return actionManage(action), access.KindPolicy, segmentValue(path, 3)
case matchPrefix(path, "/api/chat"):
if action == access.ActionCreate {
return access.ActionRun, access.KindWorkflow, ""
}
return access.ActionRead, access.KindDashboard, ""
case matchSegment(path, "/api/sources/", "/secret"):
return access.ActionUpdate, access.KindSecret, segmentValue(path, 2)
case matchPrefix(path, "/api/channels/"):
return actionManage(action), access.KindDashboard, segmentValue(path, 2)
case matchPrefix(path, "/api/config"), matchPrefix(path, "/api/logs"):
return access.ActionRead, access.KindDashboard, ""
}
switch {
case matchPrefix(path, "/api/tasks"):
return action, access.KindTask, segmentValue(path, 2)
case matchPrefix(path, "/api/event-types"):
return action, access.KindEventType, segmentValue(path, 2)
case matchPrefix(path, "/api/mappings"):
return action, access.KindMapping, segmentValue(path, 2)
case matchPrefix(path, "/api/bindings"):
return action, access.KindBinding, segmentValue(path, 2)
case matchPrefix(path, "/api/sources"):
return action, access.KindSource, segmentValue(path, 2)
case matchPrefix(path, "/api/work-requests"):
return action, access.KindTask, ""
}
return action, 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
+125
View File
@@ -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.NewRequest(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.NewRequest(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.NewRequest(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.NewRequest(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.NewRequest(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)
}
}
+15 -1
View File
@@ -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
}