forked from genuinetools/audit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
362 lines (309 loc) · 9.46 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
package main
import (
"context"
"flag"
"fmt"
"net/http"
"os"
"os/signal"
"strings"
"syscall"
"time"
"golang.org/x/oauth2"
"github.com/genuinetools/audit/version"
"github.com/google/go-github/github"
"github.com/sirupsen/logrus"
)
const (
// BANNER is what is printed for help/info output.
BANNER = ` _ _ _
__ _ _ _ __| (_) |_
/ _` + "`" + ` | | | |/ _` + "`" + ` | | __|
| (_| | |_| | (_| | | |_
\__,_|\__,_|\__,_|_|\__|
Auditing what collaborators, hooks, and deploy keys you have added on all your GitHub repositories.
Version: %s
Build: %s
`
)
var (
token string
repo string
debug bool
vrsn bool
owner bool
)
func init() {
// parse flags
flag.StringVar(&token, "token", os.Getenv("GITHUB_TOKEN"), "GitHub API token (or env var GITHUB_TOKEN)")
flag.StringVar(&repo, "repo", "", "specific repo to test (e.g. 'genuinetools/audit')")
flag.BoolVar(&vrsn, "version", false, "print version and exit")
flag.BoolVar(&vrsn, "v", false, "print version and exit (shorthand)")
flag.BoolVar(&debug, "d", false, "run in debug mode")
flag.BoolVar(&owner, "owner", false, "only audit repos the token owner owns")
flag.Usage = func() {
fmt.Fprint(os.Stderr, fmt.Sprintf(BANNER, version.VERSION, version.GITCOMMIT))
flag.PrintDefaults()
}
flag.Parse()
if vrsn {
fmt.Printf("audit version %s, build %s", version.VERSION, version.GITCOMMIT)
os.Exit(0)
}
// set log level
if debug {
logrus.SetLevel(logrus.DebugLevel)
}
if token == "" {
usageAndExit("GitHub token cannot be empty.", 1)
}
}
func main() {
// On ^C, or SIGTERM handle exit.
signals := make(chan os.Signal, 0)
signal.Notify(signals, os.Interrupt)
signal.Notify(signals, syscall.SIGTERM)
ctx, cancel := context.WithCancel(context.Background())
go func() {
for sig := range signals {
cancel()
logrus.Infof("Received %s, exiting.", sig.String())
os.Exit(0)
}
}()
// Create the http client.
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: token},
)
tc := oauth2.NewClient(ctx, ts)
// Create the github client.
client := github.NewClient(tc)
page := 1
perPage := 100
var affiliation string
if owner {
affiliation = "owner"
} else {
affiliation = "owner,collaborator,organization_member"
}
logrus.Debugf("Getting repositories...")
if err := getRepositories(ctx, client, page, perPage, affiliation, repo); err != nil {
if v, ok := err.(*github.RateLimitError); ok {
logrus.Fatalf("%s Limit: %d; Remaining: %d; Retry After: %s", v.Message, v.Rate.Limit, v.Rate.Remaining, time.Until(v.Rate.Reset.Time).String())
}
logrus.Fatal(err)
}
}
func getRepositories(ctx context.Context, client *github.Client, page, perPage int, affiliation string, searchRepo string) error {
opt := &github.RepositoryListOptions{
Affiliation: affiliation,
ListOptions: github.ListOptions{
Page: page,
PerPage: perPage,
},
}
var (
repos []*github.Repository
resp *github.Response
err error
)
if len(searchRepo) < 1 {
// Get all the repos.
repos, resp, err = client.Repositories.List(ctx, "", opt)
if err != nil {
return err
}
} else {
// Find the one repo.
repos, err = searchRepos(ctx, client, searchRepo)
}
if err != nil {
return err
}
for _, repo := range repos {
logrus.Debugf("Handling repo %s...", repo.GetFullName())
if err := handleRepo(ctx, client, repo); err != nil {
if len(searchRepo) > 0 {
return err
}
logrus.Warn(err)
}
}
// Return early if we are on the last page.
if resp == nil || page == resp.LastPage || resp.NextPage == 0 {
return nil
}
page = resp.NextPage
return getRepositories(ctx, client, page, perPage, affiliation, searchRepo)
}
func searchRepos(ctx context.Context, client *github.Client, searchRepo string) ([]*github.Repository, error) {
optSearch := &github.SearchOptions{
Sort: "forks",
Order: "desc",
ListOptions: github.ListOptions{
Page: 1,
PerPage: 1,
},
}
search := strings.SplitN(searchRepo, "/", 2)
repos, _, err := client.Search.Repositories(ctx, fmt.Sprintf("org:%s in:name %s fork:true", search[0], search[1]), optSearch)
if err != nil {
return nil, err
}
if len(repos.Repositories) < 1 {
return nil, fmt.Errorf("found no repositories matching: %s", searchRepo)
}
r := []*github.Repository{}
for _, repo := range repos.Repositories {
r = append(r, &repo)
}
return r, nil
}
// handleRepo will return nil error if the user does not have access to something.
func handleRepo(ctx context.Context, client *github.Client, repo *github.Repository) error {
opt := &github.ListOptions{
PerPage: 100,
}
teams, resp, err := client.Repositories.ListTeams(ctx, repo.GetOwner().GetLogin(), repo.GetName(), opt)
if resp.StatusCode == http.StatusNotFound || resp.StatusCode == http.StatusForbidden || err != nil {
if _, ok := err.(*github.RateLimitError); ok {
return err
}
return nil
}
if err != nil {
return err
}
collabs, resp, err := client.Repositories.ListCollaborators(ctx, repo.GetOwner().GetLogin(), repo.GetName(), &github.ListCollaboratorsOptions{ListOptions: *opt})
if resp.StatusCode == http.StatusNotFound || resp.StatusCode == http.StatusForbidden || err != nil {
if _, ok := err.(*github.RateLimitError); ok {
return err
}
return nil
}
if err != nil {
return err
}
keys, resp, err := client.Repositories.ListKeys(ctx, repo.GetOwner().GetLogin(), repo.GetName(), opt)
if resp.StatusCode == http.StatusNotFound || resp.StatusCode == http.StatusForbidden || err != nil {
if _, ok := err.(*github.RateLimitError); ok {
return err
}
return nil
}
if err != nil {
return err
}
hooks, resp, err := client.Repositories.ListHooks(ctx, repo.GetOwner().GetLogin(), repo.GetName(), opt)
if resp.StatusCode == http.StatusNotFound || resp.StatusCode == http.StatusForbidden || err != nil {
if _, ok := err.(*github.RateLimitError); ok {
return err
}
return nil
}
if err != nil {
return err
}
branches, _, err := client.Repositories.ListBranches(ctx, repo.GetOwner().GetLogin(), repo.GetName(), opt)
if err != nil {
return err
}
protectedBranches := []string{}
unprotectedBranches := []string{}
for _, branch := range branches {
// we must get the individual branch for the branch protection to work
b, _, err := client.Repositories.GetBranch(ctx, repo.GetOwner().GetLogin(), repo.GetName(), branch.GetName())
if err != nil {
return err
}
if b.GetProtected() {
protectedBranches = append(protectedBranches, b.GetName())
} else {
unprotectedBranches = append(unprotectedBranches, b.GetName())
}
}
// only print whole status if we have more that one collaborator
if len(collabs) <= 1 && len(keys) < 1 && len(hooks) < 1 && len(protectedBranches) < 1 && len(unprotectedBranches) < 1 {
return nil
}
output := fmt.Sprintf("%s -> \n", repo.GetFullName())
if len(collabs) > 1 {
push := []string{}
pull := []string{}
admin := []string{}
for _, c := range collabs {
userTeams := []github.Team{}
for _, t := range teams {
isMember, resp, err := client.Organizations.GetTeamMembership(ctx, t.GetID(), c.GetLogin())
if resp.StatusCode != http.StatusNotFound && resp.StatusCode != http.StatusForbidden && err == nil && isMember.GetState() == "active" {
userTeams = append(userTeams, *t)
}
}
perms := c.GetPermissions()
switch {
case perms["admin"]:
permTeams := []string{}
for _, t := range userTeams {
if t.GetPermission() == "admin" {
permTeams = append(permTeams, t.GetName())
}
}
admin = append(admin, fmt.Sprintf("\t\t\t%s (teams: %s)", c.GetLogin(), strings.Join(permTeams, ", ")))
case perms["push"]:
push = append(push, fmt.Sprintf("\t\t\t%s", c.GetLogin()))
case perms["pull"]:
pull = append(pull, fmt.Sprintf("\t\t\t%s", c.GetLogin()))
}
}
output += fmt.Sprintf("\tCollaborators (%d):\n", len(collabs))
output += fmt.Sprintf("\t\tAdmin (%d):\n%s\n", len(admin), strings.Join(admin, "\n"))
output += fmt.Sprintf("\t\tWrite (%d):\n%s\n", len(push), strings.Join(push, "\n"))
output += fmt.Sprintf("\t\tRead (%d):\n%s\n", len(pull), strings.Join(pull, "\n"))
}
if len(keys) > 0 {
kstr := []string{}
for _, k := range keys {
kstr = append(kstr, fmt.Sprintf("\t\t%s - ro:%t (%s)", k.GetTitle(), k.GetReadOnly(), k.GetURL()))
}
output += fmt.Sprintf("\tKeys (%d):\n%s\n", len(kstr), strings.Join(kstr, "\n"))
}
if len(hooks) > 0 {
hstr := []string{}
for _, h := range hooks {
hstr = append(hstr, fmt.Sprintf("\t\t%s - active:%t (%s)", h.GetName(), h.GetActive(), h.GetURL()))
}
output += fmt.Sprintf("\tHooks (%d):\n%s\n", len(hstr), strings.Join(hstr, "\n"))
}
if len(protectedBranches) > 0 {
output += fmt.Sprintf("\tProtected Branches (%d): %s\n", len(protectedBranches), strings.Join(protectedBranches, ", "))
}
if len(unprotectedBranches) > 0 {
output += fmt.Sprintf("\tUnprotected Branches (%d): %s\n", len(unprotectedBranches), strings.Join(unprotectedBranches, ", "))
}
repo, _, err = client.Repositories.Get(ctx, repo.GetOwner().GetLogin(), repo.GetName())
if err != nil {
return err
}
mergeMethods := "\tMerge Methods:"
if repo.GetAllowMergeCommit() {
mergeMethods += " mergeCommit"
}
if repo.GetAllowSquashMerge() {
mergeMethods += " squash"
}
if repo.GetAllowRebaseMerge() {
mergeMethods += " rebase"
}
output += mergeMethods + "\n"
fmt.Printf("%s--\n\n", output)
return nil
}
func usageAndExit(message string, exitCode int) {
if message != "" {
fmt.Fprintf(os.Stderr, message)
fmt.Fprintf(os.Stderr, "\n\n")
}
flag.Usage()
fmt.Fprintf(os.Stderr, "\n")
os.Exit(exitCode)
}