refactor(daemon): identity, org and access checks are their own gate (#1934)

This commit is contained in:
sam committed 2026-11-13 04:20:41 +11:00
1 parent 500d02be78
commit bdc457d11e
16 files changed
+155 -109

No files matched your search

+7 -10
View File
@@ -592,16 +592,14 @@ func (b *boot) issueForge(ctx context.Context, owner, repo string) (forge.IssueF
func (b *boot) buildDaemon(ctx context.Context) {
log := b.log
workspaces, _ := b.stateStore.(access.WorkspaceLister)
d := &daemon.Daemon{
ResolveRepository: b.repositoryAccess,
Cfg: b.cfgHolder,
ConnectedNATS: daemon.NATSEndpoint{URL: b.natsURL, Token: b.natsToken, Scoped: b.cfg.NATS.Mode != config.NATSModeExternal},
ConnectedStateStore: daemon.StateStoreEndpoint{URL: strings.TrimSpace(b.cfg.Services.Get(config.ServiceNameState).Target), CA: b.stateStoreCA(ctx)},
Store: b.stateStore,
IdentityRepository: b.stateClient,
AgentAssignments: b.stateClient,
Principals: b.stateClient,
Denials: b.stateClient,
Identity: daemon.NewIdentityGate(b.stateClient, b.stateClient, b.accessChain, b.stateClient, b.stateClient, b.orgPrincipals, workspaces, log),
PlaybookLedger: b.stateClient,
Bus: b.bus,
Forge: b.forgeClient,
@@ -621,8 +619,7 @@ func (b *boot) buildDaemon(ctx context.Context) {
Playbooks: b.livePlaybooks(),
}
d.Access = b.accessChain
d.ReviewScanner = daemon.NewReviewScanner(b.stateStore, b.reactionClient, b.natsClient.PublishUnique, b.bus, d, d, d, log)
d.ReviewScanner = daemon.NewReviewScanner(b.stateStore, b.reactionClient, b.natsClient.PublishUnique, b.bus, d, d.Identity, d, log)
d.BindingDispatch = daemon.NewBindingDispatch(daemon.BindingDispatchDeps{
Store: b.stateStore,
Mappings: b.stateClient,
@@ -632,15 +629,15 @@ func (b *boot) buildDaemon(ctx context.Context) {
Creator: b.stateClient,
Enablement: b.controlPlane,
Definitions: b.workflowDefinitions,
Access: b.accessChain,
Denials: b.stateClient,
Access: d.Identity,
Denials: d.Identity,
Cfg: b.cfgHolder,
Orgs: d,
Orgs: d.Identity,
OrgPrincipals: b.orgPrincipals,
Log: log,
})
d.WireTaskBus()
d.IssuePoller = daemon.NewIssuePoller(b.cfgHolder, b.stateStore, log, b.issueSources, b.taskActions().Withdraw, d.TaskBus.PublishTask, d, d.BindingDispatch)
d.IssuePoller = daemon.NewIssuePoller(b.cfgHolder, b.stateStore, log, b.issueSources, b.taskActions().Withdraw, d.TaskBus.PublishTask, d.Identity, d.BindingDispatch)
b.d = d
}
+1 -1
View File
@@ -41,7 +41,7 @@ func (b *boot) setupDaemonRPC(ctx context.Context) {
return
}
workspaces, _ := b.stateStore.(access.WorkspaceLister)
callers := rpcidentity.Callers{Principals: b.d.Principals, Workspaces: workspaces}
callers := rpcidentity.Callers{Principals: b.d.Identity.Principals(), Workspaces: workspaces}
srv := grpc.NewServer(append(servicekit.ServerLimits(), creds, grpc.ChainUnaryInterceptor(callers.Unary()), grpc.ChainStreamInterceptor(callers.Stream()))...)
daemonpb.RegisterDaemonServiceServer(srv, &repositoryServer{boot: b})
go func() {
@@ -177,7 +177,7 @@ func TestPrivateRepositoryConnection(t *testing.T) {
defer fixture.Close()
docs := &repositoryDocuments{repos: map[org.OrgID][]config.Repo{"org-a": {{Owner: "acme", Name: "app", Connection: "private", Base: "main"}}}, connections: map[org.OrgID][]config.ForgeConnection{"org-a": {{ID: "private", Name: "Private forge", Type: "gitea", Host: fixture.URL, Account: "forge-account", Token: config.SecretRef{Engine: "env", Key: "ARCHIE_TEST_CONNECTION_TOKEN"}, Permits: map[string][]string{"bot-a": {"clone", "push"}}}}}}
b := &boot{controlPlane: controlplanestore.NewRPCClient(docs), cfgHolder: config.NewHolder(config.Config{WorkDir: t.TempDir(), BotUser: "Commit author", BotEmail: "author@example.test"}), secrets: secret.NewRegistry(), log: slog.New(slog.DiscardHandler)}
b.d = &daemon.Daemon{Access: infraaccess.New(access.ShippedOrgPolicies("org-a")), Principals: connectionPrincipals{"bot-a": "org-a", "bot-b": "org-b"}, IdentityRepository: connectionIdentities{}, AgentAssignments: connectionAssignments{}, ResolveRepository: b.repositoryAccess}
b.d = &daemon.Daemon{Identity: daemon.NewIdentityGate(connectionIdentities{}, connectionAssignments{}, infraaccess.New(access.ShippedOrgPolicies("org-a")), connectionPrincipals{"bot-a": "org-a", "bot-b": "org-b"}, nil, nil, nil, b.log), ResolveRepository: b.repositoryAccess}
checker := &repositoryServer{boot: b}
request := &daemonpb.CheckRepositoryRequest{Owner: "acme", Repository: "app", IdentityId: "bot-a"}
operator := access.Principal{IdentityID: "operator", Kind: identity.KindUser, Org: "org-a", Memberships: []org.Membership{{IdentityID: "operator", OrgID: "org-a", Role: org.RoleAdmin}}}
+1 -1
View File
@@ -37,7 +37,7 @@ func (s *repositoryServer) CheckRepository(ctx context.Context, r *pb.CheckRepos
if b.d == nil {
return nil, status.Error(codes.Unavailable, "Repository checks are temporarily unavailable.")
}
decision := b.d.Access.Authorize(ctx, caller, access.ActionUpdate, access.Resource{Kind: access.KindPolicy, ID: "repository-policies", Org: caller.Org}, access.Context{})
decision := b.d.Identity.Authorize(ctx, caller, access.ActionUpdate, access.Resource{Kind: access.KindPolicy, ID: "repository-policies", Org: caller.Org}, access.Context{})
if !decision.Allowed {
return nil, status.Error(codes.PermissionDenied, "You do not have permission to check repository access.")
}
+7 -20
View File
@@ -14,10 +14,8 @@ import (
"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/eda/playbook"
"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/workflow"
"github.com/samcharles93/archie-core/internal/eventbus"
@@ -87,19 +85,13 @@ type Daemon struct {
// BindingDispatch offers captured events to armed bindings and starts their
// tasks. Built by the composition root from its own stores.
BindingDispatch *BindingDispatch
// Access evaluates the policy chain at dispatch, the second of the two
// Authorizer call sites: the workflow's identity may `run` the workflow in
// its workspace.
Access access.Authorizer
// Principals assembles the dispatch principal for the workflow's
// identity.
Principals access.PrincipalSource
// Denials records dispatch refusals.
Denials access.DenialRecorder
Forge forge.Forge
Trees *worktree.Manager
Bus *events.Bus
Log *slog.Logger
// Identity answers identity, org and access questions. Built by the
// composition root with NewIdentityGate.
Identity *IdentityGate
Forge forge.Forge
Trees *worktree.Manager
Bus *events.Bus
Log *slog.Logger
// TaskTransport is the NATS connection the task bus runs on. The bus is
// built by WireTaskBus.
TaskTransport TaskTransport
@@ -133,11 +125,6 @@ type Daemon struct {
Storage storage.Backend
// IssuePoller discovers forge issues and publishes them as tasks.
IssuePoller *IssuePoller
// IdentityRepository is the durable lifecycle authority. Polling checks it
// every cycle so suspend/reactivate commands do not require a restart.
IdentityRepository identity.Repository
AgentAssignments org.AgentAssignments
// PackageAuthorities bounds the tools a package workflow's run is offered.
PackageAuthorities PackageAuthorities
+78 -11
View File
@@ -2,14 +2,54 @@ package daemon
import (
"context"
"log/slog"
"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/taskstate"
)
// identityOrg resolves an identity's org. No PrincipalSource means the
// default org; a store error is returned.
// IdentityGate answers who an identity is, which org it acts for, whether it
// may act, and whether it may run a workflow. It is the only part of the
// daemon that reads the identity repository, agent assignments and the policy
// chain for those questions.
type IdentityGate struct {
identities identity.Repository
assignments org.AgentAssignments
authorizer access.Authorizer
principals access.PrincipalSource
denials access.DenialRecorder
orgs func(context.Context) []access.Principal
workspaces access.WorkspaceLister
log *slog.Logger
}
// NewIdentityGate builds the gate from the State Store surfaces it reads.
// workspaces lets a principal select an org it is a member of; it is the
// State Store's own WorkspaceLister, or nil when the store has none.
func NewIdentityGate(
identities identity.Repository,
assignments org.AgentAssignments,
authorizer access.Authorizer,
principals access.PrincipalSource,
denials access.DenialRecorder,
orgs func(context.Context) []access.Principal,
workspaces access.WorkspaceLister,
log *slog.Logger,
) *IdentityGate {
return &IdentityGate{
identities: identities,
assignments: assignments,
authorizer: authorizer,
principals: principals,
denials: denials,
orgs: orgs,
workspaces: workspaces,
log: log,
}
}
// orgResolver is the identity-to-org surface the identity checks read through.
type orgResolver interface {
identityOrg(ctx context.Context, id identity.IdentityID) (org.OrgID, error)
@@ -17,24 +57,51 @@ type orgResolver interface {
identityActive(ctx context.Context, id identity.IdentityID) bool
}
var _ orgResolver = (*Daemon)(nil)
var _ orgResolver = (*IdentityGate)(nil)
func (d *Daemon) identityOrg(ctx context.Context, id identity.IdentityID) (org.OrgID, error) {
principal, err := d.Principals.PrincipalFor(ctx, id)
// Authorize evaluates the policy chain for principal's action on resource.
func (g *IdentityGate) Authorize(ctx context.Context, principal access.Principal, action access.Action, resource access.Resource, c access.Context) access.Decision {
return g.authorizer.Authorize(ctx, principal, action, resource, c)
}
// RecordDenial stores a refused action so the operator can see it.
func (g *IdentityGate) RecordDenial(ctx context.Context, denial access.Denial) error {
return g.denials.RecordDenial(ctx, denial)
}
// OrgPrincipals is one acting principal per organisation, system org first.
func (g *IdentityGate) OrgPrincipals(ctx context.Context) []access.Principal {
return g.orgs(ctx)
}
// Principals is the source that resolves an identity to its principal, for the
// RPC callers that authenticate requests.
func (g *IdentityGate) Principals() access.PrincipalSource {
return g.principals
}
// Lookup reads an identity's stored record.
func (g *IdentityGate) Lookup(ctx context.Context, id identity.IdentityID) (identity.Identity, error) {
return g.identities.Get(ctx, id)
}
// identityOrg resolves an identity's org. A store error is returned.
func (g *IdentityGate) identityOrg(ctx context.Context, id identity.IdentityID) (org.OrgID, error) {
principal, err := g.principals.PrincipalFor(ctx, id)
if err != nil {
return "", err
}
return principal.Org, nil
}
func (d *Daemon) identityActive(ctx context.Context, id identity.IdentityID) bool {
func (g *IdentityGate) identityActive(ctx context.Context, id identity.IdentityID) bool {
if id == "" {
d.Log.ErrorContext(ctx, "identity lifecycle check failed", "err", "identity ID is empty")
g.log.ErrorContext(ctx, "identity lifecycle check failed", "err", "identity ID is empty")
return false
}
value, err := d.IdentityRepository.Get(ctx, id)
value, err := g.identities.Get(ctx, id)
if err != nil {
d.Log.ErrorContext(ctx, "identity lifecycle check failed", "identity", id, "err", err)
g.log.ErrorContext(ctx, "identity lifecycle check failed", "identity", id, "err", err)
return false
}
return value.Lifecycle == identity.LifecycleActive
@@ -43,11 +110,11 @@ func (d *Daemon) identityActive(ctx context.Context, id identity.IdentityID) boo
// identityMayAct reports whether a task's identity may act, and the park
// class if not. An empty, unknown or inactive identity never falls back to
// the System forge.
func (d *Daemon) identityMayAct(ctx context.Context, name string) (bool, string, taskstate.ParkClass) {
func (g *IdentityGate) identityMayAct(ctx context.Context, name string) (bool, string, taskstate.ParkClass) {
if name == "" {
return false, "task has no identity", taskstate.ParkNeedsDecision
}
value, err := d.IdentityRepository.Get(ctx, identity.IdentityID(name))
value, err := g.identities.Get(ctx, identity.IdentityID(name))
if err != nil {
return false, "execution identity unavailable: " + err.Error(), taskstate.ParkTransient
}
+3 -2
View File
@@ -90,10 +90,11 @@ func TestPollNATSSkipsDisabledRoutedWorkflow(t *testing.T) {
bus := &publishCounter{}
fg := &reactCounter{}
var logs bytes.Buffer
logger := slog.New(slog.NewTextHandler(&logs, nil))
d := wired(&Daemon{
Log: slog.New(slog.NewTextHandler(&logs, nil)), Store: taskLookup{}, TaskTransport: bus,
Log: logger, Store: taskLookup{}, TaskTransport: bus,
WorkflowDefinitions: tt.definitions,
Principals: tt.principals,
Identity: NewIdentityGate(neutralIdentities{}, neutralAssignments{}, allowAll{}, tt.principals, neutralDenials{}, nil, nil, logger),
})
d.BindingDispatch.enablement = tt.enablement
is := forge.Issue{Number: 42, Title: "crash on startup"}
+1 -1
View File
@@ -76,7 +76,7 @@ func (d *Daemon) recordPark(ctx context.Context, taskID int64, reason string) {
// parkIfIdentityUnresolvable parks task when its identity cannot be acted on,
// reporting whether it did.
func (d *Daemon) parkIfIdentityUnresolvable(ctx context.Context, task *workflow.Task) bool {
ok, reason, class := d.identityMayAct(ctx, task.Identity)
ok, reason, class := d.Identity.identityMayAct(ctx, task.Identity)
if ok {
return false
}
+1 -1
View File
@@ -50,7 +50,7 @@ func (d *Daemon) pinTaskProfile(ctx context.Context, task *workflow.Task) (confi
// passes through here, whatever started it, so this is the one enablement
// check for issue labels, handoffs, approvals, calls and playbooks alike.
func (d *Daemon) pinWorkflowDefinition(ctx context.Context, task *workflow.Task) error {
ctx, err := d.workflowContext(ctx, task)
ctx, err := d.Identity.workflowContext(ctx, task)
if err != nil {
return err
}
+3 -3
View File
@@ -361,17 +361,17 @@ func (d *Daemon) Repository(ctx context.Context, task *workflow.Task, operation
if err != nil || iface.Identity == "" {
return RepositoryAccess{}, fmt.Errorf("workflow execution identity unavailable")
}
_, name, err := d.declaredIdentity(ctx, &run, iface.Identity)
_, name, err := d.Identity.declaredIdentity(ctx, &run, iface.Identity)
if err != nil {
return RepositoryAccess{}, err
}
run.Identity = name
}
ctx, err := d.workflowContext(ctx, &run)
ctx, err := d.Identity.workflowContext(ctx, &run)
if err != nil {
return RepositoryAccess{}, err
}
if _, err := d.databaseExecutionIdentity(ctx, &run, identity.IdentityID(run.Identity)); err != nil {
if _, err := d.Identity.databaseExecutionIdentity(ctx, &run, identity.IdentityID(run.Identity)); err != nil {
return RepositoryAccess{}, err
}
return d.ResolveRepository(ctx, &run, operation)
+10 -5
View File
@@ -24,7 +24,7 @@ import (
type TaskBus struct {
transport TaskTransport
store storecontract.TaskStore
identities identity.Repository
identities identityLookup
log *slog.Logger
orgs orgResolver
process func(context.Context, *workflow.Task, *taskHold)
@@ -37,7 +37,7 @@ type TaskBus struct {
type TaskBusDeps struct {
Transport TaskTransport
Store storecontract.TaskStore
Identities identity.Repository
Identities identityLookup
Log *slog.Logger
Orgs orgResolver
MaxConcurrency int
@@ -69,9 +69,9 @@ func (d *Daemon) WireTaskBus() {
d.TaskBus = NewTaskBus(TaskBusDeps{
Transport: d.TaskTransport,
Store: d.Store,
Identities: d.IdentityRepository,
Identities: d.Identity,
Log: d.Log,
Orgs: d,
Orgs: d.Identity,
MaxConcurrency: d.Cfg.Get().Containers.MaxConcurrency,
AllowConcurrent: d.allowConcurrentForTask,
Process: d.process,
@@ -80,6 +80,11 @@ func (d *Daemon) WireTaskBus() {
})
}
// identityLookup reads one identity record.
type identityLookup interface {
Lookup(ctx context.Context, id identity.IdentityID) (identity.Identity, error)
}
// drainLoop is the only task drainer and capture dispatcher while Run is
// active. It runs apart from the poll tick so a captured event becomes a
// running task within about a second regardless of poll_interval or forge
@@ -267,7 +272,7 @@ func (b *TaskBus) emitTaskQueued(ctx context.Context, task *workflow.Task) {
Issue: task.IssueNumber, Detail: task.Title, Attempt: task.Attempt,
ActorID: task.Identity, PrincipalID: task.Identity,
}
if value, err := b.identities.Get(ctx, identity.IdentityID(task.Identity)); err == nil {
if value, err := b.identities.Lookup(ctx, identity.IdentityID(task.Identity)); err == nil {
e.ActorKind = string(value.Kind)
}
b.emit(ctx, e)
+16 -24
View File
@@ -24,6 +24,9 @@ import (
// them then never reaches a nil branch in the code under test. A test that
// does exercise one sets its own fake.
func wired(d *Daemon) *Daemon {
if d.Log == nil {
d.Log = slog.New(slog.DiscardHandler)
}
if d.TaskTransport == nil {
d.TaskTransport = neutralTaskTransport{}
}
@@ -42,20 +45,9 @@ func wired(d *Daemon) *Daemon {
if d.TaskInstructions == nil {
d.TaskInstructions = neutralTaskConfig{}
}
if d.Access == nil {
d.Access = allowAll{}
}
if d.Principals == nil {
d.Principals = neutralPrincipals{}
}
if d.Denials == nil {
d.Denials = neutralDenials{}
}
if d.IdentityRepository == nil {
d.IdentityRepository = neutralIdentities{}
}
if d.AgentAssignments == nil {
d.AgentAssignments = neutralAssignments{}
if d.Identity == nil {
lister, _ := d.Store.(access.WorkspaceLister)
d.Identity = NewIdentityGate(neutralIdentities{}, neutralAssignments{}, allowAll{}, neutralPrincipals{}, neutralDenials{}, defaultOrgPrincipals, lister, d.Log)
}
if d.PackageAuthorities == nil {
d.PackageAuthorities = neutralAuthorities{}
@@ -69,9 +61,6 @@ func wired(d *Daemon) *Daemon {
if d.AgentStatus == nil {
d.AgentStatus = &AgentStatus{}
}
if d.Log == nil {
d.Log = slog.New(slog.DiscardHandler)
}
if d.Cfg == nil {
d.Cfg = config.NewHolder(config.Config{})
}
@@ -80,22 +69,25 @@ func wired(d *Daemon) *Daemon {
Store: d.Store, Mappings: neutralMappings{}, Bindings: neutralBindings{},
Dispatcher: neutralDispatcher{}, Matches: neutralMatches{}, Creator: neutralCreator{},
Enablement: neutralEnablement{}, Definitions: d.WorkflowDefinitions,
Access: d.Access, Denials: d.Denials, Cfg: d.Cfg, Orgs: d,
OrgPrincipals: func(context.Context) []access.Principal {
return []access.Principal{{Org: org.DefaultOrgID}}
},
Log: d.Log,
Access: d.Identity, Denials: d.Identity, Cfg: d.Cfg, Orgs: d.Identity,
OrgPrincipals: defaultOrgPrincipals,
Log: d.Log,
})
}
d.WireTaskBus()
d.IssuePoller = NewIssuePoller(d.Cfg, d.Store, d.Log,
func(context.Context) []IssueSource { return nil },
func(context.Context, int64, string) error { return nil },
d.TaskBus.PublishTask, d, d.BindingDispatch)
d.ReviewScanner = NewReviewScanner(d.Store, neutralReactions{}, d.TaskTransport.PublishUnique, d.Bus, d, d, d, d.Log)
d.TaskBus.PublishTask, d.Identity, d.BindingDispatch)
d.ReviewScanner = NewReviewScanner(d.Store, neutralReactions{}, d.TaskTransport.PublishUnique, d.Bus, d, d.Identity, d, d.Log)
return d
}
// defaultOrgPrincipals is the one acting principal of the default org.
func defaultOrgPrincipals(context.Context) []access.Principal {
return []access.Principal{{Org: org.DefaultOrgID}}
}
// neutralMappings resolves no mapping, so a binding never reaches a capture.
type neutralMappings struct{ storecontract.MappingStore }
+15 -15
View File
@@ -38,16 +38,16 @@ func (d *Daemon) adoptWorkflowIdentity(ctx context.Context, task *workflow.Task)
d.parkBlockedTask(ctx, task, "workflow "+task.Workflow+" declares no identity to run as; set one in its settings", taskstate.ParkNeedsDecision, taskstate.BlockerWorkflowIdentity)
return false
}
runsAs, runnerName, err := d.declaredIdentity(ctx, task, iface.Identity)
runsAs, runnerName, err := d.Identity.declaredIdentity(ctx, task, iface.Identity)
if err != nil {
d.parkBlockedTask(ctx, task, "workflow "+task.Workflow+": "+err.Error(), pinParkClass(err), parkBlocker(err))
return false
}
if allowed, err := d.mayRunWorkflow(ctx, task, identity.IdentityID(task.Identity)); !allowed {
if allowed, err := d.Identity.mayRunWorkflow(ctx, task, identity.IdentityID(task.Identity)); !allowed {
d.parkRefusedRun(ctx, task, "the identity that started it may not run workflow "+task.Workflow, err)
return false
}
if allowed, err := d.mayRunWorkflow(ctx, task, runsAs); !allowed {
if allowed, err := d.Identity.mayRunWorkflow(ctx, task, runsAs); !allowed {
d.parkRefusedRun(ctx, task, "identity "+iface.Identity+" may not run workflow "+task.Workflow, err)
return false
}
@@ -59,16 +59,16 @@ func (d *Daemon) adoptWorkflowIdentity(ctx context.Context, task *workflow.Task)
// declaredIdentity resolves a workflow's declared identity to the ID it is
// authorized as and the name the task carries while it runs.
func (d *Daemon) declaredIdentity(ctx context.Context, task *workflow.Task, ref string) (identity.IdentityID, string, error) {
value, err := d.databaseExecutionIdentity(ctx, task, identity.IdentityID(ref))
func (g *IdentityGate) declaredIdentity(ctx context.Context, task *workflow.Task, ref string) (identity.IdentityID, string, error) {
value, err := g.databaseExecutionIdentity(ctx, task, identity.IdentityID(ref))
if err != nil {
return "", "", err
}
return value.ID, string(value.ID), nil
}
func (d *Daemon) databaseExecutionIdentity(ctx context.Context, task *workflow.Task, id identity.IdentityID) (identity.Identity, error) {
value, err := d.IdentityRepository.Get(ctx, id)
func (g *IdentityGate) databaseExecutionIdentity(ctx context.Context, task *workflow.Task, id identity.IdentityID) (identity.Identity, error) {
value, err := g.identities.Get(ctx, id)
if err != nil {
failure := pinFailure{taskstate.ParkTransient, fmt.Errorf("resolve execution identity %s: %w", id, err)}
if errors.Is(err, identity.ErrNotFound) {
@@ -81,14 +81,14 @@ func (d *Daemon) databaseExecutionIdentity(ctx context.Context, task *workflow.T
return identity.Identity{}, blockedPark{taskstate.BlockerAgentAssignment, pinFailure{taskstate.ParkNeedsDecision, fmt.Errorf("execution identity %s must be an active bot or service account", id)}}
}
owner := org.OrgID(task.OrgOrDefault())
principal, err := d.Principals.PrincipalFor(ctx, value.ID)
principal, err := g.principals.PrincipalFor(ctx, value.ID)
if err != nil {
return identity.Identity{}, pinFailure{taskstate.ParkTransient, fmt.Errorf("resolve execution principal: %w", err)}
}
if principal.Org != owner {
return identity.Identity{}, blockedPark{taskstate.BlockerAgentAssignment, pinFailure{taskstate.ParkNeedsDecision, fmt.Errorf("execution identity belongs to another organisation")}}
}
assignments, err := d.AgentAssignments.ListOrgAgents(access.WithPrincipal(ctx, principal), owner)
assignments, err := g.assignments.ListOrgAgents(access.WithPrincipal(ctx, principal), owner)
if err != nil {
return identity.Identity{}, pinFailure{taskstate.ParkTransient, fmt.Errorf("resolve execution identity assignment: %w", err)}
}
@@ -102,17 +102,17 @@ func (d *Daemon) databaseExecutionIdentity(ctx context.Context, task *workflow.T
// workflow, recording a denial. No chain allows it, as every other check on
// an install that has not built one. The error reports a chain that could not
// be consulted, which is not a denial: nothing was evaluated.
func (d *Daemon) mayRunWorkflow(ctx context.Context, task *workflow.Task, id identity.IdentityID) (bool, error) {
principal, err := d.principalIn(ctx, id, task.Org)
func (g *IdentityGate) mayRunWorkflow(ctx context.Context, task *workflow.Task, id identity.IdentityID) (bool, error) {
principal, err := g.principalIn(ctx, id, task.Org)
if err != nil {
d.Log.WarnContext(ctx, "workflow identity: principal unavailable", "task", task.ID, "identity", id, "err", err)
g.log.WarnContext(ctx, "workflow identity: principal unavailable", "task", task.ID, "identity", id, "err", err)
return false, nil
}
resource := access.Resource{Kind: access.KindWorkflow, ID: task.Workflow, Org: task.Org, Workspace: task.Workspace}
if resource.Org == "" {
resource.Org = principal.Org
}
decision := d.Access.Authorize(ctx, principal, access.ActionRun, resource, access.Context{Signature: task.BindingSignature, Addr: task.BindingAddr})
decision := g.authorizer.Authorize(ctx, principal, access.ActionRun, resource, access.Context{Signature: task.BindingSignature, Addr: task.BindingAddr})
if decision.Allowed {
return true, nil
}
@@ -125,8 +125,8 @@ func (d *Daemon) mayRunWorkflow(ctx context.Context, task *workflow.Task, id ide
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.WarnContext(ctx, "workflow identity: record denial", "task", task.ID, "err", err)
if err := g.denials.RecordDenial(ctx, denial); err != nil {
g.log.WarnContext(ctx, "workflow identity: record denial", "task", task.ID, "err", err)
}
return false, nil
}
+3 -6
View File
@@ -131,8 +131,7 @@ func TestWorkflowIdentity(t *testing.T) {
var denied denials
d := wired(&Daemon{
Store: store, Log: slog.New(slog.DiscardHandler),
Access: tt.allowed, Principals: principalOf{}, Denials: &denied,
IdentityRepository: agentDirectory{}, AgentAssignments: agentDirectory{},
Identity: NewIdentityGate(agentDirectory{}, agentDirectory{}, tt.allowed, principalOf{}, &denied, nil, nil, slog.New(slog.DiscardHandler)),
})
if tt.disabled {
d.BindingDispatch.enablement = enablementOf(workflowtask.WorkflowEnablement{}.SetEnabled("", "deploy", false))
@@ -179,8 +178,7 @@ func TestWorkflowRunCarriesEventContext(t *testing.T) {
t.Run(tt.signature, func(t *testing.T) {
d := wired(&Daemon{
Store: &identityStore{}, Log: slog.New(slog.DiscardHandler),
Access: signedOnly{runAllowed{sys: true, "id-deployer": true}},
Principals: principalOf{}, IdentityRepository: agentDirectory{}, AgentAssignments: agentDirectory{},
Identity: NewIdentityGate(agentDirectory{}, agentDirectory{}, signedOnly{runAllowed{sys: true, "id-deployer": true}}, principalOf{}, neutralDenials{}, nil, nil, slog.New(slog.DiscardHandler)),
})
task := &workflow.Task{
ID: 1, Identity: string(sys), Workflow: "deploy", BindingSignature: tt.signature,
@@ -238,8 +236,7 @@ func TestDashboardExecutionIdentity(t *testing.T) {
cfg := config.Config{BotUser: "root-bot", GrantedCredentials: []string{"root-secret"}, Forge: config.Forge{Token: config.SecretRef{Engine: "env", Key: "ROOT"}}, Repos: []config.Repo{{Owner: "acme", Name: "app"}}}
d := wired(&Daemon{
Store: store, Log: slog.New(slog.DiscardHandler), Cfg: config.NewHolder(cfg),
IdentityRepository: repository, AgentAssignments: assignedAgents{{IdentityID: value.ID, OrgID: tt.assigned}},
Principals: workflowPrincipals{sys: "org-sys", "dashboard-agent": "org-sys"}, Access: runAllowed{sys: true, "dashboard-agent": true},
Identity: NewIdentityGate(repository, assignedAgents{{IdentityID: value.ID, OrgID: tt.assigned}}, runAllowed{sys: true, "dashboard-agent": true}, workflowPrincipals{sys: "org-sys", "dashboard-agent": "org-sys"}, neutralDenials{}, nil, nil, slog.New(slog.DiscardHandler)),
})
definition := "id: deploy\nidentity: dashboard-agent\nrepository: none\n"
newTask := func() *workflow.Task {
+5 -6
View File
@@ -13,12 +13,12 @@ import (
// workflowContext forwards a task's identity so the State Store selects its
// org's definitions. An identity assigned elsewhere cannot supply the pin.
func (d *Daemon) workflowContext(ctx context.Context, task *workflow.Task) (context.Context, error) {
func (g *IdentityGate) workflowContext(ctx context.Context, task *workflow.Task) (context.Context, error) {
owner := task.Org
if owner == "" {
owner = org.DefaultOrgID
}
principal, err := d.principalIn(ctx, identity.IdentityID(task.Identity), owner)
principal, err := g.principalIn(ctx, identity.IdentityID(task.Identity), owner)
if err != nil {
return nil, pinFailure{taskstate.ParkTransient, fmt.Errorf("workflow principal: %w", err)}
}
@@ -31,8 +31,8 @@ func (d *Daemon) workflowContext(ctx context.Context, task *workflow.Task) (cont
// principalIn is id's principal acting in owner: the org it serves, or one it
// is a member of, since a person's task belongs to the org they selected. An
// identity that is no member keeps its own org, which callers refuse.
func (d *Daemon) principalIn(ctx context.Context, id identity.IdentityID, owner org.OrgID) (access.Principal, error) {
principal, err := d.Principals.PrincipalFor(ctx, id)
func (g *IdentityGate) principalIn(ctx context.Context, id identity.IdentityID, owner org.OrgID) (access.Principal, error) {
principal, err := g.principals.PrincipalFor(ctx, id)
if err != nil {
return access.Principal{}, err
}
@@ -42,6 +42,5 @@ func (d *Daemon) principalIn(ctx context.Context, id identity.IdentityID, owner
if principal.Org == owner || !principal.Member(owner) {
return principal, nil
}
lister, _ := d.Store.(access.WorkspaceLister)
return principal.Select(org.WithOrg(access.WithPrincipal(ctx, principal), principal.Org), owner, lister)
return principal.Select(org.WithOrg(access.WithPrincipal(ctx, principal), principal.Org), owner, g.workspaces)
}
+3 -2
View File
@@ -88,7 +88,7 @@ func TestDispatchOrgWorkflows(t *testing.T) {
{ID: "root", MappingID: "root", Matcher: binding.Matcher{Source: "root"}, OrgID: org.DefaultOrgID, Workflow: "deploy", Status: binding.StatusArmed, Owner: "owner", Repo: "repo"},
{ID: "acme", MappingID: "acme", Matcher: binding.Matcher{Source: "acme"}, OrgID: "acme", Workflow: "deploy", Status: binding.StatusArmed},
}}
d := wired(&Daemon{Cfg: config.NewHolder(config.Config{}), Store: store, Log: slog.New(slog.DiscardHandler), Principals: workflowPrincipals{sys: org.DefaultOrgID, "acme-bot": "acme"}, WorkflowDefinitions: orgDefinitions{
d := wired(&Daemon{Cfg: config.NewHolder(config.Config{}), Store: store, Log: slog.New(slog.DiscardHandler), Identity: NewIdentityGate(neutralIdentities{}, neutralAssignments{}, allowAll{}, workflowPrincipals{sys: org.DefaultOrgID, "acme-bot": "acme"}, neutralDenials{}, nil, nil, slog.New(slog.DiscardHandler)), WorkflowDefinitions: orgDefinitions{
org.DefaultOrgID: "id: deploy\nrepository: required\nsteps:\n - type: workflow.finish\n",
"acme": "id: deploy\nrepository: none\nsteps:\n - type: workflow.finish\n",
}})
@@ -145,7 +145,8 @@ func TestPinWorkflowInTaskOrg(t *testing.T) {
{"a non-member cannot start a task in another org", "acme", memberOf{home: org.DefaultOrgID, other: "beta"}, "", true},
} {
t.Run(tc.name, func(t *testing.T) {
d := wired(&Daemon{Store: listsWorkspaces{&identityStore{}}, Principals: tc.principals, WorkflowDefinitions: orgDefinitions{org.DefaultOrgID: shared, "acme": custom}})
store := listsWorkspaces{&identityStore{}}
d := wired(&Daemon{Store: store, Identity: NewIdentityGate(neutralIdentities{}, neutralAssignments{}, allowAll{}, tc.principals, neutralDenials{}, nil, store, slog.New(slog.DiscardHandler)), WorkflowDefinitions: orgDefinitions{org.DefaultOrgID: shared, "acme": custom}})
task := &workflow.Task{ID: 1, Identity: "bot", Org: tc.owner, Workflow: "deploy"}
err := d.pinWorkflowDefinition(t.Context(), task)
if tc.refused {