Skip to content

Commit

Permalink
update linter + fix whitespace (#443)
Browse files Browse the repository at this point in the history
Signed-off-by: Alex Goodman <[email protected]>
  • Loading branch information
wagoodman authored Oct 6, 2021
1 parent cd3b414 commit 6fe9fc2
Show file tree
Hide file tree
Showing 20 changed files with 59 additions and 54 deletions.
10 changes: 6 additions & 4 deletions .golangci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,14 @@ linters:
- dogsled
- dupl
- errcheck
- exportloopref
- funlen
- gocognit
- goconst
- gocritic
- gocyclo
- gofmt
- goimports
- golint
- goprintffuncname
- gosec
- gosimple
Expand All @@ -28,8 +28,8 @@ linters:
- misspell
- nakedret
- nolintlint
- revive
- rowserrcheck
- scopelint
- staticcheck
- structcheck
- stylecheck
Expand All @@ -46,11 +46,13 @@ linters:
# - godot
# - godox
# - goerr113
# - golint # deprecated
# - gomnd # this is too aggressive
# - interfacer # this is a good idea, but is no longer supported and is prone to false positives
# - lll # without a way to specify per-line exception cases, this is not usable
# - maligned # this is an excellent linter, but tricky to optimize and we are not sensitive to memory layout optimizations
# - prealloc # following this rule isn't consistently a good idea, as it sometimes forces unnecessary allocations that result in less idiomatic code
# - nestif
# - prealloc # following this rule isn't consistently a good idea, as it sometimes forces unnecessary allocations that result in less idiomatic code
# - scopelint # deprecated
# - testpackage
# - wsl
# - wsl # this doens't have an auto-fixer yet and is pretty noisy (https://github.com/bombsimon/wsl/issues/90)
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ bootstrap: ## Download and install all go dependencies (+ prep tooling in the ./
# install go dependencies
go mod download

curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(TEMPDIR)/ v1.26.0
curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(TEMPDIR)/ v1.42.1
curl -sSfL https://raw.githubusercontent.com/wagoodman/go-bouncer/master/bouncer.sh | sh -s -- -b $(TEMPDIR)/ v0.2.0
curl -sfL https://install.goreleaser.com/github.com/goreleaser/goreleaser.sh | sh -s -- -b $(TEMPDIR)/ v0.179.0

Expand Down
6 changes: 3 additions & 3 deletions cmd/db_check.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,15 @@ var dbCheckCmd = &cobra.Command{
Use: "check",
Short: "check to see if there is a database update available",
Args: cobra.ExactArgs(0),
RunE: runDbCheckCmd,
RunE: runDBCheckCmd,
}

func init() {
dbCmd.AddCommand(dbCheckCmd)
}

func runDbCheckCmd(_ *cobra.Command, _ []string) error {
dbCurator := db.NewCurator(appConfig.Db.ToCuratorConfig())
func runDBCheckCmd(_ *cobra.Command, _ []string) error {
dbCurator := db.NewCurator(appConfig.DB.ToCuratorConfig())

updateAvailable, _, err := dbCurator.IsUpdateAvailable()
if err != nil {
Expand Down
6 changes: 3 additions & 3 deletions cmd/db_delete.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,15 @@ var dbDeleteCmd = &cobra.Command{
Use: "delete",
Short: "delete the vulnerability database",
Args: cobra.ExactArgs(0),
RunE: runDbDeleteCmd,
RunE: runDBDeleteCmd,
}

func init() {
dbCmd.AddCommand(dbDeleteCmd)
}

func runDbDeleteCmd(_ *cobra.Command, _ []string) error {
dbCurator := db.NewCurator(appConfig.Db.ToCuratorConfig())
func runDBDeleteCmd(_ *cobra.Command, _ []string) error {
dbCurator := db.NewCurator(appConfig.DB.ToCuratorConfig())

if err := dbCurator.Delete(); err != nil {
return fmt.Errorf("unable to delete vulnerability database: %+v", err)
Expand Down
6 changes: 3 additions & 3 deletions cmd/db_import.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,15 @@ var dbImportCmd = &cobra.Command{
Short: "import a vulnerability database archive",
Long: fmt.Sprintf("import a vulnerability database archive from a local FILE.\nDB archives can be obtained from %q.", internal.DBUpdateURL),
Args: cobra.ExactArgs(1),
RunE: runDbImportCmd,
RunE: runDBImportCmd,
}

func init() {
dbCmd.AddCommand(dbImportCmd)
}

func runDbImportCmd(_ *cobra.Command, args []string) error {
dbCurator := db.NewCurator(appConfig.Db.ToCuratorConfig())
func runDBImportCmd(_ *cobra.Command, args []string) error {
dbCurator := db.NewCurator(appConfig.DB.ToCuratorConfig())

if err := dbCurator.ImportFrom(args[0]); err != nil {
return fmt.Errorf("unable to import vulnerability database: %+v", err)
Expand Down
6 changes: 3 additions & 3 deletions cmd/db_status.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,15 @@ var statusCmd = &cobra.Command{
Use: "status",
Short: "display database status",
Args: cobra.ExactArgs(0),
RunE: runDbStatusCmd,
RunE: runDBStatusCmd,
}

func init() {
dbCmd.AddCommand(statusCmd)
}

func runDbStatusCmd(_ *cobra.Command, _ []string) error {
dbCurator := db.NewCurator(appConfig.Db.ToCuratorConfig())
func runDBStatusCmd(_ *cobra.Command, _ []string) error {
dbCurator := db.NewCurator(appConfig.DB.ToCuratorConfig())
status := dbCurator.Status()

statusStr := "valid"
Expand Down
6 changes: 3 additions & 3 deletions cmd/db_update.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,15 @@ var dbUpdateCmd = &cobra.Command{
Use: "update",
Short: "download the latest vulnerability database",
Args: cobra.ExactArgs(0),
RunE: runDbUpdateCmd,
RunE: runDBUpdateCmd,
}

func init() {
dbCmd.AddCommand(dbUpdateCmd)
}

func runDbUpdateCmd(_ *cobra.Command, _ []string) error {
dbCurator := db.NewCurator(appConfig.Db.ToCuratorConfig())
func runDBUpdateCmd(_ *cobra.Command, _ []string) error {
dbCurator := db.NewCurator(appConfig.DB.ToCuratorConfig())

updated, err := dbCurator.Update()
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion cmd/event_loop.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import (
// eventLoop listens to worker errors (from execution path), worker events (from a partybus subscription), and
// signal interrupts. Is responsible for handling each event relative to a given UI an to coordinate eventing until
// an eventual graceful exit.
// nolint:gocognit,funlen
// nolint:gocognit
func eventLoop(workerErrs <-chan error, signals <-chan os.Signal, subscription *partybus.Subscription, cleanupFn func(), uxs ...ui.UI) error {
defer cleanupFn()
events := subscription.Events()
Expand Down
6 changes: 5 additions & 1 deletion cmd/report_writer.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,24 @@ import (

func reportWriter() (io.Writer, func() error, error) {
nop := func() error { return nil }

path := strings.TrimSpace(appConfig.File)

switch len(path) {
case 0:
return os.Stdout, nop, nil

default:
reportFile, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)

if err != nil {
return nil, nop, fmt.Errorf("unable to create report file: %w", err)
}

return reportFile, func() error {
if !appConfig.Quiet {
fmt.Printf("Report written to %q\n", path)
}

return reportFile.Close()
}, nil
}
Expand Down
2 changes: 1 addition & 1 deletion cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,7 @@ func startWorker(userInput string, failOnSeverity *vulnerability.Severity) <-cha
go func() {
defer wg.Done()
log.Debug("loading DB")
provider, metadataProvider, dbStatus, err = grype.LoadVulnerabilityDb(appConfig.Db.ToCuratorConfig(), appConfig.Db.AutoUpdate)
provider, metadataProvider, dbStatus, err = grype.LoadVulnerabilityDB(appConfig.DB.ToCuratorConfig(), appConfig.DB.AutoUpdate)
if err != nil {
errs <- fmt.Errorf("failed to load vulnerability db: %w", err)
}
Expand Down
8 changes: 4 additions & 4 deletions grype/db/curator.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ const (
)

type Config struct {
DbRootDir string
DBRootDir string
ListingURL string
ValidateByHashOnGet bool
}
Expand All @@ -41,7 +41,7 @@ type Curator struct {
}

func NewCurator(cfg Config) Curator {
dbDir := path.Join(cfg.DbRootDir, strconv.Itoa(vulnerability.SchemaVersion))
dbDir := path.Join(cfg.DBRootDir, strconv.Itoa(vulnerability.SchemaVersion))
return Curator{
fs: afero.NewOsFs(),
targetSchema: vulnerability.SchemaVersion,
Expand Down Expand Up @@ -293,7 +293,7 @@ func (c *Curator) validate(dbDirPath string) error {
}

// activate swaps over the downloaded db to the application directory
func (c *Curator) activate(aDbDirPath string) error {
func (c *Curator) activate(dbDirPath string) error {
_, err := c.fs.Stat(c.dbDir)
if !os.IsNotExist(err) {
// remove any previous databases
Expand All @@ -310,5 +310,5 @@ func (c *Curator) activate(aDbDirPath string) error {
}

// activate the new db cache
return file.CopyDir(c.fs, aDbDirPath, c.dbDir)
return file.CopyDir(c.fs, dbDirPath, c.dbDir)
}
2 changes: 1 addition & 1 deletion grype/db/curator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ func (g *testGetter) GetToDir(dst, src string, _ ...*progress.Manual) error {

func newTestCurator(fs afero.Fs, getter file.Getter, dbDir, metadataUrl string, validateDbHash bool) Curator {
c := NewCurator(Config{
DbRootDir: dbDir,
DBRootDir: dbDir,
ListingURL: metadataUrl,
ValidateByHashOnGet: validateDbHash,
})
Expand Down
2 changes: 1 addition & 1 deletion grype/lib.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ func FindVulnerabilitiesForPackage(provider vulnerability.Provider, d *distro.Di
return matcher.FindMatches(provider, d, packages...)
}

func LoadVulnerabilityDb(cfg db.Config, update bool) (vulnerability.Provider, vulnerability.MetadataProvider, *db.Status, error) {
func LoadVulnerabilityDB(cfg db.Config, update bool) (vulnerability.Provider, vulnerability.MetadataProvider, *db.Status, error) {
dbCurator := db.NewCurator(cfg)

if update {
Expand Down
30 changes: 15 additions & 15 deletions grype/matcher/apk/matcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ func (m *Matcher) Match(store vulnerability.Provider, d *distro.Distro, p pkg.Pa
return matches, nil
}

func (m *Matcher) cpeMatchesWithoutSecDbFixes(store vulnerability.Provider, d *distro.Distro, p pkg.Package) ([]match.Match, error) {
func (m *Matcher) cpeMatchesWithoutSecDBFixes(store vulnerability.Provider, d *distro.Distro, p pkg.Package) ([]match.Match, error) {
// find CPE-indexed vulnerability matches specific to the given package name and version
cpeMatches, err := common.FindMatchesByPackageCPE(store, p, m.Type())
if err != nil {
Expand All @@ -58,12 +58,12 @@ func (m *Matcher) cpeMatchesWithoutSecDbFixes(store vulnerability.Provider, d *d

// remove cpe matches where there is an entry in the secDB for the particular package-vulnerability pairing, and the
// installed package version is >= the fixed in version for the secDB record.
secDbVulnerabilities, err := store.GetByDistro(d, p)
secDBVulnerabilities, err := store.GetByDistro(d, p)
if err != nil {
return nil, err
}

secDbVulnerabilitiesByID := vulnerabilitiesByID(secDbVulnerabilities)
secDBVulnerabilitiesByID := vulnerabilitiesByID(secDBVulnerabilities)

verObj, err := version.NewVersionFromPkg(p)
if err != nil {
Expand All @@ -75,15 +75,15 @@ func (m *Matcher) cpeMatchesWithoutSecDbFixes(store vulnerability.Provider, d *d
cveLoop:
for id, cpeMatchesForID := range cpeMatchesByID {
// check to see if there is a secdb entry for this ID (CVE)
secDbVulnerabilitiesForID, exists := secDbVulnerabilitiesByID[id]
secDBVulnerabilitiesForID, exists := secDBVulnerabilitiesByID[id]
if !exists {
// does not exist in secdb, so the CPE record(s) should be added to the final results
finalCpeMatches = append(finalCpeMatches, cpeMatchesForID...)
continue
}

// there is a secdb entry...
for _, vuln := range secDbVulnerabilitiesForID {
for _, vuln := range secDBVulnerabilitiesForID {
// ...is there a fixed in entry? (should always be yes)
if len(vuln.Fix.Versions) == 0 {
continue
Expand All @@ -105,14 +105,14 @@ cveLoop:
return finalCpeMatches, nil
}

func deduplicateMatches(secDbMatches, cpeMatches []match.Match) (matches []match.Match) {
func deduplicateMatches(secDBMatches, cpeMatches []match.Match) (matches []match.Match) {
// add additional unique matches from CPE source that is unique from the SecDB matches
secDbMatchesByID := matchesByID(secDbMatches)
secDBMatchesByID := matchesByID(secDBMatches)
cpeMatchesByID := matchesByID(cpeMatches)
for id, cpeMatchesForID := range cpeMatchesByID {
// by this point all matches have been verified to be vulnerable within the given package version relative to the vulnerability source.
// now we will add unique CPE candidates that were not found in secdb.
if _, exists := secDbMatchesByID[id]; !exists {
if _, exists := secDBMatchesByID[id]; !exists {
// add the new CPE-based record (e.g. NVD) since it was not found in secDB
matches = append(matches, cpeMatchesForID...)
}
Expand All @@ -122,8 +122,8 @@ func deduplicateMatches(secDbMatches, cpeMatches []match.Match) (matches []match

func matchesByID(matches []match.Match) map[string][]match.Match {
var results = make(map[string][]match.Match)
for _, secDbMatch := range matches {
results[secDbMatch.Vulnerability.ID] = append(results[secDbMatch.Vulnerability.ID], secDbMatch)
for _, secDBMatch := range matches {
results[secDBMatch.Vulnerability.ID] = append(results[secDBMatch.Vulnerability.ID], secDBMatch)
}
return results
}
Expand All @@ -139,23 +139,23 @@ func vulnerabilitiesByID(vulns []vulnerability.Vulnerability) map[string][]vulne

func (m *Matcher) findApkPackage(store vulnerability.Provider, d *distro.Distro, p pkg.Package) ([]match.Match, error) {
// find Alpine SecDB matches for the given package name and version
secDbMatches, err := common.FindMatchesByPackageDistro(store, d, p, m.Type())
secDBMatches, err := common.FindMatchesByPackageDistro(store, d, p, m.Type())
if err != nil {
return nil, err
}

cpeMatches, err := m.cpeMatchesWithoutSecDbFixes(store, d, p)
cpeMatches, err := m.cpeMatchesWithoutSecDBFixes(store, d, p)
if err != nil {
return nil, err
}

var matches []match.Match

// keep all secdb matches, as this is an authoritative source
matches = append(matches, secDbMatches...)
matches = append(matches, secDBMatches...)

// keep only unique CPE matches
matches = append(matches, deduplicateMatches(secDbMatches, cpeMatches)...)
matches = append(matches, deduplicateMatches(secDBMatches, cpeMatches)...)

return matches, nil
}
Expand Down Expand Up @@ -211,7 +211,7 @@ func buildIndirectPackage(p pkg.Package) (pkg.Package, error) {
// For each cpe, replace pkg name with origin and add to set
cpeStrings := strset.New()
for _, cpe := range indirectPackage.CPEs {
updatedCPEString := strings.Replace(cpe.BindToFmtString(), p.Name, indirectPackage.Name, -1)
updatedCPEString := strings.ReplaceAll(cpe.BindToFmtString(), p.Name, indirectPackage.Name)
cpeStrings.Add(updatedCPEString)
}

Expand Down
6 changes: 3 additions & 3 deletions grype/presenter/cyclonedx/vulnerability.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,10 @@ type Vulnerability struct {
Source Source `xml:"v:source"`
Ratings []Rating `xml:"v:ratings>v:rating"`
// We do not capture Common Weakness Enumeration
//Cwes Cwes `xml:"v:cwes"`
// Cwes Cwes `xml:"v:cwes"`
Description string `xml:"v:description,omitempty"`
// We don't have recommendations (e.g. "upgrade")
//Recommendations *Recommendations `xml:"v:recommendations"`
// Recommendations *Recommendations `xml:"v:recommendations"`
Advisories *Advisories `xml:"v:advisories,omitempty"`
}

Expand Down Expand Up @@ -57,7 +57,7 @@ type Advisories struct {
// cvssVersionToMethod accepts a CVSS version as string (e.g. "3.1") and converts it to a
// CycloneDx rating Method, for example "CVSSv3"
func cvssVersionToMethod(version string) (string, error) {
value, err := strconv.ParseFloat(version, 16)
value, err := strconv.ParseFloat(version, 64)
if err != nil {
return "", err
}
Expand Down
2 changes: 1 addition & 1 deletion grype/presenter/models/descriptor.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,5 @@ type descriptor struct {
Name string `json:"name"`
Version string `json:"version"`
Configuration interface{} `json:"configuration,omitempty"`
VulnerabilityDbStatus interface{} `json:"db,omitempty"`
VulnerabilityDBStatus interface{} `json:"db,omitempty"`
}
2 changes: 1 addition & 1 deletion grype/presenter/models/document.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ func NewDocument(packages []pkg.Package, context pkg.Context, matches match.Matc
Name: internal.ApplicationName,
Version: version.FromBuild().Version,
Configuration: appConfig,
VulnerabilityDbStatus: dbStatus,
VulnerabilityDBStatus: dbStatus,
},
}, nil
}
Loading

0 comments on commit 6fe9fc2

Please sign in to comment.