Files
archie/internal/daemon/workflow_identity_test.go

283 lines
12 KiB
Go

package daemon
import (
"context"
"errors"
"log/slog"
"reflect"
"testing"
"github.com/samcharles93/archie-core/internal/config"
"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/domain/storecontract"
"github.com/samcharles93/archie-core/internal/domain/workflow"
workflowtask "github.com/samcharles93/archie-core/internal/domain/workflow/task"
"github.com/samcharles93/archie-core/internal/taskstate"
)
type identityStore struct {
storecontract.TaskStore
parked bool
class taskstate.ParkClass
}
func (*identityStore) Update(context.Context, *workflow.Task) error { return nil }
func (s *identityStore) ParkTask(_ context.Context, _ int64, _, _ string, class taskstate.ParkClass, _ taskstate.Blocker) error {
s.parked = true
s.class = class
return nil
}
type principalOf struct{}
func (principalOf) PrincipalFor(_ context.Context, id identity.IdentityID) (access.Principal, error) {
return access.Principal{IdentityID: id, Org: org.DefaultOrgID}, nil
}
const sys = identity.SystemID
// agentDirectory knows each agent by name and by ID, all assigned to the
// system org.
type agentDirectory struct{ identity.Repository }
var directoryAgents = map[identity.IdentityID]identity.IdentityID{
"deployer": "id-deployer", "id-deployer": "id-deployer", "bot": "id-bot", "id-bot": "id-bot",
}
func (agentDirectory) Get(_ context.Context, ref identity.IdentityID) (identity.Identity, error) {
id, ok := directoryAgents[ref]
if !ok {
return identity.Identity{}, identity.ErrNotFound
}
return identity.Identity{ID: id, Kind: identity.KindBot, Lifecycle: identity.LifecycleActive}, nil
}
func (agentDirectory) ListOrgAgents(_ context.Context, owner org.OrgID) ([]org.AgentAssignment, error) {
var out []org.AgentAssignment
for _, id := range directoryAgents {
out = append(out, org.AgentAssignment{IdentityID: id, OrgID: owner})
}
return out, nil
}
// runAllowed permits run only to the identities it lists.
type runAllowed map[identity.IdentityID]bool
func (r runAllowed) Authorize(_ context.Context, p access.Principal, _ access.Action, _ access.Resource, _ access.Context) access.Decision {
if r[p.IdentityID] {
return access.Allowed()
}
return access.DeniedAt(access.LevelOrg, nil)
}
func (runAllowed) Reload(context.Context) error { return nil }
// unavailableChain is a chain that cannot be read: nothing is evaluated.
type unavailableChain struct{ runAllowed }
func (unavailableChain) Authorize(context.Context, access.Principal, access.Action, access.Resource, access.Context) access.Decision {
return access.Unavailable()
}
type enablementOf workflowtask.WorkflowEnablement
func (e enablementOf) WorkflowEnablement(context.Context) (workflowtask.WorkflowEnablement, error) {
return workflowtask.WorkflowEnablement(e), nil
}
// denials records the principals refused.
type denials []identity.IdentityID
func (d *denials) RecordDenial(_ context.Context, denial access.Denial) error {
*d = append(*d, denial.Principal)
return nil
}
// TestWorkflowIdentity pins that a run acts as the identity its workflow
// declares only when both the identity that started it and the declared one
// may run the workflow, that a refusal is recorded, and that a workflow
// naming no identity is refused rather than inheriting one. A called
// workflow is started by its caller's declared identity and runs as its own.
func TestWorkflowIdentity(t *testing.T) {
const deploy = "id: deploy\nidentity: deployer\n"
const callee = "id: deploy\nidentity: bot\n"
tests := []struct {
name string
yaml string
starter string
allowed access.Authorizer
wantIdentity string
wantParked bool
wantClass taskstate.ParkClass
wantDenied []identity.IdentityID
disabled bool
}{
{"allowed dispatch runs as the workflow's identity", deploy, string(sys), runAllowed{sys: true, "id-deployer": true}, "id-deployer", false, "", nil, false},
{"refused invocation is parked", deploy, string(sys), runAllowed{"id-deployer": true}, "", true, taskstate.ParkNeedsDecision, []identity.IdentityID{sys}, false},
{"refused execution is parked", deploy, string(sys), runAllowed{sys: true}, "", true, taskstate.ParkNeedsDecision, []identity.IdentityID{"id-deployer"}, false},
{"a chain that cannot be read parks transient, not as a denial", deploy, "", unavailableChain{}, "", true, taskstate.ParkTransient, nil, false},
{"called workflow runs as its own identity, not its caller's", callee, "id-deployer", runAllowed{"id-deployer": true, "id-bot": true}, "id-bot", false, "", nil, false},
{"caller refused the called workflow is parked", callee, "id-deployer", runAllowed{"id-bot": true}, "", true, taskstate.ParkNeedsDecision, []identity.IdentityID{"id-deployer"}, false},
{"no declared identity is refused", "id: deploy\n", "id-bot", runAllowed{sys: true, "id-bot": true}, "", true, taskstate.ParkNeedsDecision, nil, false},
{"unconfigured identity is parked", "id: deploy\nidentity: ghost\n", string(sys), runAllowed{sys: true}, "", true, taskstate.ParkNeedsDecision, nil, false},
{"disabled workflow is parked", deploy, "id-bot", runAllowed{"id-bot": true, "id-deployer": true}, "", true, taskstate.ParkNeedsDecision, nil, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
store := &identityStore{}
var denied denials
d := wired(&Daemon{
Store: store, Log: slog.New(slog.DiscardHandler),
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))
}
task := &workflow.Task{
ID: 1, Identity: tt.starter, Workflow: "deploy",
WorkflowDefinitionYAML: tt.yaml, WorkflowDefinitionDigest: workflow.DigestDefinition(tt.yaml),
}
ok := d.adoptWorkflowIdentity(context.Background(), task)
if ok == tt.wantParked || store.parked != tt.wantParked || (ok && task.Identity != tt.wantIdentity) {
t.Fatalf("ok %v parked %v identity %q, want parked %v identity %q", ok, store.parked, task.Identity, tt.wantParked, tt.wantIdentity)
}
if store.parked && store.class != tt.wantClass {
t.Fatalf("parked %q, want %q", store.class, tt.wantClass)
}
if !reflect.DeepEqual([]identity.IdentityID(denied), tt.wantDenied) {
t.Fatalf("denied %v, want %v", denied, tt.wantDenied)
}
})
}
}
// signedOnly permits run only for a verified signature, as a policy
// conditioned on context.signature does.
type signedOnly struct{ runAllowed }
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" {
return access.DeniedAt(access.LevelOrg, nil)
}
return s.runAllowed.Authorize(ctx, p, a, r, c)
}
// TestWorkflowRunCarriesEventContext pins that the run-time re-check sees the
// signature the binding's capture carried, so a signature-conditioned policy
// that admitted the dispatch admits the task, and an unsigned event stays
// refused.
func TestWorkflowRunCarriesEventContext(t *testing.T) {
const deploy = "id: deploy\nidentity: deployer\n"
for _, tt := range []struct {
signature string
want bool
}{{"valid", true}, {"unsigned", false}, {"", false}} {
t.Run(tt.signature, func(t *testing.T) {
d := wired(&Daemon{
Store: &identityStore{}, Log: slog.New(slog.DiscardHandler),
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,
WorkflowDefinitionYAML: deploy, WorkflowDefinitionDigest: workflow.DigestDefinition(deploy),
}
if got := d.adoptWorkflowIdentity(context.Background(), task); got != tt.want {
t.Fatalf("admitted %v, want %v", got, tt.want)
}
})
}
}
type dashboardIdentities struct {
identity.Repository
value identity.Identity
err error
}
func (r *dashboardIdentities) Get(_ context.Context, id identity.IdentityID) (identity.Identity, error) {
if r.err != nil {
return identity.Identity{}, r.err
}
if id != r.value.ID {
return identity.Identity{}, identity.ErrNotFound
}
return r.value, nil
}
func TestDashboardExecutionIdentity(t *testing.T) {
tests := []struct {
name string
kind identity.Kind
lifecycle identity.Lifecycle
assigned org.OrgID
unavailable bool
denied bool
}{
{"dashboard bot", identity.KindBot, identity.LifecycleActive, "org-sys", false, false},
{"dashboard service account", identity.KindServiceAccount, identity.LifecycleActive, "org-sys", false, false},
{"human", identity.KindUser, identity.LifecycleActive, "org-sys", false, true},
{"suspended", identity.KindBot, identity.LifecycleSuspended, "org-sys", false, true},
{"retired", identity.KindBot, identity.LifecycleRetired, "org-sys", false, true},
{"unassigned", identity.KindBot, identity.LifecycleActive, "", false, true},
{"another org", identity.KindBot, identity.LifecycleActive, "other", false, true},
{"authority unavailable", identity.KindBot, identity.LifecycleActive, "org-sys", true, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
value := identity.Identity{ID: "dashboard-agent", Kind: tt.kind, Lifecycle: tt.lifecycle, DisplayName: "Renamed agent"}
repository := &dashboardIdentities{value: value}
if tt.unavailable {
repository.err = errors.New("offline")
}
store := &identityStore{}
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),
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 {
return &workflow.Task{ID: 1, Identity: string(sys), Workflow: "deploy", WorkflowDefinitionYAML: definition, WorkflowDefinitionDigest: workflow.DigestDefinition(definition)}
}
task := newTask()
ok := d.adoptWorkflowIdentity(context.Background(), task)
if ok == tt.denied || store.parked != tt.denied {
t.Fatalf("admitted %v parked %v, want denied %v", ok, store.parked, tt.denied)
}
if !ok {
return
}
if task.Identity != string(value.ID) {
t.Fatalf("execution identity %q", task.Identity)
}
runtime := d.configFor(task)
if runtime.Forge != (config.Forge{}) || runtime.BotUser != "" || len(runtime.GrantedCredentials) != 0 {
t.Fatal("new agent inherited root credentials")
}
if d.treesFor(task).Token != "" {
t.Fatal("new agent inherited Git token")
}
if _, found := d.repoFor(&workflow.Task{Identity: task.Identity, Owner: "acme", Repo: "app"}); found {
t.Fatal("new agent inherited root repository access")
}
repository.value.Lifecycle = identity.LifecycleSuspended
if d.adoptWorkflowIdentity(context.Background(), newTask()) {
t.Fatal("retry ignored suspension")
}
})
}
}
type assignedAgents []org.AgentAssignment
func (a assignedAgents) ListOrgAgents(ctx context.Context, owner org.OrgID) ([]org.AgentAssignment, error) {
p, ok := access.PrincipalFromContext(ctx)
if !ok || p.Org != owner {
return nil, errors.New("missing organisation principal")
}
return a, nil
}