321 lines
14 KiB
Go
321 lines
14 KiB
Go
package approvals
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"log/slog"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
|
|
"github.com/samcharles93/archie-core/modules/approvals/internal/store"
|
|
"github.com/samcharles93/archie-core/modules/audit"
|
|
"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)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
// TestSoDRefusesSelfApproval guards four-eyes Segregation of Duties:
|
|
// an initiator cannot approve their own SoD-protected request, while
|
|
// another approver or a denial is permitted and refusals classify properly.
|
|
func TestSoDRefusesSelfApproval(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
row store.Request
|
|
who Answerer
|
|
approved bool
|
|
wantErr error
|
|
}{
|
|
{
|
|
name: "same initiator approving SoD request is refused",
|
|
row: store.Request{InitiatorID: "alice", RequireSoD: true},
|
|
who: Answerer{ID: "alice", Name: "Alice"},
|
|
approved: true,
|
|
wantErr: ErrSelfApprovalForbidden,
|
|
},
|
|
{
|
|
name: "different approver approving SoD request succeeds",
|
|
row: store.Request{InitiatorID: "alice", RequireSoD: true},
|
|
who: Answerer{ID: "bob", Name: "Bob"},
|
|
approved: true,
|
|
},
|
|
{
|
|
name: "initiator denying SoD request succeeds",
|
|
row: store.Request{InitiatorID: "alice", RequireSoD: true},
|
|
who: Answerer{ID: "alice", Name: "Alice"},
|
|
approved: false,
|
|
},
|
|
{
|
|
name: "same initiator succeeds when SoD is not required",
|
|
row: store.Request{InitiatorID: "alice", RequireSoD: false},
|
|
who: Answerer{ID: "alice", Name: "Alice"},
|
|
approved: true,
|
|
},
|
|
{
|
|
name: "empty initiator succeeds even when SoD is enabled",
|
|
row: store.Request{InitiatorID: "", RequireSoD: true},
|
|
who: Answerer{ID: "alice", Name: "Alice"},
|
|
approved: true,
|
|
},
|
|
}
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
err := checkSoD(tt.row, tt.who, tt.approved)
|
|
if !errors.Is(err, tt.wantErr) {
|
|
t.Fatalf("checkSoD = %v, want %v", err, tt.wantErr)
|
|
}
|
|
})
|
|
}
|
|
if !refusal(ErrSelfApprovalForbidden) {
|
|
t.Fatal("refusal(ErrSelfApprovalForbidden) = false, want true")
|
|
}
|
|
|
|
userCtx := governance.WithPrincipal(t.Context(), governance.Principal{IdentityID: "alice", Kind: governance.KindUser})
|
|
if got := initiatorOf(userCtx); got != "alice" {
|
|
t.Fatalf("initiatorOf(user) = %q, want alice", got)
|
|
}
|
|
botCtx := governance.WithPrincipal(t.Context(), governance.Principal{IdentityID: "bot-1", Kind: governance.KindBot})
|
|
if got := initiatorOf(botCtx); got != "" {
|
|
t.Fatalf("initiatorOf(bot) = %q, want empty", got)
|
|
}
|
|
if got := initiatorOf(WithInitiator(botCtx, "charlie")); got != "charlie" {
|
|
t.Fatalf("initiatorOf(WithInitiator) = %q, want charlie", got)
|
|
}
|
|
if !requireSoDOf(WithRequireSoD(t.Context(), true), false) {
|
|
t.Fatal("requireSoDOf override true returned false")
|
|
}
|
|
}
|
|
|
|
type recordedAudit []audit.Event
|
|
|
|
func (r *recordedAudit) Record(_ context.Context, e audit.Event) error {
|
|
*r = append(*r, e)
|
|
return nil
|
|
}
|
|
|
|
func TestUseAuditRecordsRefusals(t *testing.T) {
|
|
var rec recordedAudit
|
|
m := &Module{log: slog.New(slog.DiscardHandler)}
|
|
m.UseAudit(&rec)
|
|
audit.Emit(t.Context(), m.audit, m.log, audit.Event{
|
|
Category: "approval", Action: "approval.refuse", ActorID: "alice",
|
|
ResourceKind: "approval", ResourceID: uuid.NewString(), Outcome: "denied",
|
|
})
|
|
if len(rec) != 1 || rec[0].Action != "approval.refuse" || rec[0].Outcome != "denied" {
|
|
t.Fatalf("recorded audit events = %+v", rec)
|
|
}
|
|
}
|