refactor(access): authorization takes the caller's context instead of a stored one (#1925)

This commit is contained in:
sam committed 2026-11-13 03:54:05 +11:00
1 parent 68e8552f0d
commit afaea346ee
25 files changed
+77 -77

No files matched your search

+1 -1
View File
@@ -317,7 +317,7 @@ func (b *boot) openAccessChain(ctx context.Context) error {
if !ok { if !ok {
return fmt.Errorf("state store policy reader unavailable") return fmt.Errorf("state store policy reader unavailable")
} }
live := infraaccess.NewPending(ctx, source.PoliciesVersion, source.ListPolicies, b.log) live := infraaccess.NewPending(source.PoliciesVersion, source.ListPolicies, b.log)
if err := live.Reload(ctx); err != nil { if err := live.Reload(ctx); err != nil {
b.log.WarnContext(ctx, "workflow policies unavailable; execution remains denied", "err", err) b.log.WarnContext(ctx, "workflow policies unavailable; execution remains denied", "err", err)
} }
+1 -1
View File
@@ -37,7 +37,7 @@ func (s *repositoryServer) CheckRepository(ctx context.Context, r *pb.CheckRepos
if b.d == nil || b.d.Access == nil || b.d.Principals == nil { if b.d == nil || b.d.Access == nil || b.d.Principals == nil {
return nil, status.Error(codes.Unavailable, "Repository checks are temporarily unavailable.") return nil, status.Error(codes.Unavailable, "Repository checks are temporarily unavailable.")
} }
decision := b.d.Access.Authorize(caller, access.ActionUpdate, access.Resource{Kind: access.KindPolicy, ID: "repository-policies", Org: caller.Org}, access.Context{}) decision := b.d.Access.Authorize(ctx, caller, access.ActionUpdate, access.Resource{Kind: access.KindPolicy, ID: "repository-policies", Org: caller.Org}, access.Context{})
if !decision.Allowed { if !decision.Allowed {
return nil, status.Error(codes.PermissionDenied, "You do not have permission to check repository access.") return nil, status.Error(codes.PermissionDenied, "You do not have permission to check repository access.")
} }
+1 -1
View File
@@ -48,7 +48,7 @@ func (b *server) startGatewayRuntime(ctx context.Context, actor gateway.ChatTask
if err != nil { if err != nil {
return nil, err return nil, err
} }
if err := b.registerTools(); err != nil { if err := b.registerTools(ctx); err != nil {
return nil, err return nil, err
} }
b.registerStandaloneTools(ctx) b.registerStandaloneTools(ctx)
+2 -2
View File
@@ -53,8 +53,8 @@ func (b *server) reconcileToolSettings(ctx context.Context, cfg config.Config) e
// API key again as part of the rebuild, so a rotated credential // API key again as part of the rebuild, so a rotated credential
// applies too. // applies too.
b.toolReg.Unregister(webfetch.ToolName, minimax.ToolName) b.toolReg.Unregister(webfetch.ToolName, minimax.ToolName)
b.registerWebFetchTool(cfg) b.registerWebFetchTool(ctx, cfg)
b.registerMinimaxTool(cfg, b.log) b.registerMinimaxTool(ctx, cfg, b.log)
} }
return errors.Join(problems...) return errors.Join(problems...)
} }
+21 -21
View File
@@ -30,7 +30,7 @@ import (
"github.com/samcharles93/archie-core/internal/tools/webfetch" "github.com/samcharles93/archie-core/internal/tools/webfetch"
) )
func (b *server) registerTools() error { func (b *server) registerTools(ctx context.Context) error {
cfg, log := b.cfgHolder.Get(), b.log cfg, log := b.cfgHolder.Get(), b.log
b.providerRegistry = toolprovider.NewRegistry(b.toolReg) b.providerRegistry = toolprovider.NewRegistry(b.toolReg)
b.mcpMu.Lock() b.mcpMu.Lock()
@@ -41,27 +41,27 @@ func (b *server) registerTools() error {
// A workspace chosen in the dashboard names a directory nobody has // A workspace chosen in the dashboard names a directory nobody has
// created yet; every file tool would fail on it. // created yet; every file tool would fail on it.
if err := os.MkdirAll(workspace, 0o700); err != nil { if err := os.MkdirAll(workspace, 0o700); err != nil {
log.Error("create chat workspace", "workspace", workspace, "err", err) log.ErrorContext(ctx, "create chat workspace", "workspace", workspace, "err", err)
} }
if err := b.providerRegistry.Register(builtintoolprovider.New(workspace, unrestricted)); err != nil { if err := b.providerRegistry.Register(builtintoolprovider.New(workspace, unrestricted)); err != nil {
log.Error("workspace tool provider registration failed", "err", err) log.ErrorContext(ctx, "workspace tool provider registration failed", "err", err)
return err return err
} }
log.Info("workspace tools enabled", log.InfoContext(ctx, "workspace tools enabled",
"workspace", workspace, "unrestricted_filesystem", unrestricted) "workspace", workspace, "unrestricted_filesystem", unrestricted)
} else { } else {
log.Info("workspace tools disabled (chat.workspace is unset)") log.InfoContext(ctx, "workspace tools disabled (chat.workspace is unset)")
} }
for _, srv := range cfg.Tools.MCPServers { for _, srv := range cfg.Tools.MCPServers {
provider, err := b.buildMCPProvider(srv) provider, err := b.buildMCPProvider(srv)
if err != nil { if err != nil {
log.Warn("mcp tool provider skipped", "name", srv.Name, "err", err) log.WarnContext(ctx, "mcp tool provider skipped", "name", srv.Name, "err", err)
continue continue
} }
if err := b.providerRegistry.RegisterOptional(provider); err != nil { if err := b.providerRegistry.RegisterOptional(provider); err != nil {
log.Warn("mcp tool provider skipped", "name", srv.Name, "err", err) log.WarnContext(ctx, "mcp tool provider skipped", "name", srv.Name, "err", err)
continue continue
} }
b.mcpMu.Lock() b.mcpMu.Lock()
@@ -69,7 +69,7 @@ func (b *server) registerTools() error {
b.mcpMu.Unlock() b.mcpMu.Unlock()
} }
if err := b.capabilityHost.Register(b.providerRegistry); err != nil { if err := b.capabilityHost.Register(b.providerRegistry); err != nil {
log.Error("tool-provider capability registration failed", "err", err) log.ErrorContext(ctx, "tool-provider capability registration failed", "err", err)
return err return err
} }
return nil return nil
@@ -87,7 +87,7 @@ func (b *server) registerStandaloneTools(ctx context.Context) {
} }
} }
b.registerWebFetchTool(cfg) b.registerWebFetchTool(ctx, cfg)
if entry := sendfile.Tool(cfg.Chat.Workspace); entry != nil { if entry := sendfile.Tool(cfg.Chat.Workspace); entry != nil {
if err := b.toolReg.Register(*entry); err != nil { if err := b.toolReg.Register(*entry); err != nil {
@@ -99,7 +99,7 @@ func (b *server) registerStandaloneTools(ctx context.Context) {
log.InfoContext(ctx, "file sending disabled (chat.workspace is unset)") log.InfoContext(ctx, "file sending disabled (chat.workspace is unset)")
} }
b.registerMinimaxTool(cfg, log) b.registerMinimaxTool(ctx, cfg, log)
b.registerWorkflowTools(ctx) b.registerWorkflowTools(ctx)
} }
@@ -143,7 +143,7 @@ func (s integrationSource) Policies(ctx context.Context) ([]access.Policy, error
return s.store.ListPolicies(ctx) return s.store.ListPolicies(ctx)
} }
func (b *server) registerWebFetchTool(cfg config.Config) { func (b *server) registerWebFetchTool(ctx context.Context, cfg config.Config) {
log := b.log log := b.log
entry := webfetch.Tool(webfetch.Config{ entry := webfetch.Tool(webfetch.Config{
Enabled: cfg.Tools.WebFetch.IsEnabled(), Enabled: cfg.Tools.WebFetch.IsEnabled(),
@@ -152,36 +152,36 @@ func (b *server) registerWebFetchTool(cfg config.Config) {
AllowPrivateNetworks: cfg.Tools.WebFetch.AllowPrivateNetworks, AllowPrivateNetworks: cfg.Tools.WebFetch.AllowPrivateNetworks,
}) })
if entry == nil { if entry == nil {
log.Info("web fetch disabled") log.InfoContext(ctx, "web fetch disabled")
return return
} }
if err := b.toolReg.Register(*entry); err != nil { if err := b.toolReg.Register(*entry); err != nil {
log.Warn("web_fetch registration failed", "err", err) log.WarnContext(ctx, "web_fetch registration failed", "err", err)
return return
} }
log.Info("web fetch enabled", log.InfoContext(ctx, "web fetch enabled",
"allow_private_networks", cfg.Tools.WebFetch.AllowPrivateNetworks) "allow_private_networks", cfg.Tools.WebFetch.AllowPrivateNetworks)
} }
func (b *server) registerMinimaxTool(cfg config.Config, log *slog.Logger) { func (b *server) registerMinimaxTool(ctx context.Context, cfg config.Config, log *slog.Logger) {
if !cfg.Tools.Minimax.IsEnabled() { if !cfg.Tools.Minimax.IsEnabled() {
log.Info("minimax video generation disabled") log.InfoContext(ctx, "minimax video generation disabled")
return return
} }
apiKey, err := b.secrets.Resolve(cfg.Tools.Minimax.APIKey) apiKey, err := b.secrets.Resolve(cfg.Tools.Minimax.APIKey)
if err != nil { if err != nil {
log.Warn("minimax video generation enabled but the API key failed to resolve; tool not registered", "err", err) log.WarnContext(ctx, "minimax video generation enabled but the API key failed to resolve; tool not registered", "err", err)
return return
} }
if apiKey == "" { if apiKey == "" {
log.Warn("minimax video generation enabled but no API key is configured; tool not registered") log.WarnContext(ctx, "minimax video generation enabled but no API key is configured; tool not registered")
return return
} }
provider, err := minimax.New(minimax.Config{APIKey: apiKey, BaseURL: cfg.Tools.Minimax.BaseURL}) provider, err := minimax.New(minimax.Config{APIKey: apiKey, BaseURL: cfg.Tools.Minimax.BaseURL})
if err != nil { if err != nil {
log.Warn("minimax video generation enabled but the provider could not be built; tool not registered", "err", err) log.WarnContext(ctx, "minimax video generation enabled but the provider could not be built; tool not registered", "err", err)
return return
} }
@@ -190,10 +190,10 @@ func (b *server) registerMinimaxTool(cfg config.Config, log *slog.Logger) {
return return
} }
if err := b.toolReg.Register(*entry); err != nil { if err := b.toolReg.Register(*entry); err != nil {
log.Warn("generate_video registration failed", "err", err) log.WarnContext(ctx, "generate_video registration failed", "err", err)
return return
} }
log.Info("minimax video generation enabled") log.InfoContext(ctx, "minimax video generation enabled")
} }
// toolLimits reads the configured per-turn result limits. // toolLimits reads the configured per-turn result limits.
+1 -1
View File
@@ -92,7 +92,7 @@ func (g guardedPolicies) ownerCanManage(ctx context.Context, engine *accessengin
} }
resource := access.Resource{Kind: access.KindPolicy, Org: orgID} resource := access.Resource{Kind: access.KindPolicy, Org: orgID}
for _, principal := range principals { for _, principal := range principals {
if engine.Authorize(principal, access.ActionManagePolicies, resource, access.Context{}).Allowed { if engine.Authorize(ctx, principal, access.ActionManagePolicies, resource, access.Context{}).Allowed {
return true, nil return true, nil
} }
} }
+1 -1
View File
@@ -753,7 +753,7 @@ func (d *Daemon) authorizeDispatch(ctx context.Context, b binding.Binding, c sto
Kind: access.KindWorkflow, ID: b.Workflow, Org: principal.Org, Workspace: b.WorkspaceID, Kind: access.KindWorkflow, ID: b.Workflow, Org: principal.Org, Workspace: b.WorkspaceID,
} }
contextValue := access.Context{Signature: signatureOf(c), Addr: c.RemoteAddr} contextValue := access.Context{Signature: signatureOf(c), Addr: c.RemoteAddr}
decision := d.Access.Authorize(principal, access.ActionRun, resource, contextValue) decision := d.Access.Authorize(ctx, principal, access.ActionRun, resource, contextValue)
if decision.Allowed { if decision.Allowed {
return true return true
} }
+1 -1
View File
@@ -124,7 +124,7 @@ func (d *Daemon) mayRunWorkflow(ctx context.Context, task *workflow.Task, id ide
if resource.Org == "" { if resource.Org == "" {
resource.Org = principal.Org resource.Org = principal.Org
} }
decision := d.Access.Authorize(principal, access.ActionRun, resource, access.Context{Signature: task.BindingSignature, Addr: task.BindingAddr}) decision := d.Access.Authorize(ctx, principal, access.ActionRun, resource, access.Context{Signature: task.BindingSignature, Addr: task.BindingAddr})
if decision.Allowed { if decision.Allowed {
return true, nil return true, nil
} }
+4 -4
View File
@@ -66,7 +66,7 @@ func (agentDirectory) ListOrgAgents(_ context.Context, owner org.OrgID) ([]org.A
// runAllowed permits run only to the identities it lists. // runAllowed permits run only to the identities it lists.
type runAllowed map[identity.IdentityID]bool type runAllowed map[identity.IdentityID]bool
func (r runAllowed) Authorize(p access.Principal, _ access.Action, _ access.Resource, _ access.Context) access.Decision { func (r runAllowed) Authorize(_ context.Context, p access.Principal, _ access.Action, _ access.Resource, _ access.Context) access.Decision {
if r[p.IdentityID] { if r[p.IdentityID] {
return access.Allowed() return access.Allowed()
} }
@@ -78,7 +78,7 @@ func (runAllowed) Reload(context.Context) error { return nil }
// unavailableChain is a chain that cannot be read: nothing is evaluated. // unavailableChain is a chain that cannot be read: nothing is evaluated.
type unavailableChain struct{ runAllowed } type unavailableChain struct{ runAllowed }
func (unavailableChain) Authorize(access.Principal, access.Action, access.Resource, access.Context) access.Decision { func (unavailableChain) Authorize(context.Context, access.Principal, access.Action, access.Resource, access.Context) access.Decision {
return access.Unavailable() return access.Unavailable()
} }
@@ -159,11 +159,11 @@ func TestWorkflowIdentity(t *testing.T) {
// conditioned on context.signature does. // conditioned on context.signature does.
type signedOnly struct{ runAllowed } type signedOnly struct{ runAllowed }
func (s signedOnly) Authorize(p access.Principal, a access.Action, r access.Resource, c access.Context) access.Decision { func (s signedOnly) Authorize(ctx context.Context, p access.Principal, a access.Action, r access.Resource, c access.Context) access.Decision {
if c.Signature != "valid" { if c.Signature != "valid" {
return access.DeniedAt(access.LevelOrg, nil) return access.DeniedAt(access.LevelOrg, nil)
} }
return s.runAllowed.Authorize(p, a, r, c) return s.runAllowed.Authorize(ctx, p, a, r, c)
} }
// TestWorkflowRunCarriesEventContext pins that the run-time re-check sees the // TestWorkflowRunCarriesEventContext pins that the run-time re-check sees the
+4 -2
View File
@@ -4,6 +4,8 @@
package access package access
import ( import (
"context"
"github.com/samcharles93/archie-core/internal/domain/identity" "github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/domain/org" "github.com/samcharles93/archie-core/internal/domain/org"
) )
@@ -15,7 +17,7 @@ type Authorizer interface {
// the request. A request is allowed only if every level with policies // 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 // for it permits it; a forbid at any level wins; with no permit the
// request is denied. // request is denied.
Authorize(p Principal, a Action, r Resource, c Context) Decision Authorize(ctx context.Context, p Principal, a Action, r Resource, c Context) Decision
} }
// Validator checks a policy's Cedar syntax and entity vocabulary. // Validator checks a policy's Cedar syntax and entity vocabulary.
@@ -29,5 +31,5 @@ const SenderID identity.IdentityID = "sender"
// DeliveryAuthorizer decides whether an address may deliver an event to a // DeliveryAuthorizer decides whether an address may deliver an event to a
// source. Only the capture receiver asks. // source. Only the capture receiver asks.
type DeliveryAuthorizer interface { type DeliveryAuthorizer interface {
AuthorizeDelivery(orgID org.OrgID, sourcePath, addr string) Decision AuthorizeDelivery(ctx context.Context, orgID org.OrgID, sourcePath, addr string) Decision
} }
+1 -1
View File
@@ -27,7 +27,7 @@ func guarded(authz access.Authorizer, action access.Action, kind access.Resource
if id != nil { if id != nil {
resource.ID = id(input) resource.ID = id(input)
} }
decision := authz.Authorize(p, action, resource, access.Context{}) decision := authz.Authorize(ctx, p, action, resource, access.Context{})
if decision.Allowed { if decision.Allowed {
return handler(ctx, input) return handler(ctx, input)
} }
+1 -1
View File
@@ -10,7 +10,7 @@ import (
type allowOnly struct{ action access.Action } type allowOnly struct{ action access.Action }
func (a allowOnly) Authorize(_ access.Principal, action access.Action, _ access.Resource, _ access.Context) access.Decision { func (a allowOnly) Authorize(_ context.Context, _ access.Principal, action access.Action, _ access.Resource, _ access.Context) access.Decision {
return access.Decision{Allowed: action == a.action} return access.Decision{Allowed: action == a.action}
} }
@@ -45,7 +45,7 @@ func TestAuthorizeDelivery(t *testing.T) {
if acting == "" { if acting == "" {
acting = org.DefaultOrgID acting = org.DefaultOrgID
} }
if got := engine.AuthorizeDelivery(acting, tt.source, tt.addr); got.Allowed != tt.allowed { if got := engine.AuthorizeDelivery(t.Context(), acting, tt.source, tt.addr); got.Allowed != tt.allowed {
t.Fatalf("allowed = %v, want %v (%+v)", got.Allowed, tt.allowed, got) t.Fatalf("allowed = %v, want %v (%+v)", got.Allowed, tt.allowed, got)
} }
}) })
+3 -2
View File
@@ -4,6 +4,7 @@
package access package access
import ( import (
"context"
"fmt" "fmt"
"sync" "sync"
@@ -192,7 +193,7 @@ func compile(p access.Policy) (*cedar.Policy, error) {
} }
// Authorize evaluates the chain for one request. // 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 { func (e *Engine) Authorize(_ context.Context, p access.Principal, a access.Action, r access.Resource, c access.Context) access.Decision {
if e.pending { if e.pending {
return access.Unavailable() return access.Unavailable()
} }
@@ -215,7 +216,7 @@ func (e *Engine) Authorize(p access.Principal, a access.Action, r access.Resourc
// the instance network rules, then the source's own object policies. A // the instance network rules, then the source's own object policies. A
// sender has no identity or role, so the org and workspace role policies // sender has no identity or role, so the org and workspace role policies
// never apply to it. // never apply to it.
func (e *Engine) AuthorizeDelivery(orgID org.OrgID, sourcePath, addr string) access.Decision { func (e *Engine) AuthorizeDelivery(_ context.Context, orgID org.OrgID, sourcePath, addr string) access.Decision {
if e.pending { if e.pending {
return access.Unavailable() return access.Unavailable()
} }
@@ -38,7 +38,7 @@ func TestInvalidInstancePolicy(t *testing.T) {
} }
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
got := engine.Authorize(tt.principal, tt.action, access.Resource{Kind: tt.kind}, access.Context{}) got := engine.Authorize(t.Context(), tt.principal, tt.action, access.Resource{Kind: tt.kind}, access.Context{})
if got.Allowed != tt.allowed { if got.Allowed != tt.allowed {
t.Fatalf("allowed = %v, want %v (%+v)", got.Allowed, tt.allowed, got) t.Fatalf("allowed = %v, want %v (%+v)", got.Allowed, tt.allowed, got)
} }
@@ -67,7 +67,7 @@ func TestReadAuditRoleBoundary(t *testing.T) {
IdentityID: "person", Org: auditOrg, IdentityID: "person", Org: auditOrg,
Memberships: []org.Membership{{IdentityID: "person", OrgID: auditOrg, Role: tt.role}}, Memberships: []org.Membership{{IdentityID: "person", OrgID: auditOrg, Role: tt.role}},
} }
got := engine.Authorize(p, access.ActionReadAudit, access.Resource{Kind: access.KindAudit, Org: auditOrg}, access.Context{}) got := engine.Authorize(t.Context(), p, access.ActionReadAudit, access.Resource{Kind: access.KindAudit, Org: auditOrg}, access.Context{})
if got.Allowed != tt.allowed { if got.Allowed != tt.allowed {
t.Fatalf("allowed = %v, want %v (%+v)", got.Allowed, tt.allowed, got) t.Fatalf("allowed = %v, want %v (%+v)", got.Allowed, tt.allowed, got)
} }
@@ -106,7 +106,7 @@ func TestWorkspaceEnvironment(t *testing.T) {
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
resource := access.Resource{Kind: access.KindWorkflow, ID: "triage", Org: "acme", Workspace: tt.workspace} resource := access.Resource{Kind: access.KindWorkflow, ID: "triage", Org: "acme", Workspace: tt.workspace}
if got := engine.Authorize(dev, tt.action, resource, access.Context{}); got.Allowed != tt.allowed { if got := engine.Authorize(t.Context(), dev, tt.action, resource, access.Context{}); got.Allowed != tt.allowed {
t.Fatalf("allowed = %v, want %v (%+v)", got.Allowed, tt.allowed, got) t.Fatalf("allowed = %v, want %v (%+v)", got.Allowed, tt.allowed, got)
} }
}) })
+16 -19
View File
@@ -11,10 +11,9 @@ import (
"github.com/samcharles93/archie-core/internal/domain/org" "github.com/samcharles93/archie-core/internal/domain/org"
) )
// versionTimeout bounds one check of the version and the policies. The // versionTimeout bounds one check of the version and the policies. Without a
// Authorizer contract carries no context, so the check owns its deadline: // deadline a hung State Store would hang every decision in the process instead
// without one a hung State Store would hang every decision in the process // of refusing.
// instead of refusing.
const versionTimeout = 5 * time.Second const versionTimeout = 5 * time.Second
// Live is an engine rebuilt from the stored policies whenever their version // Live is an engine rebuilt from the stored policies whenever their version
@@ -23,10 +22,6 @@ const versionTimeout = 5 * time.Second
// holds may predate the edit, and standing on it would be exactly the allow // holds may predate the edit, and standing on it would be exactly the allow
// the edit meant to remove. // the edit meant to remove.
type Live struct { type Live struct {
// ctx is the process lifetime: no request's context reaches a check.
//
//nolint:containedctx // The Authorizer contract carries no context, so the check has nothing but the process's own to derive a deadline from.
ctx context.Context
version func(context.Context) (int64, error) version func(context.Context) (int64, error)
load func(context.Context) ([]access.Policy, error) load func(context.Context) ([]access.Policy, error)
log *slog.Logger log *slog.Logger
@@ -46,9 +41,8 @@ type Live struct {
// one org would cache that org's policies under the instance-wide version, and // one org would cache that org's policies under the instance-wide version, and
// every other org's policies would stay missing for as long as the version // every other org's policies would stay missing for as long as the version
// holds. // holds.
func NewPending(ctx context.Context, version func(context.Context) (int64, error), load func(context.Context) ([]access.Policy, error), log *slog.Logger) *Live { func NewPending(version func(context.Context) (int64, error), load func(context.Context) ([]access.Policy, error), log *slog.Logger) *Live {
l := &Live{ l := &Live{
ctx: ctx,
version: version, version: version,
load: func(ctx context.Context) ([]access.Policy, error) { load: func(ctx context.Context) ([]access.Policy, error) {
return load(access.WithoutPrincipal(ctx)) return load(access.WithoutPrincipal(ctx))
@@ -84,8 +78,8 @@ func (l *Live) Reload(ctx context.Context) error {
// current returns the engine for the version the store reports, rebuilding it // current returns the engine for the version the store reports, rebuilding it
// when the version moved since the engine was built. A check that cannot read // when the version moved since the engine was built. A check that cannot read
// the store returns the pending engine, which refuses everything. // the store returns the pending engine, which refuses everything.
func (l *Live) current() *Engine { func (l *Live) current(ctx context.Context) *Engine {
ctx, cancel := context.WithTimeout(l.ctx, versionTimeout) ctx, cancel := context.WithTimeout(ctx, versionTimeout)
defer cancel() defer cancel()
// The version before the list, never after and never in the same // The version before the list, never after and never in the same
@@ -95,7 +89,7 @@ func (l *Live) current() *Engine {
// and no later check would ever see a version it had not already applied. // and no later check would ever see a version it had not already applied.
version, err := l.version(ctx) version, err := l.version(ctx)
if err != nil { if err != nil {
l.log.Warn("access policy version unavailable; refusing until it is readable", "err", err) l.log.WarnContext(ctx, "access policy version unavailable; refusing until it is readable", "err", err)
return pendingEngine return pendingEngine
} }
if version == l.stamp.Load() { if version == l.stamp.Load() {
@@ -108,7 +102,7 @@ func (l *Live) current() *Engine {
return l.engine.Load() return l.engine.Load()
} }
if err := l.apply(ctx, version); err != nil { if err := l.apply(ctx, version); err != nil {
l.log.Warn("access policies not reloaded; refusing until they load", "err", err) l.log.WarnContext(ctx, "access policies not reloaded; refusing until they load", "err", err)
return pendingEngine return pendingEngine
} }
return l.engine.Load() return l.engine.Load()
@@ -133,12 +127,15 @@ func (l *Live) apply(ctx context.Context, version int64) error {
return nil return nil
} }
func (l *Live) Authorize(p access.Principal, a access.Action, r access.Resource, c access.Context) access.Decision { func (l *Live) Authorize(ctx context.Context, p access.Principal, a access.Action, r access.Resource, c access.Context) access.Decision {
return l.current().Authorize(p, a, r, c) return l.current(ctx).Authorize(ctx, p, a, r, c)
} }
func (l *Live) AuthorizeDelivery(orgID org.OrgID, sourcePath, addr string) access.Decision { // AuthorizeDelivery has no caller context: the DeliveryAuthorizer contract
return l.current().AuthorizeDelivery(orgID, sourcePath, addr) // carries none, so its check runs under the background context and the
// version deadline bounds it.
func (l *Live) AuthorizeDelivery(ctx context.Context, orgID org.OrgID, sourcePath, addr string) access.Decision {
return l.current(ctx).AuthorizeDelivery(ctx, orgID, sourcePath, addr)
} }
// Problems reports the current engine's invalid policies. // Problems reports the current engine's invalid policies.
@@ -147,7 +144,7 @@ func (l *Live) Problems() []Problem { return l.engine.Load().Problems() }
// StartLive loads the stored policies through list and keeps them current as // StartLive loads the stored policies through list and keeps them current as
// they change. // they change.
func StartLive(ctx context.Context, list func(context.Context) ([]access.Policy, error), version func(context.Context) (int64, error), log *slog.Logger) *Live { func StartLive(ctx context.Context, list func(context.Context) ([]access.Policy, error), version func(context.Context) (int64, error), log *slog.Logger) *Live {
live := NewPending(ctx, version, list, log) live := NewPending(version, list, log)
if err := live.Reload(ctx); err != nil { if err := live.Reload(ctx); err != nil {
log.WarnContext(ctx, "access policies not loaded; requests are refused until they load", "err", err) log.WarnContext(ctx, "access policies not loaded; requests are refused until they load", "err", err)
} }
+5 -5
View File
@@ -13,7 +13,7 @@ import (
// is up refuses every request until the first load succeeds, then allows. // is up refuses every request until the first load succeeds, then allows.
func TestPendingChainRefusesUntilLoaded(t *testing.T) { func TestPendingChainRefusesUntilLoaded(t *testing.T) {
loaded := false loaded := false
live := NewPending(t.Context(), func(context.Context) (int64, error) { live := NewPending(func(context.Context) (int64, error) {
return 1, nil return 1, nil
}, func(context.Context) ([]access.Policy, error) { }, func(context.Context) ([]access.Policy, error) {
if !loaded { if !loaded {
@@ -23,7 +23,7 @@ func TestPendingChainRefusesUntilLoaded(t *testing.T) {
}, slog.New(slog.DiscardHandler)) }, slog.New(slog.DiscardHandler))
request := func() access.Decision { request := func() access.Decision {
return live.Authorize(access.SharedTokenOwner(), access.ActionRead, return live.Authorize(t.Context(), access.SharedTokenOwner(), access.ActionRead,
access.Resource{Kind: access.KindDashboard}, access.Context{}) access.Resource{Kind: access.KindDashboard}, access.Context{})
} }
@@ -36,7 +36,7 @@ func TestPendingChainRefusesUntilLoaded(t *testing.T) {
if got := live.Problems(); got != nil { if got := live.Problems(); got != nil {
t.Fatalf("Problems before load = %v, want nil", got) t.Fatalf("Problems before load = %v, want nil", got)
} }
if decision := live.AuthorizeDelivery("acme", "sources/x", "10.0.0.1"); decision.Allowed || if decision := live.AuthorizeDelivery(t.Context(), "acme", "sources/x", "10.0.0.1"); decision.Allowed ||
!errors.Is(decision.Err, access.ErrChainUnavailable) { !errors.Is(decision.Err, access.ErrChainUnavailable) {
t.Fatalf("delivery before load = %+v, want the not-loaded refusal", decision) t.Fatalf("delivery before load = %+v, want the not-loaded refusal", decision)
} }
@@ -86,7 +86,7 @@ func TestLiveAppliesAPolicyEditBeforeTheNextDecision(t *testing.T) {
forbidAll := access.Policy{ID: "forbid-all", Level: access.LevelInstance, Text: `forbid(principal, action, resource);`} forbidAll := access.Policy{ID: "forbid-all", Level: access.LevelInstance, Text: `forbid(principal, action, resource);`}
storeDown := errors.New("state store down") storeDown := errors.New("state store down")
request := func(live *Live) access.Decision { request := func(live *Live) access.Decision {
return live.Authorize(access.SharedTokenOwner(), access.ActionRead, return live.Authorize(t.Context(), access.SharedTokenOwner(), access.ActionRead,
access.Resource{Kind: access.KindDashboard}, access.Context{}) access.Resource{Kind: access.KindDashboard}, access.Context{})
} }
tests := []struct { tests := []struct {
@@ -124,7 +124,7 @@ func TestLiveAppliesAPolicyEditBeforeTheNextDecision(t *testing.T) {
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
store := &fakePolicyStore{version: 1} store := &fakePolicyStore{version: 1}
live := NewPending(t.Context(), store.PoliciesVersion, store.ListPolicies, slog.New(slog.DiscardHandler)) live := NewPending(store.PoliciesVersion, store.ListPolicies, slog.New(slog.DiscardHandler))
if err := live.Reload(t.Context()); err != nil { if err := live.Reload(t.Context()); err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -40,7 +40,7 @@ type stubDelivery struct {
decision access.Decision decision access.Decision
} }
func (s *stubDelivery) AuthorizeDelivery(orgID org.OrgID, _, _ string) access.Decision { func (s *stubDelivery) AuthorizeDelivery(_ context.Context, orgID org.OrgID, _, _ string) access.Decision {
s.orgID = orgID s.orgID = orgID
return s.decision return s.decision
} }
@@ -175,7 +175,7 @@ func (rc *Receiver) refusal(r *http.Request, path string, owner org.OrgID) int {
return 0 return 0
} }
addr := remoteAddrHost(r) addr := remoteAddrHost(r)
decision := rc.Delivery.AuthorizeDelivery(owner, path, addr) decision := rc.Delivery.AuthorizeDelivery(r.Context(), owner, path, addr)
if decision.Allowed { if decision.Allowed {
return 0 return 0
} }
@@ -16,7 +16,7 @@ import (
// once they do, without rebuilding the probe. // once they do, without rebuilding the probe.
func TestProblemProbeFollowsTheChain(t *testing.T) { func TestProblemProbeFollowsTheChain(t *testing.T) {
up := false up := false
chain := infraaccess.NewPending(t.Context(), func(context.Context) (int64, error) { chain := infraaccess.NewPending(func(context.Context) (int64, error) {
return 1, nil return 1, nil
}, func(context.Context) ([]access.Policy, error) { }, func(context.Context) ([]access.Policy, error) {
if !up { if !up {
+1 -1
View File
@@ -162,7 +162,7 @@ func (s *server) authorizeAccountManagement(ctx context.Context) error {
if err != nil { if err != nil {
return status.Error(codes.Unavailable, "access policies unavailable") return status.Error(codes.Unavailable, "access policies unavailable")
} }
decision := infraaccess.New(policies).Authorize(p, access.ActionManageMembers, access.Resource{Kind: access.KindMember, Org: p.Org}, access.Context{}) decision := infraaccess.New(policies).Authorize(ctx, p, access.ActionManageMembers, access.Resource{Kind: access.KindMember, Org: p.Org}, access.Context{})
if !decision.Allowed { if !decision.Allowed {
return status.Error(codes.PermissionDenied, "account management refused") return status.Error(codes.PermissionDenied, "account management refused")
} }
+2 -2
View File
@@ -54,7 +54,7 @@ func (s *Server) authorize(h http.Handler) http.Handler {
return return
} }
peer, _, _ := net.SplitHostPort(r.RemoteAddr) peer, _, _ := net.SplitHostPort(r.RemoteAddr)
decision := s.Access.Authorize(principal, action, resource, access.Context{Addr: peer}) decision := s.Access.Authorize(ctx, principal, action, resource, access.Context{Addr: peer})
if !decision.Allowed { if !decision.Allowed {
if errors.Is(decision.Err, access.ErrChainUnavailable) { if errors.Is(decision.Err, access.ErrChainUnavailable) {
// Nothing was evaluated: the chain has not loaded. This is an // Nothing was evaluated: the chain has not loaded. This is an
@@ -87,7 +87,7 @@ func (s *Server) authorizeCreateIn(w http.ResponseWriter, r *http.Request, kind
return true return true
} }
resource := access.Resource{Kind: kind, Org: principal.Org, Workspace: workspace} resource := access.Resource{Kind: kind, Org: principal.Org, Workspace: workspace}
decision := s.Access.Authorize(principal, access.ActionCreate, resource, access.Context{}) decision := s.Access.Authorize(r.Context(), principal, access.ActionCreate, resource, access.Context{})
if decision.Allowed { if decision.Allowed {
return true return true
} }
+2 -2
View File
@@ -46,7 +46,7 @@ func (s operatorPrincipals) PrincipalFor(_ context.Context, id identity.Identity
type allowAll struct{} type allowAll struct{}
func (allowAll) Authorize(access.Principal, access.Action, access.Resource, access.Context) access.Decision { func (allowAll) Authorize(context.Context, access.Principal, access.Action, access.Resource, access.Context) access.Decision {
return access.Allowed() return access.Allowed()
} }
@@ -56,7 +56,7 @@ func (allowAll) Ready() bool { return true }
// is the not-loaded refusal, which no policy evaluated. // is the not-loaded refusal, which no policy evaluated.
type notReadyChain struct{} type notReadyChain struct{}
func (notReadyChain) Authorize(access.Principal, access.Action, access.Resource, access.Context) access.Decision { func (notReadyChain) Authorize(context.Context, access.Principal, access.Action, access.Resource, access.Context) access.Decision {
return access.Unavailable() return access.Unavailable()
} }
+1 -1
View File
@@ -513,7 +513,7 @@ func TestOrgSelection(t *testing.T) {
// recordingChain allows everything and keeps the last principal it judged. // recordingChain allows everything and keeps the last principal it judged.
type recordingChain struct{ last access.Principal } type recordingChain struct{ last access.Principal }
func (c *recordingChain) Authorize(p access.Principal, _ access.Action, _ access.Resource, _ access.Context) access.Decision { func (c *recordingChain) Authorize(_ context.Context, p access.Principal, _ access.Action, _ access.Resource, _ access.Context) access.Decision {
c.last = p c.last = p
return access.Allowed() return access.Allowed()
} }
+1 -1
View File
@@ -84,5 +84,5 @@ func (s *Server) mayCall(r *http.Request, method, path string) bool {
} }
action, kind, id := accessRequest(&http.Request{Method: method, URL: &url.URL{Path: path}}) action, kind, id := accessRequest(&http.Request{Method: method, URL: &url.URL{Path: path}})
resource, err := s.recordResource(r.Context(), kind, id) resource, err := s.recordResource(r.Context(), kind, id)
return err == nil && s.Access.Authorize(principal, action, resource, access.Context{}).Allowed return err == nil && s.Access.Authorize(r.Context(), principal, action, resource, access.Context{}).Allowed
} }