package approvals import ( "context" "errors" "testing" "time" "github.com/google/uuid" "github.com/samcharles93/archie-core/modules/approvals/internal/store" "github.com/samcharles93/archie-core/modules/governance" "github.com/samcharles93/archie-core/modules/judgement" ) // fakeAccounts holds accounts by id, each with the role the shipped policies // read, and the channel credentials linked to them. type fakeAccounts struct { accounts map[governance.IdentityID]governance.Identity roles map[governance.IdentityID]governance.Role linked map[governance.Subject]governance.IdentityID } func (f fakeAccounts) ResolveSubject(_ context.Context, s governance.Subject) (governance.Identity, error) { id, ok := f.linked[s] if !ok { return governance.Identity{}, governance.ErrIdentityNotFound } return f.accounts[id], nil } func (f fakeAccounts) Get(_ context.Context, id governance.IdentityID) (governance.Identity, error) { account, ok := f.accounts[id] if !ok { return governance.Identity{}, governance.ErrIdentityNotFound } return account, nil } func (f fakeAccounts) PrincipalFor(_ context.Context, id governance.IdentityID) (governance.Principal, error) { return governance.Principal{ IdentityID: id, Org: governance.DefaultOrgID, Memberships: []governance.Membership{{IdentityID: id, OrgID: governance.DefaultOrgID, Role: f.roles[id]}}, }, nil } func newAccounts() fakeAccounts { f := fakeAccounts{ accounts: map[governance.IdentityID]governance.Identity{}, roles: map[governance.IdentityID]governance.Role{}, linked: map[governance.Subject]governance.IdentityID{}, } for id, role := range map[governance.IdentityID]governance.Role{ "admin": governance.RoleAdmin, "owner": governance.RoleOwner, "developer": governance.RoleDeveloper, "viewer": governance.RoleViewer, } { f.accounts[id] = governance.Identity{ID: id, Kind: governance.KindUser, DisplayName: string(id), Lifecycle: governance.LifecycleActive} f.roles[id] = role f.linked[governance.Subject{Issuer: "telegram", Subject: "tg-" + string(id)}] = id } return f } // shipped is the access chain an install starts with: admin and owner may // approve, a developer or viewer may not. func shipped() governance.Authorizer { return governance.NewEngine(governance.ShippedOrgPolicies(governance.DefaultOrgID)) } // approveOnlyForDevelopers grants approve, and nothing about policy, to the // developer role. func approveOnlyForDevelopers() governance.Authorizer { return governance.NewEngine([]governance.Policy{{ ID: "developers-approve", Level: governance.LevelOrg, OrgID: governance.DefaultOrgID, Text: `permit(principal, action == Archie::Action::"approve", resource) when { resource.org == principal.org && principal.role == "developer" };`, }}) } // TestChannelAnswerComesFromALinkedAccountWhoseRoleMayApprove guards the // channel answer path: the channel credential resolves to an account, and // role alone decides whether that account may answer, as for any other // permission. A credential no account has linked is refused. func TestChannelAnswerComesFromALinkedAccountWhoseRoleMayApprove(t *testing.T) { action := func(level string) store.Request { return store.Request{ID: uuid.New(), Kind: KindAction, Level: level} } propose, escalate := judgement.ProposeAndWait.String(), judgement.Escalate.String() suspended := newAccounts() suspended.accounts["admin"] = governance.Identity{ID: "admin", Kind: governance.KindUser, DisplayName: "admin", Lifecycle: governance.LifecycleSuspended} bot := newAccounts() bot.accounts["admin"] = governance.Identity{ID: "admin", Kind: governance.KindBot, DisplayName: "admin", Lifecycle: governance.LifecycleActive} tests := []struct { name string accounts fakeAccounts authz governance.Authorizer who string row store.Request wantName string wantErr error }{ {name: "an admin may approve", accounts: newAccounts(), authz: shipped(), who: "tg-admin", row: action(propose), wantName: "admin"}, {name: "an owner may approve", accounts: newAccounts(), authz: shipped(), who: "tg-owner", row: action(propose), wantName: "owner"}, {name: "an admin may answer an escalated action", accounts: newAccounts(), authz: shipped(), who: "tg-admin", row: action(escalate), wantName: "admin"}, {name: "an admin may answer an autonomy proposal", accounts: newAccounts(), authz: shipped(), who: "tg-admin", row: store.Request{ID: uuid.New(), Kind: KindAutonomy}, wantName: "admin"}, {name: "a developer may not approve", accounts: newAccounts(), authz: shipped(), who: "tg-developer", row: action(propose), wantErr: ErrNotApprover}, {name: "a viewer may not approve", accounts: newAccounts(), authz: shipped(), who: "tg-viewer", row: action(propose), wantErr: ErrNotApprover}, {name: "a channel account no account has linked is refused", accounts: newAccounts(), authz: shipped(), who: "tg-stranger", row: action(propose), wantErr: ErrUnlinked}, {name: "an unlinked channel account can't answer an autonomy proposal", accounts: newAccounts(), authz: shipped(), who: "tg-stranger", row: store.Request{Kind: KindAutonomy}, wantErr: ErrUnlinked}, {name: "a suspended account is refused", accounts: suspended, authz: shipped(), who: "tg-admin", row: action(propose), wantErr: ErrNotApprover}, {name: "a bot is refused", accounts: bot, authz: shipped(), who: "tg-admin", row: action(propose), wantErr: ErrNotApprover}, {name: "nobody may approve before access policies are attached", accounts: newAccounts(), who: "tg-admin", row: action(propose), wantErr: ErrNotApprover}, {name: "a policy can grant approve to a role", accounts: newAccounts(), authz: approveOnlyForDevelopers(), who: "tg-developer", row: action(propose), wantName: "developer"}, {name: "approve alone does not answer an escalated action", accounts: newAccounts(), authz: approveOnlyForDevelopers(), who: "tg-developer", row: action(escalate), wantErr: ErrNotApprover}, {name: "approve alone does not answer an autonomy proposal", accounts: newAccounts(), authz: approveOnlyForDevelopers(), who: "tg-developer", row: store.Request{ID: uuid.New(), Kind: KindAutonomy}, wantErr: ErrNotApprover}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { m := &Module{accounts: tt.accounts, authz: tt.authz} who, err := m.channelAnswerer(context.Background(), governance.Subject{Issuer: "telegram", Subject: tt.who}, tt.row) if !errors.Is(err, tt.wantErr) { t.Fatalf("err = %v, want %v", err, tt.wantErr) } if who.Name != tt.wantName { t.Fatalf("name = %q, want %q", who.Name, tt.wantName) } if tt.wantErr != nil && !refusal(err) { t.Fatalf("%v isn't recorded as a refusal", err) } }) } } // TestSettleableRefusesASecondAnswerOrALateOne checks that a settled request or // one at its deadline cannot accept a response. func TestSettleableRefusesASecondAnswerOrALateOne(t *testing.T) { deadline := time.Date(2026, 11, 16, 12, 0, 0, 0, time.UTC) request := func(state string) store.Request { return store.Request{State: state, Deadline: deadline} } tests := []struct { name string row store.Request now time.Time wantErr error }{ {name: "a pending request accepts a response before the deadline", row: request(StatePending), now: deadline.Add(-time.Minute)}, {name: "a pending request rejects a response at the deadline", row: request(StatePending), now: deadline, wantErr: ErrExpired}, {name: "an approved request doesn't settle again", row: request(StateApproved), now: deadline.Add(-time.Minute), wantErr: ErrAnswered}, {name: "a denied request doesn't settle again", row: request(StateDenied), now: deadline.Add(-time.Minute), wantErr: ErrAnswered}, {name: "an expired request doesn't settle", row: request(StateExpired), now: deadline.Add(-time.Minute), wantErr: ErrAnswered}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if err := settleable(tt.row, tt.now); !errors.Is(err, tt.wantErr) { t.Fatalf("err = %v, want %v", err, tt.wantErr) } }) } } // TestAnswerersWithTheSameNameRecordDifferentIDs guards the approver record: // display names are not unique, so an answer must carry the account's // identity ID for the trail and audit record to distinguish two accounts. func TestAnswerersWithTheSameNameRecordDifferentIDs(t *testing.T) { accounts := newAccounts() for _, id := range []governance.IdentityID{"admin", "owner"} { a := accounts.accounts[id] a.DisplayName = "Alex" accounts.accounts[id] = a } m := &Module{accounts: accounts, authz: shipped()} row := store.Request{ID: uuid.New(), Kind: KindAction, Level: judgement.ProposeAndWait.String()} tests := []struct { name string who string wantID string }{ {name: "the first account records its own id", who: "tg-admin", wantID: "admin"}, {name: "the second account with the same name records its own id", who: "tg-owner", wantID: "owner"}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { who, err := m.channelAnswerer(context.Background(), governance.Subject{Issuer: "telegram", Subject: tt.who}, row) if err != nil { t.Fatal(err) } if who.Name != "Alex" || who.ID != tt.wantID { t.Fatalf("answerer = %+v, want name Alex and id %q", who, tt.wantID) } answer := Answer{By: who.Name, ByID: who.ID} if got := answer.Approval(judgement.Decision{}).ByID; got != tt.wantID { t.Fatalf("approval records id %q, want %q", got, tt.wantID) } }) } } // TestCoversStillBindsARequestRecordedBeforeItListedItsActions guards a request // made before requests carried the actions they cover: the decision and digest // it records on its own still bind it to that action and no other, so an // existing run keeps its approval. func TestCoversStillBindsARequestRecordedBeforeItListedItsActions(t *testing.T) { decision := func(id uuid.UUID, digest string) judgement.Decision { return judgement.Decision{ID: id, Action: judgement.Action{Digest: digest}} } approved := decision(uuid.New(), "abc") request := Request{DecisionID: approved.ID, Digest: "abc"} tests := []struct { name string d judgement.Decision want bool }{ {name: "the action it approved is covered", d: approved, want: true}, {name: "the same action with a new digest is not covered", d: decision(approved.ID, "def")}, {name: "another action is not covered", d: decision(uuid.New(), "abc")}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := request.Covers(tt.d); got != tt.want { t.Fatalf("Covers = %t, want %t", got, tt.want) } }) } }