-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
304 lines (262 loc) · 8.7 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
// Package main implements the Ortelius v11 Scorecard Microservice, which provides a REST API
// to retrieve OpenSSF Scorecard metrics for a given repository and commit SHA. This microservice
// uses the Fiber web framework for handling HTTP requests and integrates with the OpenSSF Scorecard
// API to fetch security-related metrics. Additionally, it provides a Swagger UI for API documentation
// and a health check endpoint for Kubernetes deployments. The microservice is configured to log
// in a human-readable format using the Zap logging library.
package main
import (
"github.com/ortelius/scec-commons/model"
_ "github.com/ortelius/scec-scorecard/docs"
"encoding/json"
"os"
"os/exec"
"strings"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"github.com/go-resty/resty/v2"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/swagger"
ossf "github.com/ossf/scorecard/v5/pkg/scorecard"
)
const scorecardAPIBaseURL = "https://api.securityscorecards.dev/projects/"
// InitLogger sets up the Zap Logger to log to the console in a human readable format
func InitLogger() *zap.Logger {
prodConfig := zap.NewProductionConfig()
prodConfig.Encoding = "console"
prodConfig.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
prodConfig.EncoderConfig.EncodeDuration = zapcore.StringDurationEncoder
logger, _ := prodConfig.Build()
return logger
}
var logger = InitLogger()
var client = resty.New()
// getScorecard godoc
// @Summary Get the OSSF scorecard for a repo
// @Description Get a scorecard for a repo and commit sha
// @Tags scorecard
// @Accept */*
// @Produce json
// @Success 200
// @Router /msapi/scorecard/:key [get]
func getScorecard(c *fiber.Ctx) error {
var scorecard model.Scorecard
repoURL := c.Params("*")
commitSha := c.Query("commit")
if repoURL == "" {
return c.JSON(scorecard)
}
githubURL := cleanRepoURL(repoURL)
fullURL := scorecardAPIBaseURL + githubURL
if commitSha != "" {
fullURL += "?commit=" + commitSha
}
resp, err := client.R().Get(fullURL)
if err != nil {
return c.JSON(scorecard) // handle error
}
if resp.StatusCode() == fiber.StatusOK {
return c.JSON(parseScoreCard(resp, commitSha))
}
// Retry without commitSha if the first attempt fails
if commitSha != "" {
fullURL = scorecardAPIBaseURL + githubURL
resp, err = client.R().Get(fullURL)
if err != nil {
return c.JSON(scorecard)
}
if resp.StatusCode() == fiber.StatusOK {
return c.JSON(parseScoreCard(resp, commitSha))
}
}
// If failed and GITHUB_TOKEN is available, fallback to CLI
if token := os.Getenv("GITHUB_TOKEN"); token != "" && strings.Contains(githubURL, "github.com") && commitSha != "" {
return c.JSON(fetchScoreCardWithCLI(githubURL, commitSha))
}
return c.JSON(scorecard)
}
func cleanRepoURL(repoURL string) string {
replacements := []struct {
old string
new string
}{
{"git+ssh://git@", ""},
{"git+https://", ""},
{"http://", ""},
{"https://", ""},
{"git:", ""},
{"git+", ""},
{".git", ""},
}
for _, repl := range replacements {
repoURL = strings.ReplaceAll(repoURL, repl.old, repl.new)
}
return repoURL
}
func parseScoreCard(resp *resty.Response, commitSha string) *model.Scorecard {
var scorecard model.Scorecard
var result ossf.JSONScorecardResultV2
if err := json.Unmarshal(resp.Body(), &result); err != nil {
return &scorecard
}
if result.Repo.Commit == commitSha {
scorecard.Pinned = true
scorecard.CommitSha = commitSha
}
scorecard.Score = float32(result.AggregateScore)
for _, check := range result.Checks {
name := check.Name
score := float32(check.Score)
switch name {
case "Maintained":
scorecard.Maintained = score
case "Code-Review":
scorecard.CodeReview = score
case "CII-Best-Practices":
scorecard.CIIBestPractices = score
case "License":
scorecard.License = score
case "Signed-Releases":
scorecard.SignedReleases = score
case "Dangerous-Workflow":
scorecard.DangerousWorkflow = score
case "Packaging":
scorecard.Packaging = score
case "Token-Permissions":
scorecard.TokenPermissions = score
case "Branch-Protection":
scorecard.BranchProtection = score
case "Binary-Artifacts":
scorecard.BinaryArtifacts = score
case "Pinned-Dependencies":
scorecard.PinnedDependencies = score
case "Security-Policy":
scorecard.SecurityPolicy = score
case "Fuzzing":
scorecard.Fuzzing = score
case "SAST":
scorecard.SAST = score
case "Vulnerabilities":
scorecard.Vulnerabilities = score
case "CI-Tests":
scorecard.CITests = score
case "Contributors":
scorecard.Contributors = score
case "Dependency-Update-Tool":
scorecard.DependencyUpdateTool = score
case "SBOM":
scorecard.SBOM = score
case "Webhooks":
scorecard.Webhooks = score
}
}
return &scorecard
}
func fetchScoreCardWithCLI(repoURL, commitSha string) *model.Scorecard {
var scorecard model.Scorecard
var out strings.Builder
cmd := exec.Command("scorecard", "--repo="+repoURL, "--commit="+commitSha, "--format", "json") // #nosec G204
cmd.Stdout = &out
err := cmd.Run()
if err != nil {
return &scorecard
}
var result ossf.JSONScorecardResultV2
if err := json.Unmarshal([]byte(out.String()), &result); err != nil {
return &scorecard
}
if result.Repo.Commit == commitSha {
scorecard.Pinned = true
scorecard.CommitSha = commitSha
}
scorecard.Score = float32(result.AggregateScore)
for _, check := range result.Checks {
name := check.Name
score := float32(check.Score)
switch name {
case "Maintained":
scorecard.Maintained = score
case "Code-Review":
scorecard.CodeReview = score
case "CII-Best-Practices":
scorecard.CIIBestPractices = score
case "License":
scorecard.License = score
case "Signed-Releases":
scorecard.SignedReleases = score
case "Dangerous-Workflow":
scorecard.DangerousWorkflow = score
case "Packaging":
scorecard.Packaging = score
case "Token-Permissions":
scorecard.TokenPermissions = score
case "Branch-Protection":
scorecard.BranchProtection = score
case "Binary-Artifacts":
scorecard.BinaryArtifacts = score
case "Pinned-Dependencies":
scorecard.PinnedDependencies = score
case "Security-Policy":
scorecard.SecurityPolicy = score
case "Fuzzing":
scorecard.Fuzzing = score
case "SAST":
scorecard.SAST = score
case "Vulnerabilities":
scorecard.Vulnerabilities = score
case "CI-Tests":
scorecard.CITests = score
case "Contributors":
scorecard.Contributors = score
case "Dependency-Update-Tool":
scorecard.DependencyUpdateTool = score
case "SBOM":
scorecard.SBOM = score
case "Webhooks":
scorecard.Webhooks = score
}
}
return &scorecard
}
// HealthCheck for kubernetes to determine if it is in a good state
func HealthCheck(c *fiber.Ctx) error {
return c.SendString("OK")
}
// setupRoutes defines maps the routes to the functions
func setupRoutes(app *fiber.App) {
app.Get("/swagger/*", swagger.HandlerDefault) // handle displaying the swagger
app.Get("/msapi/scorecard/*", getScorecard) // repo + ?commit=<sha>
app.Get("/health", HealthCheck) // kubernetes health check
}
// @title Ortelius v11 Scorecard Microservice
// @version 11.0.0
// @description RestAPI for the Scorecard Object
// @description ![Release](https://img.shields.io/github/v/release/ortelius/scec-scorecard?sort=semver)
// @description ![license](https://img.shields.io/github/license/ortelius/.github)
// @description
// @description ![Build](https://img.shields.io/github/actions/workflow/status/ortelius/scec-scorecard/build-push-chart.yml)
// @description [![MegaLinter](https://github.com/ortelius/scec-scorecard/workflows/MegaLinter/badge.svg?branch=main)](https://github.com/ortelius/scec-scorecard/actions?query=workflow%3AMegaLinter+branch%3Amain)
// @description ![CodeQL](https://github.com/ortelius/scec-scorecard/workflows/CodeQL/badge.svg)
// @description [![OpenSSF-Scorecard](https://api.securityscorecards.dev/projects/github.com/ortelius/scec-scorecard/badge)](https://api.securityscorecards.dev/projects/github.com/ortelius/scec-scorecard)
// @description
// @description ![Discord](https://img.shields.io/discord/722468819091849316)
// @termsOfService http://swagger.io/terms/
// @contact.name Ortelius Google Group
// @contact.email [email protected]
// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html
// @host localhost:3000
// @BasePath /msapi/scorecard
func main() {
port := os.Getenv("MS_PORT")
if port == "" {
port = ":8083"
} else {
port = ":" + port
}
app := fiber.New() // create a new fiber application
setupRoutes(app) // define the routes for this microservice
if err := app.Listen(port); err != nil { // start listening for incoming connections
logger.Sugar().Fatalf("Failed get the microservice running: %v", err)
}
}