This repository has been archived by the owner on Jun 10, 2024. It is now read-only.
generated from ossf/project-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
383 lines (357 loc) · 12.1 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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
// Copyright 2023 OpenSSF Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"regexp"
"strconv"
"strings"
"github.com/google/go-github/v46/github"
"golang.org/x/oauth2"
)
func extractPRNumber(ref string) string {
re := regexp.MustCompile(`refs/pull/(\d+)/merge`)
matches := re.FindStringSubmatch(ref)
if len(matches) > 1 {
return matches[1]
}
return ""
}
func main() {
vulnerabilities := ""
result := ""
repo := os.Getenv("GITHUB_REPOSITORY")
commitSHA := os.Getenv("GITHUB_SHA")
token := os.Getenv("GITHUB_TOKEN")
pr := extractPRNumber(os.Getenv("GITHUB_REF"))
ghUser := os.Getenv("GITHUB_ACTOR")
fileName := os.Getenv("SCORECARD_CHECKS")
if err := Validate(token, repo, commitSHA, pr); err != nil {
log.Fatal(err)
}
// convert pr to int
prInt, err := strconv.Atoi(pr)
if err != nil {
log.Fatal(err)
}
ownerRepo := strings.Split(repo, "/")
if len(ownerRepo) != 2 {
log.Fatal("invalid repo")
}
owner := ownerRepo[0]
repo = ownerRepo[1]
checks, err := GetScorecardChecks(fileName)
log.Println("checks", checks)
if err != nil {
log.Fatal(err)
}
ts := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: token})
tc := oauth2.NewClient(context.Background(), ts)
client := github.NewClient(tc)
defaultBranch, err := getDefaultBranch(owner, repo, client)
if err != nil {
log.Fatal(err)
}
diff, err := GetDependencyDiff(owner, repo, token, defaultBranch, commitSHA)
if err != nil {
log.Fatal(err)
}
m := make(map[string]DependencyDiff)
for _, dep := range diff { //nolint:gocritic
m[dep.SourceRepositoryURL] = dep
}
log.Println("dependency diff", m)
for k, i := range m { //nolint:gocritic
url := strings.TrimPrefix(k, "https://")
scorecard, err := GetScorecardResult(url)
log.Printf("scorecard result for %s: %+v\n", url, scorecard)
if err != nil {
if len(i.Vulnerabilities) > 0 {
vulnerabilities = GetVulnsHTML(i, vulnerabilities)
continue
}
continue
}
if len(i.Vulnerabilities) > 0 {
vulnerabilities = GetVulnsHTML(i, vulnerabilities)
}
scorecard.Checks = filter(scorecard.Checks, func(check Check) bool {
for _, c := range checks {
if check.Name == c {
return true
}
}
return false
})
scorecard.Vulnerabilities = i.Vulnerabilities
result += GitHubIssueComment(&scorecard)
}
// create or update comment
if vulnerabilities == "" && result == "" {
log.Println("no vulnerabilities and no scorecard results")
return
}
if err := createOrUpdateComment(
client, owner, ghUser, repo, prInt, "## Scorecard Results</br>\n"+vulnerabilities+"</br>"+result); err != nil {
log.Fatal(err)
}
if vulnerabilities != "" {
// this will fail the workflow if there are any vulnerabilities
os.Exit(1)
}
}
// GetVulnsHTML returns the vulnerabilities in HTML format.
func GetVulnsHTML(i DependencyDiff, vulnerabilities string) string { //nolint:gocritic
sb := strings.Builder{}
sb.WriteString(fmt.Sprintf("<details><summary>Vulnerabilties %s</summary>\n </br>", i.SourceRepositoryURL))
sb.WriteString("<table>\n")
sb.WriteString("<tr>\n")
sb.WriteString("<th>Severity</th>\n")
sb.WriteString("<th>AdvisoryGHSAId</th>\n")
sb.WriteString("<th>AdvisorySummary</th>\n")
sb.WriteString("<th>AdvisoryUrl</th>\n")
sb.WriteString("</tr>\n")
for _, v := range i.Vulnerabilities {
sb.WriteString("<tr>\n")
sb.WriteString(fmt.Sprintf("<td>%s</td>\n", v.Severity))
sb.WriteString(fmt.Sprintf("<td>%s</td>\n", v.AdvisoryGHSAId))
sb.WriteString(fmt.Sprintf("<td>%s</td>\n", v.AdvisorySummary))
sb.WriteString(fmt.Sprintf("<td>%s</td>\n", v.AdvisoryURL))
}
sb.WriteString("</table>\n")
sb.WriteString("</details>\n")
vulnerabilities += sb.String()
return vulnerabilities
}
// getDefaultBranch gets the default branch of the repository.
func getDefaultBranch(owner, repo string, client *github.Client) (string, error) {
ctx := context.Background()
repository, _, err := client.Repositories.Get(ctx, owner, repo)
if err != nil {
return "", fmt.Errorf("failed to get repository: %w", err)
}
return repository.GetDefaultBranch(), nil
}
// Validate validates the input parameters.
func Validate(token, repo, commitSHA, pr string) error {
if token == "" {
return fmt.Errorf("token is empty") //nolint:goerr113
}
if repo == "" {
return fmt.Errorf("repo is empty") //nolint:goerr113
}
if commitSHA == "" {
return fmt.Errorf("commitSHA is empty") //nolint:goerr113
}
if pr == "" {
return fmt.Errorf("pr is empty") //nolint:goerr113
}
return nil
}
// createOrUpdateComment creates a new comment on the pull request or updates an existing one.
func createOrUpdateComment(client *github.Client, owner, githubUser, repo string, prNum int, commentBody string) error {
comments, _, err := client.Issues.ListComments(
context.Background(), owner, repo, prNum, &github.IssueListCommentsOptions{})
if err != nil {
return fmt.Errorf("failed to get comments: %w", err)
}
// Check if the user has already left a comment on the pull request.
var existingComment *github.IssueComment
for _, comment := range comments {
if comment.GetUser().GetLogin() == githubUser {
existingComment = comment
break
}
}
// If the user has already left a comment, update it.
if existingComment != nil {
existingComment.Body = &commentBody
_, _, err = client.Issues.EditComment(context.Background(), owner, repo, *existingComment.ID, existingComment)
if err != nil {
return fmt.Errorf("failed to update comment: %w", err)
}
log.Println("Comment updated successfully!")
} else {
// Otherwise, create a new comment.
newComment := &github.IssueComment{
Body: &commentBody,
}
_, _, err = client.Issues.CreateComment(context.Background(), owner, repo, prNum, newComment)
if err != nil {
return fmt.Errorf("failed to create comment: %w", err)
}
log.Println("Comment created successfully!")
}
return nil
}
// GitHubIssueComment returns a markdown string for a GitHub issue comment.
func GitHubIssueComment(checks *ScorecardResult) string {
if checks.Repo.Name == "" {
log.Println("no checks")
return ""
}
sb := strings.Builder{}
sb.WriteString(fmt.Sprintf("<details><summary>%s - %s</summary>\n </br>", checks.Repo.Name, checks.Date))
sb.WriteString(fmt.Sprintf(
"<a href=https://api.securityscorecards.dev/projects/%s>https://api.securityscorecards.dev/projects/%s</a><br></br>",
checks.Repo.Name,
checks.Repo.Name))
sb.WriteString("<table>\n")
sb.WriteString("<tr><th>Check</th><th>Score</th></tr>\n")
for _, check := range checks.Checks {
sb.WriteString(fmt.Sprintf("<tr><td>%s</td><td>%d</td></tr>\n", check.Name, check.Score))
}
sb.WriteString("</table>\n")
if len(checks.Vulnerabilities) > 0 {
sb.WriteString("<table>\n")
sb.WriteString("<tr><th>Vulnerability</th><th>Severity</th><th>Summary</th></tr>\n")
for _, vulns := range checks.Vulnerabilities {
sb.WriteString(
fmt.Sprintf("<tr><td>%s</td><td>%s</td><td>%s</td></tr>\n", vulns.AdvisoryURL, vulns.Severity, vulns.AdvisorySummary)) //nolint:lll
}
sb.WriteString("</table>\n")
}
sb.WriteString("</details>")
return sb.String()
}
// GetDependencyDiff returns the dependency diff between two commits.
// It returns an error if the dependency graph is not enabled.
func GetDependencyDiff(owner, repo, token, base, head string) ([]DependencyDiff, error) {
var data []DependencyDiff
message := "failed to get dependency diff, please enable dependency graph https://docs.github.com/en/code-security/supply-chain-security/understanding-your-software-supply-chain/configuring-the-dependency-graph" //nolint:lll
if owner == "" {
return data, fmt.Errorf("owner is required") //nolint:goerr113
}
if repo == "" {
return data, fmt.Errorf("repo is required") //nolint:goerr113
}
if token == "" {
return data, fmt.Errorf("token is required") //nolint:goerr113
}
resp, err := GetGitHubDependencyDiff(owner, repo, token, base, head)
defer resp.Body.Close() //nolint:staticcheck
if resp.StatusCode != http.StatusOK {
// if the dependency graph is not enabled, we can't get the dependency diff
return data,
fmt.Errorf(" %s: %v", message, resp.Status) //nolint:goerr113
}
if err != nil {
return data, fmt.Errorf("failed to get dependency diff: %w", err)
}
// print the repnose body for debugging
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return data, fmt.Errorf("failed to read response body: %w", err)
}
fmt.Println(string(body))
// also decode the response body
// reset the body
resp.Body = ioutil.NopCloser(bytes.NewBuffer(body)) //nolint:staticcheck
err = json.NewDecoder(resp.Body).Decode(&data)
if err != nil {
return data, fmt.Errorf("failed to decode dependency diff: %w", err)
}
// filter out the dependencies that are not added
var filteredData []DependencyDiff
for _, dep := range data { //nolint:gocritic
// also if the source repo doesn't start with GitHub.com, we can ignore it
if dep.ChangeType == "added" && strings.HasPrefix(dep.SourceRepositoryURL, "https://github.com") {
filteredData = append(filteredData, dep)
}
}
return filteredData, nil
}
// GetGitHubDependencyDiff returns the dependency diff between two commits.
// It returns an error if the dependency graph is not enabled.
func GetGitHubDependencyDiff(owner, repo, token, base, head string) (*http.Response, error) {
req, err := http.NewRequest("GET",
fmt.Sprintf("https://api.github.com/repos/%s/%s/dependency-graph/compare/%s...%s", owner, repo, base, head), nil)
log.Println(req.URL.String())
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
// handle err
}
req.Header.Set("Accept", "application/vnd.github+json")
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to get response: %w", err)
}
return resp, nil
}
// filter returns a new slice containing all elements of slice that satisfy the predicate f.
func filter[T any](slice []T, f func(T) bool) []T {
var n []T
for _, e := range slice {
if f(e) {
n = append(n, e)
}
}
return n
}
// GetScorecardChecks returns the list of checks to run.
// This uses the SCORECARD_CHECKS environment variable to get the path to the checks list.
func GetScorecardChecks(fileName string) ([]string, error) {
if fileName == "" {
// default to critical and high severity checks
return []string{
"Dangerous-Workflow",
"Binary-Artifacts", "Branch-Protection", "Code-Review", "Dependency-Update-Tool",
}, nil
}
f, err := os.Open(fileName)
if err != nil {
return nil, fmt.Errorf("failed to open file %s: %w", fileName, err)
}
defer f.Close()
decoder := json.NewDecoder(f)
var checksFromFile []string
err = decoder.Decode(&checksFromFile)
if err != nil {
return nil, fmt.Errorf("failed to decode file %s: %w", fileName, err)
}
return checksFromFile, nil
}
// GetScorecardResult returns the scorecard result for a given repository.
func GetScorecardResult(repo string) (ScorecardResult, error) {
req, err := http.NewRequest("GET", fmt.Sprintf("https://api.securityscorecards.dev/projects/%s", repo), nil)
if err != nil {
return ScorecardResult{}, fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Accept", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return ScorecardResult{}, fmt.Errorf("failed to get response: %w", err)
}
defer resp.Body.Close()
result, err := ioutil.ReadAll(resp.Body)
if err != nil {
return ScorecardResult{}, fmt.Errorf("failed to read response: %w", err)
}
var scorecard ScorecardResult
err = json.Unmarshal(result, &scorecard)
if err != nil {
return ScorecardResult{}, fmt.Errorf("failed to unmarshal response: %w", err)
}
return scorecard, nil
}