update linter + fix whitespace (#443)

Signed-off-by: Alex Goodman <alex.goodman@anchore.com>
This commit is contained in:
Alex Goodman 2021-10-06 09:49:42 -04:00 committed by GitHub
parent cd3b414e59
commit 6fe9fc2c8c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
20 changed files with 59 additions and 54 deletions

View file

@ -12,6 +12,7 @@ linters:
- dogsled
- dupl
- errcheck
- exportloopref
- funlen
- gocognit
- goconst
@ -19,7 +20,6 @@ linters:
- gocyclo
- gofmt
- goimports
- golint
- goprintffuncname
- gosec
- gosimple
@ -28,8 +28,8 @@ linters:
- misspell
- nakedret
- nolintlint
- revive
- rowserrcheck
- scopelint
- staticcheck
- structcheck
- stylecheck
@ -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)

View file

@ -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

View file

@ -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 {

View file

@ -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)

View file

@ -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)

View file

@ -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"

View file

@ -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 {

View file

@ -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()

View file

@ -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
}

View file

@ -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)
}

View file

@ -25,7 +25,7 @@ const (
)
type Config struct {
DbRootDir string
DBRootDir string
ListingURL string
ValidateByHashOnGet bool
}
@ -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,
@ -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
@ -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)
}

View file

@ -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,
})

View file

@ -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 {

View file

@ -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 {
@ -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 {
@ -75,7 +75,7 @@ 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...)
@ -83,7 +83,7 @@ cveLoop:
}
// 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
@ -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...)
}
@ -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
}
@ -139,12 +139,12 @@ 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
}
@ -152,10 +152,10 @@ func (m *Matcher) findApkPackage(store vulnerability.Provider, d *distro.Distro,
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
}
@ -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)
}

View file

@ -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"`
}
@ -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
}

View file

@ -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"`
}

View file

@ -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
}

View file

@ -39,7 +39,7 @@ type Application struct {
ScopeOpt source.Scope `json:"-"`
Scope string `yaml:"scope" json:"scope" mapstructure:"scope"`
Log logging `yaml:"log" json:"log" mapstructure:"log"`
Db database `yaml:"db" json:"db" mapstructure:"db"`
DB database `yaml:"db" json:"db" mapstructure:"db"`
Dev development `yaml:"dev" json:"dev" mapstructure:"dev"`
FailOn string `yaml:"fail-on-severity" json:"fail-on-severity" mapstructure:"fail-on-severity"`
FailOnSeverity *vulnerability.Severity `json:"-"`
@ -184,7 +184,6 @@ func (cfg Application) String() string {
}
// readConfig attempts to read the given config path from disk or discover an alternate store location
// nolint:funlen
func readConfig(v *viper.Viper, configPath string) error {
var err error
v.AutomaticEnv()

View file

@ -25,7 +25,7 @@ func (cfg database) loadDefaultValues(v *viper.Viper) {
func (cfg database) ToCuratorConfig() db.Config {
return db.Config{
DbRootDir: cfg.Dir,
DBRootDir: cfg.Dir,
ListingURL: cfg.UpdateURL,
ValidateByHashOnGet: cfg.ValidateByHashOnStart,
}

View file

@ -28,8 +28,8 @@ func TestCompareSBOMInputToLibResults(t *testing.T) {
}
// get a grype DB
vulnProvider, _, _, err := grype.LoadVulnerabilityDb(db.Config{
DbRootDir: "test-fixtures/grype-db",
vulnProvider, _, _, err := grype.LoadVulnerabilityDB(db.Config{
DBRootDir: "test-fixtures/grype-db",
ListingURL: internal.DBUpdateURL,
ValidateByHashOnGet: false,
}, true)