-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
203 lines (175 loc) · 5.91 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
/*
Copyright (C) 2024 eLife Sciences
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io/ioutil"
"math"
"net/url"
"os"
"strconv"
"strings"
"time"
"github.com/google/go-github/v52/github"
"golang.org/x/oauth2"
)
// type aliases, readability only
type Project = string
type Maintainer = string
// subset of interesting fields of a `github.DependabotAlert`
type Alert struct {
AgeDays int
Summary string
URL string
CVE_ID string
GHSA_ID string
}
func panicOnErr(err error, action string) {
if err != nil {
panic(fmt.Sprintf("failed with '%s' while '%s'", err.Error(), action))
}
}
// dump data into prettily formatted json with ordered fields.
func as_json(thing interface{}) string {
json_blob_bytes, err := json.Marshal(thing)
panicOnErr(err, "marshalling JSON data into a byte array")
var out bytes.Buffer
json.Indent(&out, json_blob_bytes, "", " ")
return out.String()
}
// ---
func github_token() string {
token, present := os.LookupEnv("GITHUB_TOKEN")
if !present {
panic("envvar GITHUB_TOKEN not set.")
}
return token
}
// extracts a repository name from a url:
// "https://github.com/elifesciences/journal-cms/security/dependabot/19" => "journal-cms"
func extract_project_from_url(github_url string) Project {
u, err := url.Parse(github_url)
panicOnErr(err, "parsing a URL")
p := u.Path
bits := strings.Split(p, "/")
return bits[2]
}
// parse and return a mapping of `project => maintainer` from a json file
// optionally provided at the command line.
// returns an empty map if not.
func parse_maintainer_alias_map(args []string) map[Project][]Maintainer {
maintainer_alias_map := map[Project][]Maintainer{}
if len(args) > 0 {
path := args[0]
txt, err := ioutil.ReadFile(path)
panicOnErr(err, "reading maintainer alias map file")
json.Unmarshal(txt, &maintainer_alias_map)
}
return maintainer_alias_map
}
// talks to the Github API and returns a mapping of project names to
// simplified alert lists.
func fetch_project_alert_map(org_name, token string) map[Project][]Alert {
ctx := context.Background()
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: token},
)
tc := oauth2.NewClient(ctx, ts)
client := github.NewClient(tc)
opts := &github.ListAlertsOptions{
State: github.String("open"),
Sort: github.String("created"), // default
Direction: github.String("asc"), // default is 'desc'
ListCursorOptions: github.ListCursorOptions{
PerPage: 100,
},
}
var dependabot_alert_list []*github.DependabotAlert
for {
dependabot_alert_list_page, resp, err := client.Dependabot.ListOrgAlerts(ctx, org_name, opts)
panicOnErr(err, "listing org security alerts")
dependabot_alert_list = append(dependabot_alert_list, dependabot_alert_list_page...)
if resp.NextPage == 0 {
break
}
opts.Page = strconv.Itoa(resp.NextPage)
}
now := time.Now()
idx := map[Project][]Alert{}
for _, dependabot_alert := range dependabot_alert_list {
pname := extract_project_from_url(dependabot_alert.GetHTMLURL())
project_alert_list, present := idx[pname]
if !present {
project_alert_list = []Alert{}
}
age := now.Sub(dependabot_alert.GetCreatedAt().Time)
age_days := int(math.Ceil(age.Hours() / 24))
alert := Alert{
CVE_ID: dependabot_alert.SecurityAdvisory.GetCVEID(),
GHSA_ID: dependabot_alert.SecurityAdvisory.GetGHSAID(),
Summary: dependabot_alert.SecurityAdvisory.GetSummary(),
URL: dependabot_alert.GetHTMLURL(),
AgeDays: age_days,
}
project_alert_list = append(project_alert_list, alert)
idx[pname] = project_alert_list
}
return idx
}
// returns `true` if `str` is (probably) an email address
func is_email_address(str string) bool {
return str != "" && str[0] != '#' && strings.Contains(str, "@")
}
func main() {
args := os.Args[1:]
token := github_token()
org_name := "elifesciences"
maintainer_alias_map := parse_maintainer_alias_map(args)
project_alert_map := fetch_project_alert_map(org_name, token)
if len(project_alert_map) > 0 && len(maintainer_alias_map) > 0 {
// we have project alerts and we have project maintainers.
// group the projects by maintainers.
maintainer_project_map := map[Maintainer]map[Project][]Alert{}
for project, alert_list := range project_alert_map {
project_maintainer_list, present := maintainer_alias_map[project]
if !present {
// project has no maintainers!
// it's possible the repository is new and using vulnerable deps.
// projects with no maintainers are handled in `elifesciences/maintainers-txt` repository.
fmt.Fprintf(os.Stderr, "skipping project '%s' with %d alert(s): no maintainers found\n", project, len(alert_list))
continue
}
for _, maintainer := range project_maintainer_list {
if !is_email_address(maintainer) {
fmt.Fprintf(os.Stderr, "skipping maintainer, doesn't look like an email address: %s\n", maintainer)
continue
}
project_map, present := maintainer_project_map[maintainer]
if !present {
project_map = map[Project][]Alert{}
}
project_map[project] = alert_list
maintainer_project_map[maintainer] = project_map
}
}
fmt.Println(as_json(maintainer_project_map))
} else if len(project_alert_map) > 0 {
// we have project alerts but no list of project maintainers.
// output everything as-is
fmt.Println(as_json(project_alert_map))
}
}