-
Notifications
You must be signed in to change notification settings - Fork 444
/
generate_docs.go
486 lines (438 loc) · 14 KB
/
generate_docs.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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
package main
import (
"bytes"
"context"
"encoding/base64"
"encoding/gob"
"fmt"
"io/ioutil"
"log"
"os"
"github.com/solo-io/go-utils/contextutils"
"go.uber.org/zap/zapcore"
"github.com/solo-io/go-utils/securityscanutils"
"github.com/Masterminds/semver/v3"
"github.com/google/go-github/v32/github"
"github.com/rotisserie/eris"
. "github.com/solo-io/gloo/docs/cmd/securityscanutils"
changelogdocutils "github.com/solo-io/go-utils/changeloggenutils"
"github.com/solo-io/go-utils/githubutils"
"github.com/spf13/cobra"
)
func main() {
ctx := context.Background()
app := rootApp(ctx)
if err := app.Execute(); err != nil {
log.Fatalf("unable to run: %v\n", err)
}
}
type options struct {
ctx context.Context
targetRepo string
}
func rootApp(ctx context.Context) *cobra.Command {
opts := &options{
ctx: ctx,
}
app := &cobra.Command{}
app.AddCommand(changelogMdFromGithubCmd(opts))
app.AddCommand(securityScanMdFromCmd(opts))
app.AddCommand(enterpriseHelmValuesMdFromGithubCmd(opts))
app.AddCommand(getReleasesCmd(opts))
app.AddCommand(runSecurityScanCmd(opts))
app.PersistentFlags().StringVarP(&opts.targetRepo, "TargetRepo", "r", glooOpenSourceRepo, "specify one of 'gloo' or 'glooe'")
_ = app.MarkFlagRequired("TargetRepo")
return app
}
// Serializes github repository release and prints serialized releases to stdout
// To be used for caching release data for changelog/security scan docsgen.
func getReleasesCmd(opts *options) *cobra.Command {
app := &cobra.Command{
Use: "gen-releases",
Short: "cache github releases for gloo edge repository",
RunE: fetchAndSerializeReleases(opts),
}
return app
}
// Pulls scan results from google cloud bucket during docs generation.
// Then generates a human-readable single page for all our security scan results.
func securityScanMdFromCmd(opts *options) *cobra.Command {
app := &cobra.Command{
Use: "gen-security-scan-md",
Short: "pull down security scan files from gcloud bucket and generate docs markdown file",
RunE: func(cmd *cobra.Command, args []string) error {
if os.Getenv(skipSecurityScan) != "" {
return nil
}
return generateSecurityScanMd(opts)
},
}
return app
}
func changelogMdFromGithubCmd(opts *options) *cobra.Command {
app := &cobra.Command{
Use: "gen-changelog-md",
Short: "generate a markdown file from Github Release pages API",
RunE: func(cmd *cobra.Command, args []string) error {
if os.Getenv(skipChangelogGeneration) != "" {
return nil
}
return generateChangelogMd(opts)
},
}
return app
}
func enterpriseHelmValuesMdFromGithubCmd(opts *options) *cobra.Command {
app := &cobra.Command{
Use: "get-enterprise-helm-values",
Short: "Get documentation of valid helm values from Gloo Enterprise github",
RunE: func(cmd *cobra.Command, args []string) error {
if os.Getenv(skipEnterpriseDocsGeneration) != "" {
return nil
}
return fetchEnterpriseHelmValues(args)
},
}
return app
}
// Command for running the actual security scan on the images
func runSecurityScanCmd(opts *options) *cobra.Command {
app := &cobra.Command{
Use: "run-security-scan",
Short: "runs trivy scans on images from repo specified",
Long: "runs trivy vulnerability scans on images from the repo specified. Only reports HIGH and CRITICAL-level vulnerabilities and uploads scan results to google cloud bucket and github security page",
RunE: func(cmd *cobra.Command, args []string) error {
err := scanImagesForRepo(opts.ctx, opts.targetRepo)
return err
},
}
return app
}
// Fetches releases and serializes them and prints to stdout.
// This is meant to be used so that releases can be cached locally for multiple tasks
// such as security scanning, changelog generation
// rather than fetch all repo releases per task and risk hitting GitHub ratelimit
func fetchAndSerializeReleases(opts *options) func(cmd *cobra.Command, args []string) error {
return func(cmd *cobra.Command, args []string) error {
if !useCachedReleases() {
return nil
}
client, err := githubutils.GetClient(opts.ctx)
if err != nil {
return err
}
switch opts.targetRepo {
case glooDocGen:
err = getRepoReleases(opts.ctx, glooOpenSourceRepo, client)
case glooEDocGen:
err = getRepoReleases(opts.ctx, glooEnterpriseRepo, client)
default:
return InvalidInputError(opts.targetRepo)
}
return err
}
}
// Serialized github RepositoryRelease array to be written to file
func getRepoReleases(ctx context.Context, repo string, client *github.Client) error {
allReleases, err := githubutils.GetAllRepoReleases(ctx, client, "solo-io", repo)
var buf bytes.Buffer
enc := gob.NewEncoder(&buf)
err = enc.Encode(allReleases)
if err != nil {
return err
}
fmt.Print(buf.String())
return nil
}
const (
glooDocGen = "gloo"
glooEDocGen = "glooe"
skipChangelogGeneration = "SKIP_CHANGELOG_GENERATION"
skipSecurityScan = "SKIP_SECURITY_SCAN"
skipEnterpriseDocsGeneration = "SKIP_ENTERPRISE_DOCS_GENERATION"
)
const (
repoOwner = "solo-io"
glooOpenSourceRepo = "gloo"
glooEnterpriseRepo = "solo-projects"
)
const (
glooCachedReleasesFile = "opensource.out"
glooeCachedReleasesFile = "enterprise.out"
)
var (
InvalidInputError = func(arg string) error {
return eris.Errorf("invalid input, must provide exactly one argument, either '%v' or '%v', (provided %v)",
glooDocGen,
glooEDocGen,
arg)
}
MissingGithubTokenError = func(envVar string) error {
return eris.Errorf("Must either set GITHUB_TOKEN or set %s environment variable to true", envVar)
}
FileNotFoundError = func(path string, branch string) error {
return eris.Errorf("Could not find file at path %s on branch %s", path, branch)
}
)
// Generates changelog for releases as fetched from Github
// Github defaults to a chronological order
func generateChangelogMd(opts *options) error {
client := githubutils.GetClientOrExit(context.Background())
switch opts.targetRepo {
case glooDocGen:
generator := changelogdocutils.NewMinorReleaseGroupedChangelogGenerator(changelogdocutils.Options{
MainRepo: "gloo",
RepoOwner: "solo-io",
MainRepoReleases: getCachedReleases(glooCachedReleasesFile),
}, client)
out, err := generator.GenerateJSON(context.Background())
if err != nil {
return err
}
fmt.Println(out)
case glooEDocGen:
err := generateGlooEChangelog()
if err != nil {
return err
}
default:
return InvalidInputError(opts.targetRepo)
}
return nil
}
// Fetches Gloo Enterprise releases, merges in open source release notes, and orders them by version
func generateGlooEChangelog() error {
// Initialize Auth
ctx := context.Background()
ghToken := os.Getenv("GITHUB_TOKEN")
if ghToken == "" {
return MissingGithubTokenError(skipChangelogGeneration)
}
client, err := githubutils.GetClient(ctx)
if err != nil {
return err
}
opts := changelogdocutils.Options{
NumVersions: 200,
MainRepo: glooEnterpriseRepo,
DependentRepo: glooOpenSourceRepo,
RepoOwner: repoOwner,
MainRepoReleases: getCachedReleases(glooeCachedReleasesFile),
DependentRepoReleases: getCachedReleases(glooCachedReleasesFile),
}
depFn, err := changelogdocutils.GetOSDependencyFunc(repoOwner, glooEnterpriseRepo, glooOpenSourceRepo, ghToken)
if err != nil {
return err
}
generator := changelogdocutils.NewMergedReleaseGeneratorWithDepFn(opts, client, depFn)
out, err := generator.GenerateJSON(context.Background())
if err != nil {
return err
}
fmt.Println(out)
return nil
}
func getCachedReleases(fileName string) []*github.RepositoryRelease {
bArray, err := ioutil.ReadFile(fileName)
if err != nil {
return nil
}
buf := bytes.NewBuffer(bArray)
enc := gob.NewDecoder(buf)
var releases []*github.RepositoryRelease
err = enc.Decode(&releases)
if err != nil {
return nil
}
return releases
}
func useCachedReleases() bool {
if os.Getenv("USE_CACHED_RELEASES") == "false" {
return false
}
return true
}
// Generates security scan log for releases
func generateSecurityScanMd(opts *options) error {
var err error
switch opts.targetRepo {
case glooDocGen:
err = generateSecurityScanGloo(context.Background())
case glooEDocGen:
err = generateSecurityScanGlooE(context.Background())
default:
return InvalidInputError(opts.targetRepo)
}
return err
}
// scanImagesForRepo executes a SecurityScan for the repo provided
func scanImagesForRepo(ctx context.Context, targetRepo string) error {
contextutils.SetLogLevel(zapcore.DebugLevel)
logger := contextutils.LoggerFrom(ctx)
versionConstraint, err := getScannerVersionConstraint()
if err != nil {
logger.Fatalf("Invalid constraint version: %v", err)
}
if versionConstraint == nil {
// to be extra-safe, we should require devs to configure a constraint
logger.Fatalf("No version constraint defined")
}
outputDir := getScannerOutputDir()
logger.Debugf("Scanner will write results to directory: %s", outputDir)
var securityScanRepos []*securityscanutils.SecurityScanRepo
if targetRepo == glooDocGen {
securityScanRepos = append(securityScanRepos, &securityscanutils.SecurityScanRepo{
Repo: glooOpenSourceRepo,
Owner: repoOwner,
Opts: &securityscanutils.SecurityScanOpts{
OutputDir: outputDir,
ImagesPerVersion: map[string][]string{
">=v1.6.0": OpenSourceImages(),
},
VersionConstraint: versionConstraint,
ImageRepo: "quay.io/solo-io",
UploadCodeScanToGithub: false,
CreateGithubIssuePerVersion: false,
CreateGithubIssueForLatestPatchVersion: true,
},
})
}
if targetRepo == glooEDocGen {
securityScanRepos = append(securityScanRepos, &securityscanutils.SecurityScanRepo{
Repo: glooEnterpriseRepo,
Owner: repoOwner,
Opts: &securityscanutils.SecurityScanOpts{
OutputDir: outputDir,
ImagesPerVersion: map[string][]string{
">=v1.7.x": EnterpriseImages(false),
},
VersionConstraint: versionConstraint,
ImageRepo: "quay.io/solo-io",
UploadCodeScanToGithub: false,
CreateGithubIssuePerVersion: false,
CreateGithubIssueForLatestPatchVersion: true,
},
})
}
if securityScanRepos == nil {
logger.Fatalf("No repositories were targeted to be scanned")
}
scanner := &securityscanutils.SecurityScanner{
Repos: securityScanRepos,
}
return scanner.GenerateSecurityScans(ctx)
}
func getScannerVersionConstraint() (*semver.Constraints, error) {
if versionConstraint := os.Getenv("VERSION_CONSTRAINT"); versionConstraint != "" {
return semver.NewConstraint(fmt.Sprintf("%s", versionConstraint))
}
if minVersionToScan := os.Getenv("MIN_SCANNED_VERSION"); minVersionToScan != "" {
return semver.NewConstraint(fmt.Sprintf(">= %s", minVersionToScan))
}
// no constraint applied
return nil, nil
}
// getScannerOutputDir returns the local directory where scans will be accumulated
func getScannerOutputDir() string {
if scanDir := os.Getenv("SCAN_DIR"); scanDir != "" {
return scanDir
}
return "_output/scans"
}
func generateSecurityScanGloo(ctx context.Context) error {
// Initialize Auth
client, err := githubutils.GetClient(ctx)
if err != nil {
return err
}
var allReleases []*github.RepositoryRelease
if useCachedReleases() {
allReleases = getCachedReleases(glooCachedReleasesFile)
} else {
allReleases, err = githubutils.GetAllRepoReleases(ctx, client, repoOwner, glooOpenSourceRepo)
if err != nil {
return err
}
}
githubutils.SortReleasesBySemver(allReleases)
versionsToScan := getVersionsToScan(allReleases)
return BuildSecurityScanReportGloo(versionsToScan)
}
func generateSecurityScanGlooE(ctx context.Context) error {
// Initialize Auth
client, err := githubutils.GetClient(ctx)
if err != nil {
return err
}
var allReleases []*github.RepositoryRelease
if useCachedReleases() {
allReleases = getCachedReleases(glooeCachedReleasesFile)
} else {
allReleases, err = githubutils.GetAllRepoReleases(ctx, client, repoOwner, glooEnterpriseRepo)
if err != nil {
return err
}
}
githubutils.SortReleasesBySemver(allReleases)
versionsToScan := getVersionsToScan(allReleases)
return BuildSecurityScanReportGlooE(versionsToScan)
}
func fetchEnterpriseHelmValues(args []string) error {
ctx := context.Background()
client, err := githubutils.GetClient(ctx)
if err != nil {
return err
}
// Download the file at the specified path on the latest released branch of solo-projects
path := "install/helm/gloo-ee/reference/values.txt"
semverReleaseTag, err := ioutil.ReadFile("../_output/gloo-enterprise-version")
if err != nil {
return err
}
version, err := semver.NewVersion(string(semverReleaseTag))
if err != nil {
return err
}
minorReleaseTag := fmt.Sprintf("v%d.%d.x", version.Major(), version.Minor())
files, err := githubutils.GetFilesFromGit(ctx, client, repoOwner, glooEnterpriseRepo, minorReleaseTag, path)
if err != nil {
return err
}
if len(files) <= 0 {
return FileNotFoundError(path, minorReleaseTag)
}
// Decode the file and log to the console
decodedContents, err := base64.StdEncoding.DecodeString(*files[0].Content)
if err != nil {
return err
}
fmt.Printf("%s", decodedContents)
return nil
}
func getVersionsToScan(releases []*github.RepositoryRelease) []string {
var (
versions []string
stableOnlyConstraint *semver.Constraints
err error
)
minVersionToScan := os.Getenv("MIN_SCANNED_VERSION")
if minVersionToScan == "" {
log.Println("MIN_SCANNED_VERSION environment variable not set, scanning all versions from repo")
} else {
stableOnlyConstraint, err = semver.NewConstraint(fmt.Sprintf(">= %s", minVersionToScan))
if err != nil {
log.Fatalf("Invalid constraint version: %s", minVersionToScan)
}
}
for _, release := range releases {
// ignore beta releases when display security scan results
test, err := semver.NewVersion(release.GetTagName())
if err != nil {
continue
}
if stableOnlyConstraint == nil || stableOnlyConstraint.Check(test) {
versions = append(versions, test.String())
}
}
return versions
}