diff --git a/internal/plan.go b/internal/plan.go new file mode 100644 index 0000000..7e711eb --- /dev/null +++ b/internal/plan.go @@ -0,0 +1,257 @@ +package internal + +import ( + "context" + "fmt" + "sort" + "strings" +) + +// maxListed caps the names listed per change in a message, so it stays one readable line. +const maxListed = 10 + +// State is what the plugin read from the repository: only what the enabled remediations need. +type State struct { + Repo *repository + Collaborators []user // with Remediations.DirectCollaborators + Invitations []invitation // with Remediations.DirectCollaborators.Invitations +} + +// Plan is the changes the enabled remediations need, kept in refs as last_plan. +type Plan struct { + Mode string `json:"mode"` + Repository string `json:"repository"` + // RemoveCollaborators are the direct collaborators to remove, sorted case-insensitively. + RemoveCollaborators []string `json:"remove_collaborators,omitempty"` + // CancelInvitations are the pending invitations to delete. + CancelInvitations []PlannedInvitation `json:"cancel_invitations,omitempty"` + // WebCommitSignoff is the value to set, when it differs. + WebCommitSignoff string `json:"web_commit_signoff,omitempty"` + // Kept are the direct collaborators left in place because Keep lists them (or they own + // the repository). + Kept []string `json:"kept,omitempty"` +} + +// PlannedInvitation is an invitation to cancel. +type PlannedInvitation struct { + ID int64 `json:"id"` + Login string `json:"login"` // the invitee, or the email, or "#" +} + +// Empty reports whether nothing needs to change. +func (p *Plan) Empty() bool { + return len(p.RemoveCollaborators) == 0 && len(p.CancelInvitations) == 0 && p.WebCommitSignoff == "" +} + +// read reads the state the enabled remediations need. The repository is always read: it +// checks access first, and gives its owner and settings page. +func read(ctx context.Context, c *githubClient, r Repo, p *Params) (*State, error) { + repo, err := c.getRepository(ctx, r) + if err != nil { + return nil, err + } + st := &State{Repo: repo} + dc := p.Remediations.DirectCollaborators + if dc.Enabled { + if st.Collaborators, err = c.listDirectCollaborators(ctx, r); err != nil { + return nil, err + } + if dc.Invitations { + if st.Invitations, err = c.listInvitations(ctx, r); err != nil { + return nil, err + } + } + } + return st, nil +} + +// ComputePlan returns the changes that make st match the parameters. The repository's +// owner is never removed (GitHub refuses it, so it would fail every run). +func ComputePlan(r Repo, p *Params, keep *KeepList, st *State) *Plan { + plan := &Plan{Mode: p.Mode, Repository: r.FullName()} + if st.Repo != nil && st.Repo.FullName != "" { + plan.Repository = st.Repo.FullName + } + owner := "" + if st.Repo != nil { + owner = strings.ToLower(st.Repo.Owner.Login) + } + dc := p.Remediations.DirectCollaborators + if dc.Enabled { + for _, u := range st.Collaborators { + if keep.Has(u.Login) || strings.ToLower(u.Login) == owner { + plan.Kept = append(plan.Kept, u.Login) + continue + } + plan.RemoveCollaborators = append(plan.RemoveCollaborators, u.Login) + } + sortFold(plan.RemoveCollaborators) + sortFold(plan.Kept) + if dc.Invitations { + for _, inv := range st.Invitations { + if login := inv.login(); login != "" && keep.Has(login) { + continue + } + plan.CancelInvitations = append(plan.CancelInvitations, PlannedInvitation{ID: inv.ID, Login: invitationLabel(inv)}) + } + sort.SliceStable(plan.CancelInvitations, func(i, j int) bool { + a, b := strings.ToLower(plan.CancelInvitations[i].Login), strings.ToLower(plan.CancelInvitations[j].Login) + if a != b { + return a < b + } + return plan.CancelInvitations[i].ID < plan.CancelInvitations[j].ID + }) + } + } + if ws := p.Remediations.WebCommitSignoff; ws.Enabled && st.Repo != nil { + want := ws.Value == SignoffRequired + if st.Repo.WebCommitSignoffRequired != want { + plan.WebCommitSignoff = ws.Value + } + } + return plan +} + +func invitationLabel(inv invitation) string { + switch { + case inv.login() != "": + return inv.login() + case inv.Email != "": + return inv.Email + } + return fmt.Sprintf("#%d", inv.ID) +} + +func sortFold(s []string) { + sort.SliceStable(s, func(i, j int) bool { return strings.ToLower(s[i]) < strings.ToLower(s[j]) }) +} + +// Done is what an apply changed, in the order it ran. +type Done struct { + RemovedCollaborators []string + CancelledInvitations []string + WebCommitSignoff string +} + +func (d *Done) empty() bool { + return len(d.RemovedCollaborators) == 0 && len(d.CancelledInvitations) == 0 && d.WebCommitSignoff == "" +} + +// execute makes the plan's changes: collaborators, then invitations, then signoff. It stops +// at the first error; what was done before it stays done and is returned. +func execute(ctx context.Context, c *githubClient, r Repo, plan *Plan) (*Done, error) { + done := &Done{} + for _, login := range plan.RemoveCollaborators { + if !loginRE.MatchString(login) { + return done, fmt.Errorf("refusing to remove %q: not a GitHub login", login) + } + if err := c.removeCollaborator(ctx, r, login); err != nil { + return done, err + } + done.RemovedCollaborators = append(done.RemovedCollaborators, login) + } + for _, inv := range plan.CancelInvitations { + if err := c.deleteInvitation(ctx, r, inv.ID); err != nil { + return done, err + } + done.CancelledInvitations = append(done.CancelledInvitations, inv.Login) + } + if plan.WebCommitSignoff != "" { + want := plan.WebCommitSignoff == SignoffRequired + repo, err := c.setWebCommitSignoff(ctx, r, want) + if err != nil { + return done, err + } + if repo.WebCommitSignoffRequired != want { + return done, fmt.Errorf("PATCH %s: GitHub kept web commit signoff %s (an organization policy may enforce it)", + repoPath(r), signoffWord(repo.WebCommitSignoffRequired)) + } + done.WebCommitSignoff = plan.WebCommitSignoff + } + return done, nil +} + +func signoffWord(required bool) string { + if required { + return SignoffRequired + } + return SignoffNotRequired +} + +// Messages. + +const msgCompliant = "compliant: nothing to change" + +// dryRunMessage is "dry-run: would remove 3 direct collaborators (alice, bob, carol), cancel +// 1 invitation (dave), set web commit signoff to required". +func dryRunMessage(plan *Plan) string { + if plan.Empty() { + return msgCompliant + } + var parts []string + if n := len(plan.RemoveCollaborators); n > 0 { + parts = append(parts, fmt.Sprintf("remove %s (%s)", count(n, "direct collaborator"), names(plan.RemoveCollaborators))) + } + if n := len(plan.CancelInvitations); n > 0 { + parts = append(parts, fmt.Sprintf("cancel %s (%s)", count(n, "invitation"), names(invitationLogins(plan.CancelInvitations)))) + } + if plan.WebCommitSignoff != "" { + parts = append(parts, "set web commit signoff to "+plan.WebCommitSignoff) + } + return "dry-run: would " + strings.Join(parts, ", ") +} + +// doneText is "removed 2 direct collaborators (alice, bob), cancelled 1 invitation (dave), +// set web commit signoff to required". +func doneText(d *Done) string { + var parts []string + if n := len(d.RemovedCollaborators); n > 0 { + parts = append(parts, fmt.Sprintf("removed %s (%s)", count(n, "direct collaborator"), names(d.RemovedCollaborators))) + } + if n := len(d.CancelledInvitations); n > 0 { + parts = append(parts, fmt.Sprintf("cancelled %s (%s)", count(n, "invitation"), names(d.CancelledInvitations))) + } + if d.WebCommitSignoff != "" { + parts = append(parts, "set web commit signoff to "+d.WebCommitSignoff) + } + return strings.Join(parts, ", ") +} + +// appliedMessage is "applied: ", or compliant when nothing needed changing. +func appliedMessage(d *Done) string { + if d.empty() { + return msgCompliant + } + return "applied: " + doneText(d) +} + +// failedMessage is the error, then what was changed before it. +func failedMessage(err error, d *Done) string { + msg := err.Error() + if d != nil && !d.empty() { + msg += "; changed before the error: " + doneText(d) + } + return msg +} + +func invitationLogins(invs []PlannedInvitation) []string { + out := make([]string, len(invs)) + for i, inv := range invs { + out[i] = inv.Login + } + return out +} + +func count(n int, noun string) string { + if n == 1 { + return "1 " + noun + } + return fmt.Sprintf("%d %ss", n, noun) +} + +func names(list []string) string { + if len(list) <= maxListed { + return strings.Join(list, ", ") + } + return strings.Join(list[:maxListed], ", ") + fmt.Sprintf(" and %d more", len(list)-maxListed) +} diff --git a/internal/plan_test.go b/internal/plan_test.go new file mode 100644 index 0000000..c0f2f73 --- /dev/null +++ b/internal/plan_test.go @@ -0,0 +1,201 @@ +package internal + +import ( + "errors" + "fmt" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// planRepo has the owner and four other direct collaborators, two invitations, and signoff off. +func planRepo(f *fakeGitHub) { + f.addRepo("acme/repo-1", &fakeRepo{ + collaborators: []string{"carol", "Alice", "acme", "bob", "dependabot-ops"}, + invitations: []fakeInvitation{{id: 9, login: "Dependabot-Ops"}, {id: 7, login: "dave"}, {id: 3, email: "eve@example.com"}}, + }) +} + +func enforcing(mode, keep string, invitations bool, signoff string) *Params { + p := DefaultParams() + p.Mode = mode + p.Remediations.DirectCollaborators = DirectCollaborators{Enabled: true, Keep: keep, Invitations: invitations} + if signoff != "" { + p.Remediations.WebCommitSignoff = WebCommitSignoff{Enabled: true, Value: signoff} + } + return p +} + +func mustKeep(t *testing.T, s string) *KeepList { + t.Helper() + k, err := ParseKeep(s) + require.NoError(t, err) + return k +} + +func readPlan(t *testing.T, f *fakeGitHub, p *Params, keep string) *Plan { + t.Helper() + st, err := read(testCtx(t), newTestClient(t, f.url(), testToken), testRepo, p) + require.NoError(t, err) + return ComputePlan(testRepo, p, mustKeep(t, keep), st) +} + +func TestReadOnlyWhatIsEnforced(t *testing.T) { + f := newFakeGitHub(t) + planRepo(f) + c := newTestClient(t, f.url(), testToken) + + onlySignoff := DefaultParams() + onlySignoff.Remediations.WebCommitSignoff.Enabled = true + _, err := read(testCtx(t), c, testRepo, onlySignoff) + require.NoError(t, err) + assert.Equal(t, []string{"GET /repos/acme/repo-1"}, f.recorded(), "collaborators aren't read when not enforced") + + st, err := read(testCtx(t), c, testRepo, enforcing(ModeApply, "", false, "")) + require.NoError(t, err) + assert.Len(t, st.Collaborators, 5) + assert.Nil(t, st.Invitations) + assert.NotContains(t, f.recorded(), "GET /repos/acme/repo-1/invitations") + + f.failOn("GET /repos/acme/repo-1/invitations", 429, "API rate limit exceeded") + _, err = read(testCtx(t), c, testRepo, enforcing(ModeApply, "", true, "")) + assert.EqualError(t, err, "GET /repos/acme/repo-1/invitations: 429 API rate limit exceeded") +} + +func TestComputePlan(t *testing.T) { + f := newFakeGitHub(t) + planRepo(f) + + plan := readPlan(t, f, enforcing(ModeDryRun, "", true, SignoffRequired), "") + assert.Equal(t, &Plan{ + Mode: ModeDryRun, + Repository: "acme/repo-1", + RemoveCollaborators: []string{"Alice", "bob", "carol", "dependabot-ops"}, + CancelInvitations: []PlannedInvitation{{ID: 7, Login: "dave"}, {ID: 9, Login: "Dependabot-Ops"}, {ID: 3, Login: "eve@example.com"}}, + WebCommitSignoff: SignoffRequired, + Kept: []string{"acme"}, + }, plan, "the owner is never removed; names sort case-insensitively") + assert.False(t, plan.Empty()) + + plan = readPlan(t, f, enforcing(ModeApply, "", true, ""), " ALICE, @dependabot-OPS ") + assert.Equal(t, []string{"bob", "carol"}, plan.RemoveCollaborators) + assert.Equal(t, []string{"acme", "Alice", "dependabot-ops"}, plan.Kept) + assert.Equal(t, []PlannedInvitation{{ID: 7, Login: "dave"}, {ID: 3, Login: "eve@example.com"}}, plan.CancelInvitations, + "an invitation for a kept login stays; an email invitation can't be kept") + assert.Empty(t, plan.WebCommitSignoff, "signoff not enforced") +} + +func TestComputePlanSignoffBothWays(t *testing.T) { + for _, tc := range []struct { + current bool + want string + change string + }{ + {false, SignoffRequired, SignoffRequired}, + {true, SignoffNotRequired, SignoffNotRequired}, + {true, SignoffRequired, ""}, + {false, SignoffNotRequired, ""}, + } { + p := DefaultParams() + p.Remediations.WebCommitSignoff = WebCommitSignoff{Enabled: true, Value: tc.want} + st := &State{Repo: &repository{FullName: "acme/repo-1", WebCommitSignoffRequired: tc.current}} + plan := ComputePlan(testRepo, p, mustKeep(t, ""), st) + assert.Equal(t, tc.change, plan.WebCommitSignoff, "current %v, want %s", tc.current, tc.want) + assert.Equal(t, tc.change == "", plan.Empty()) + } +} + +func TestExecute(t *testing.T) { + f := newFakeGitHub(t) + planRepo(f) + c := newTestClient(t, f.url(), testToken) + plan := readPlan(t, f, enforcing(ModeApply, "dependabot-ops", true, SignoffRequired), "dependabot-ops") + + done, err := execute(testCtx(t), c, testRepo, plan) + require.NoError(t, err) + assert.Equal(t, &Done{ + RemovedCollaborators: []string{"Alice", "bob", "carol"}, + CancelledInvitations: []string{"dave", "eve@example.com"}, + WebCommitSignoff: SignoffRequired, + }, done) + assert.Equal(t, []string{ + "DELETE /repos/acme/repo-1/collaborators/Alice", + "DELETE /repos/acme/repo-1/collaborators/bob", + "DELETE /repos/acme/repo-1/collaborators/carol", + "DELETE /repos/acme/repo-1/invitations/7", + "DELETE /repos/acme/repo-1/invitations/3", + "PATCH /repos/acme/repo-1", + }, f.writes(), "collaborators, then invitations, then signoff") + after := f.repo("acme/repo-1") + assert.ElementsMatch(t, []string{"acme", "dependabot-ops"}, after.collaborators) + assert.Equal(t, []fakeInvitation{{id: 9, login: "Dependabot-Ops"}}, after.invitations) + assert.True(t, after.signoff) + + assert.True(t, readPlan(t, f, enforcing(ModeApply, "", true, SignoffRequired), "dependabot-ops").Empty(), "compliant afterwards") +} + +func TestExecuteStopsAtFirstError(t *testing.T) { + f := newFakeGitHub(t) + planRepo(f) + f.failOn("DELETE /repos/acme/repo-1/collaborators/carol", 403, "Must have admin rights to Repository.") + plan := readPlan(t, f, enforcing(ModeApply, "", true, SignoffRequired), "dependabot-ops") + + done, err := execute(testCtx(t), newTestClient(t, f.url(), testToken), testRepo, plan) + require.Error(t, err) + assert.Equal(t, []string{"Alice", "bob"}, done.RemovedCollaborators, "what was done before the error is returned") + assert.Equal(t, "DELETE /repos/acme/repo-1/collaborators/carol: 403 Must have admin rights to Repository.; changed before the error: removed 2 direct collaborators (Alice, bob)", + failedMessage(err, done)) + assert.Len(t, f.repo("acme/repo-1").invitations, 3, "nothing after the error runs") + assert.False(t, f.repo("acme/repo-1").signoff) +} + +func TestExecuteSignoffKeptByGitHub(t *testing.T) { + f := newFakeGitHub(t) + f.addRepo("acme/repo-1", &fakeRepo{signoff: true}) + f.keepSignoff = true + plan := &Plan{Mode: ModeApply, Repository: "acme/repo-1", WebCommitSignoff: SignoffNotRequired} + + done, err := execute(testCtx(t), newTestClient(t, f.url(), testToken), testRepo, plan) + require.Error(t, err) + assert.Equal(t, "PATCH /repos/acme/repo-1: GitHub kept web commit signoff required (an organization policy may enforce it)", err.Error()) + assert.Empty(t, done.WebCommitSignoff) +} + +func TestExecuteRefusesBadLogin(t *testing.T) { + f := newFakeGitHub(t) + f.addRepo("acme/repo-1", &fakeRepo{}) + plan := &Plan{Mode: ModeApply, Repository: "acme/repo-1", RemoveCollaborators: []string{"../../orgs/acme"}} + + _, err := execute(testCtx(t), newTestClient(t, f.url(), testToken), testRepo, plan) + assert.EqualError(t, err, `refusing to remove "../../orgs/acme": not a GitHub login`) + assert.Empty(t, f.recorded()) +} + +func TestMessages(t *testing.T) { + assert.Equal(t, msgCompliant, dryRunMessage(&Plan{})) + assert.Equal(t, "dry-run: would remove 3 direct collaborators (alice, bob, carol), cancel 1 invitation (dave), set web commit signoff to required", + dryRunMessage(&Plan{ + RemoveCollaborators: []string{"alice", "bob", "carol"}, + CancelInvitations: []PlannedInvitation{{ID: 7, Login: "dave"}}, + WebCommitSignoff: SignoffRequired, + })) + assert.Equal(t, "dry-run: would remove 1 direct collaborator (alice)", dryRunMessage(&Plan{RemoveCollaborators: []string{"alice"}})) + + assert.Equal(t, msgCompliant, appliedMessage(&Done{})) + assert.Equal(t, "applied: removed 2 direct collaborators (alice, bob), cancelled 2 invitations (dave, eve@example.com), set web commit signoff to not-required", + appliedMessage(&Done{ + RemovedCollaborators: []string{"alice", "bob"}, + CancelledInvitations: []string{"dave", "eve@example.com"}, + WebCommitSignoff: SignoffNotRequired, + })) + assert.Equal(t, "boom", failedMessage(errors.New("boom"), &Done{})) + assert.Equal(t, "boom", failedMessage(errors.New("boom"), nil)) + + var many []string + for i := range 25 { + many = append(many, fmt.Sprintf("user-%02d", i)) + } + assert.Equal(t, "applied: removed 25 direct collaborators (user-00, user-01, user-02, user-03, user-04, user-05, user-06, user-07, user-08, user-09 and 15 more)", + appliedMessage(&Done{RemovedCollaborators: many}), "at most maxListed names per change") +}