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 } func (*identityStore) Update(context.Context, *workflow.Task) error { return nil } func (s *identityStore) ParkTask(context.Context, int64, string, string, taskstate.ParkClass, taskstate.Blocker) error { s.parked = true 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 } // 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{ "root": "root", "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(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 } 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 runAllowed wantIdentity string wantParked bool wantDenied []identity.IdentityID disabled bool }{ {"allowed dispatch runs as the workflow's identity", deploy, "", runAllowed{"root": true, "id-deployer": true}, "id-deployer", false, nil, false}, {"refused invocation is parked", deploy, "", runAllowed{"id-deployer": true}, "", true, []identity.IdentityID{"root"}, false}, {"refused execution is parked", deploy, "", runAllowed{"root": true}, "", true, []identity.IdentityID{"id-deployer"}, 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, []identity.IdentityID{"id-deployer"}, false}, {"no declared identity is refused", "id: deploy\n", "id-bot", runAllowed{"root": true, "id-bot": true}, "", true, nil, false}, {"unconfigured identity is parked", "id: deploy\nidentity: ghost\n", "", runAllowed{"root": true}, "", true, nil, false}, {"disabled workflow is parked", deploy, "id-bot", runAllowed{"id-bot": true, "id-deployer": true}, "", true, nil, true}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { store := &identityStore{} var denied denials d := &Daemon{ Store: store, Log: slog.New(slog.DiscardHandler), RootIdentityID: "root", Access: tt.allowed, Principals: principalOf{}, Denials: &denied, IdentityRepository: agentDirectory{}, AgentAssignments: agentDirectory{}, } if tt.disabled { d.WorkflowEnablement = 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 !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(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(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 := &Daemon{ Store: &identityStore{}, Log: slog.New(slog.DiscardHandler), RootIdentityID: "root", Access: signedOnly{runAllowed{"root": true, "id-deployer": true}}, Principals: principalOf{}, IdentityRepository: agentDirectory{}, AgentAssignments: agentDirectory{}, } task := &workflow.Task{ ID: 1, 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 := &Daemon{ Store: store, Log: slog.New(slog.DiscardHandler), Cfg: config.NewHolder(cfg), RootIdentityID: "root", IdentityRepository: repository, AgentAssignments: assignedAgents{{IdentityID: value.ID, OrgID: tt.assigned}}, Principals: workflowPrincipals{"root": "org-sys", "dashboard-agent": "org-sys"}, Access: runAllowed{"root": true, "dashboard-agent": true}, } definition := "id: deploy\nidentity: dashboard-agent\nrepository: none\n" newTask := func() *workflow.Task { return &workflow.Task{ID: 1, 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 }