Skip to content

Commit

Permalink
[lint] Add golangci-lint automation + fix existing issues
Browse files Browse the repository at this point in the history
  • Loading branch information
Tomasz Jonak committed Nov 21, 2023
1 parent 3628e71 commit fd5412b
Show file tree
Hide file tree
Showing 20 changed files with 254 additions and 266 deletions.
28 changes: 28 additions & 0 deletions .github/workflows/golang-linter.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
name: golangci-lint
on:
push:
branches:
- main
pull_request:

permissions:
contents: read
pull-requests: read

jobs:
lint:
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v3
with:
submodules: recursive
fetch-depth: "0"
- uses: actions/setup-go@v4
with:
go-version: '1.21'
cache: false
- name: golangci-lint
uses: golangci/golangci-lint-action@v3
with:
version: v1.55
only-new-issues: true
11 changes: 11 additions & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
linters:
enable:
- stylecheck
- gocritic
# - dupl
- durationcheck
# - goconst
- gofmt
- goimports
# - misspell
# - nestif
10 changes: 5 additions & 5 deletions internal/deepfence/lock.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,12 @@ func NewFlock() *Flock {
return &Flock{}
}

func getBootId() ([]byte, error) {
bootId, err := os.ReadFile("/proc/sys/kernel/random/boot_id")
func getBootID() ([]byte, error) {
bootID, err := os.ReadFile("/proc/sys/kernel/random/boot_id")
if err != nil {
return nil, fmt.Errorf("failed to read boot id: %w", err)
}
return bootId, nil
return bootID, nil
}

// Acquires a shared lock on the file.
Expand All @@ -36,13 +36,13 @@ func (f *Flock) LockFile() error {
}
defer fd.Close()

bootId, err := getBootId()
bootID, err := getBootID()
if err != nil {
return err
}

file := os.NewFile(fd.Fd(), lockFilePath)
file.Write(bootId)
_, _ = file.Write(bootID)

if err := syscall.Flock(int(fd.Fd()), syscall.LOCK_SH); err != nil {
return fmt.Errorf("failed to acquire the lock file: %w", err)
Expand Down
8 changes: 4 additions & 4 deletions jobs/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,17 @@ import (
)

var (
running_jobs_num atomic.Int32
runningJobsNum atomic.Int32
)

func StartScanJob() {
running_jobs_num.Add(1)
runningJobsNum.Add(1)
}

func StopScanJob() {
running_jobs_num.Add(-1)
runningJobsNum.Add(-1)
}

func GetRunningJobCount() int32 {
return running_jobs_num.Load()
return runningJobsNum.Load()
}
36 changes: 18 additions & 18 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ const (

var (
supportedRuntime = []string{vc.DOCKER, vc.CONTAINERD, vc.CRIO, vc.PODMAN}
modes = []string{utils.ModeLocal, utils.ModeGrpcServer, utils.ModeHttpServer, utils.ModeScannerOnly}
modes = []string{utils.ModeLocal, utils.ModeGRPCServer, utils.ModeHTTPServer, utils.ModeScannerOnly}
severities = []string{utils.CRITICAL, utils.HIGH, utils.MEDIUM, utils.LOW}
)

Expand All @@ -45,13 +45,13 @@ var (
port = flag.String("port", "", "Port for grpc server")
output = flag.String("output", utils.TableOutput, "Output format: json or table")
quiet = flag.Bool("quiet", false, "Don't display any output in stdout")
consoleUrl = flag.String("console-url", "", "Deepfence Management Console URL")
consoleURL = flag.String("console-url", "", "Deepfence Management Console URL")
consolePort = flag.Int("console-port", 443, "Deepfence Management Console Port")
vulnerabilityScan = flag.Bool("vulnerability-scan", false, "Publish SBOM to Deepfence Management Console and run Vulnerability Scan")
deepfenceKey = flag.String("deepfence-key", "", "Deepfence key for auth")
source = flag.String("source", "", "Image name (nginx:latest) or directory (dir:/)")
scanType = flag.String("scan-type", "base,java,python,ruby,php,javascript,rust,rust-binary,golang,golang-binary,dotnet", "base,java,python,ruby,php,javascript,rust,rust-binary,golang,golang-binary,dotnet")
scanId = flag.String("scan-id", "", "(Optional) Scan id")
scanID = flag.String("scan-id", "", "(Optional) Scan id")
failOnCount = flag.Int("fail-on-count", -1, "Exit with status 1 if number of vulnerabilities found is >= this value (Default: -1)")
failOnCriticalCount = flag.Int("fail-on-critical-count", -1, "Exit with status 1 if number of critical vulnerabilities found is >= this value (Default: -1)")
failOnHighCount = flag.Int("fail-on-high-count", -1, "Exit with status 1 if number of high vulnerabilities found is >= this value (Default: -1)")
Expand All @@ -60,7 +60,7 @@ var (
failOnSeverityCount = flag.String("fail-on-count-severity", "", "Exit with status 1 if number of vulnerabilities of given severity found is >= fail-on-count")
failOnScore = flag.Float64("fail-on-score", -1, "Exit with status 1 if cumulative CVE score is >= this value (Default: -1)")
maskCveIds = flag.String("mask-cve-ids", "", "Comma separated cve id's to mask. Example: \"CVE-2019-9168,CVE-2019-9169\"")
c_runtime = flag.String("container-runtime", "auto", "container runtime to be used can be one of "+strings.Join(supportedRuntime, "/"))
cRuntime = flag.String("container-runtime", "auto", "container runtime to be used can be one of "+strings.Join(supportedRuntime, "/"))
severity = flag.String("severity", "", "Filter Vulnerabilities by severity, can be one or comma separated values of "+strings.Join(severities, "/"))
systemBin = flag.Bool("system-bin", false, "use system tools")
debug = flag.Bool("debug", false, "show debug logs")
Expand Down Expand Up @@ -135,12 +135,12 @@ func main() {

// no need to determine runtime if local directory
if !strings.HasPrefix(*source, "dir:") {
if *c_runtime != "auto" {
if !utils.Contains(supportedRuntime, *c_runtime) {
log.Fatalf("unsupported runtime has to be one of %s", strings.Join(supportedRuntime, "/"))
if *cRuntime != "auto" {
if !utils.Contains(supportedRuntime, *cRuntime) {
log.Panicf("unsupported runtime has to be one of %s", strings.Join(supportedRuntime, "/"))
}
containerRuntime = *c_runtime
switch *c_runtime {
containerRuntime = *cRuntime
switch *cRuntime {
case vc.DOCKER:
endpoint = vc.DOCKER_SOCKET_URI
case vc.CONTAINERD:
Expand All @@ -164,13 +164,13 @@ func main() {
Port: *port,
Output: *output,
Quiet: *quiet,
ConsoleURL: *consoleUrl,
ConsoleURL: *consoleURL,
ConsolePort: strconv.Itoa(*consolePort),
DeepfenceKey: *deepfenceKey,
Source: *source,
ScanType: *scanType,
VulnerabilityScan: *vulnerabilityScan,
ScanId: *scanId,
ScanID: *scanID,
FailOnScore: *failOnScore,
FailOnCount: *failOnCount,
FailOnCriticalCount: *failOnCriticalCount,
Expand Down Expand Up @@ -209,15 +209,15 @@ func main() {
switch *mode {
case utils.ModeLocal:
RunOnce(config)
case utils.ModeGrpcServer:
case utils.ModeGRPCServer:
err := sbom.RunGrpcServer(PluginName, config)
if err != nil {
log.Fatalf("error running grpc server: %v", err)
log.Panicf("error running grpc server: %v", err)
}
case utils.ModeHttpServer:
err := sbom.RunHttpServer(config)
case utils.ModeHTTPServer:
err := sbom.RunHTTPServer(config)
if err != nil {
log.Fatalf("error running http server: %v", err)
log.Panicf("error running http server: %v", err)
}
case utils.ModeScannerOnly:
r := router.New()
Expand All @@ -226,8 +226,8 @@ func main() {
*port = "8001"
}
log.Infof("listen on port: %s", *port)
log.Fatal(r.Run(":" + *port))
log.Panic(r.Run(":" + *port))
default:
log.Fatalf("unsupported mode %s", *mode)
log.Panicf("unsupported mode %s", *mode)
}
}
48 changes: 24 additions & 24 deletions output/output.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,11 @@ type JobStatus struct {
}

const (
IN_PROGRESS = "IN_PROGRESS"
COMPLETE = "COMPLETE"
ABORT = "ABORT"
CANCELLED = "CANCELLED"
ERROR = "ERROR"
StatusInProgress = "IN_PROGRESS"
StatusComplete = "COMPLETE"
StatusAbort = "ABORT"
StatisCancelled = "CANCELLED"
StatusError = "ERROR"
)

func NewPublisher(config utils.Config) (*Publisher, error) {
Expand All @@ -49,8 +49,8 @@ func NewPublisher(config utils.Config) (*Publisher, error) {
}, nil
}

func (p *Publisher) SetScanId(scanId string) {
p.config.ScanId = scanId
func (p *Publisher) SetScanID(scanID string) {
p.config.ScanID = scanID
}

func (p *Publisher) SendReport() {
Expand All @@ -71,9 +71,9 @@ func (p *Publisher) SendReport() {
if !(strings.HasPrefix(p.config.Source, "dir:") || (p.config.Source == ".")) {
image := map[string]interface{}{
"docker_image_name_with_tag": p.config.Source,
"docker_image_id": p.config.ImageId,
"node_id": p.config.ImageId,
"node_name": p.config.ImageId,
"docker_image_id": p.config.ImageID,
"node_id": p.config.ImageID,
"node_name": p.config.ImageID,
"node_type": p.config.NodeType,
}
s := strings.Split(p.config.Source, ":")
Expand All @@ -83,7 +83,7 @@ func (p *Publisher) SendReport() {
}
containerImageEdge := map[string]interface{}{
"source": p.config.HostName,
"destinations": p.config.ImageId,
"destinations": p.config.ImageID,
}
report.ContainerImageBatch = []map[string]interface{}{image}
report.ContainerImageEdgeBatch = []map[string]interface{}{containerImageEdge}
Expand Down Expand Up @@ -111,7 +111,7 @@ func (p *Publisher) StartScan() string {
ScanConfig: []dsc.ModelVulnerabilityScanConfigLanguage{},
}

nodeIds := dsc.ModelNodeIdentifier{NodeId: p.config.NodeId, NodeType: "image"}
nodeIds := dsc.ModelNodeIdentifier{NodeId: p.config.NodeID, NodeType: "image"}
if strings.HasPrefix(p.config.Source, "dir:") || (p.config.Source == ".") {
nodeIds.NodeType = "host"
}
Expand Down Expand Up @@ -139,7 +139,7 @@ func (p *Publisher) StartScan() string {

func (p *Publisher) PublishScanStatusMessage(message string, status string) {
data := dsc.IngestersVulnerabilityScanStatus{}
data.SetScanId(p.config.ScanId)
data.SetScanId(p.config.ScanID)
data.SetScanStatus(status)
data.SetScanMessage(message)

Expand Down Expand Up @@ -190,18 +190,18 @@ func (p *Publisher) RunVulnerabilityScan(sbom []byte) {
err := p.SendSbomToConsole(sbom, true)
if err != nil {
p.PublishScanError(err.Error())
log.Error(p.config.ScanId, " ", err.Error())
log.Error(p.config.ScanID, " ", err.Error())
}
}

func (p *Publisher) SendSbomToConsole(sbom []byte, skipScan bool) error {
data := dsc.UtilsScanSbomRequest{}
data.SetImageName(p.config.NodeId)
data.SetImageId(p.config.ImageId)
data.SetScanId(p.config.ScanId)
data.SetImageName(p.config.NodeID)
data.SetImageId(p.config.ImageID)
data.SetScanId(p.config.ScanID)
data.SetKubernetesClusterName(p.config.KubernetesClusterName)
data.SetHostName(p.config.HostName)
data.SetNodeId(p.config.NodeId)
data.SetNodeId(p.config.NodeID)
data.SetNodeType(p.config.NodeType)
data.SetScanType(p.config.ScanType)
data.SetContainerName(p.config.ContainerName)
Expand All @@ -221,10 +221,10 @@ func (p *Publisher) SendSbomToConsole(sbom []byte, skipScan bool) error {
float64(len(sbom))/1000.0/1000.0, float64(out.Len())/1000.0/1000.0)

bb := out.Bytes()
c_sbom := make([]byte, base64.StdEncoding.EncodedLen(len(bb)))
base64.StdEncoding.Encode(c_sbom, bb)
cSBOM := make([]byte, base64.StdEncoding.EncodedLen(len(bb)))
base64.StdEncoding.Encode(cSBOM, bb)

data.SetSbom(string(c_sbom))
data.SetSbom(string(cSBOM))

req := p.client.Client().VulnerabilityAPI.IngestSbom(context.Background())
req = req.UtilsScanSbomRequest(data)
Expand All @@ -245,15 +245,15 @@ func (p *Publisher) SendScanResultToConsole(vulnerabilities []scanner.Vulnerabil

for _, v := range vulnerabilities {
n := dsc.NewIngestersVulnerability()
n.SetScanId(v.ScanId)
n.SetScanId(v.ScanID)
n.SetCveAttackVector(v.CveAttackVector)
n.SetCveCausedByPackage(v.CveCausedByPackage)
n.SetCveCausedByPackagePath(v.CveCausedByPackagePath)
n.SetCveContainerLayer(v.CveContainerLayer)
n.SetCveCvssScore(float32(v.CveCvssScore))
n.SetCveDescription(v.CveDescription)
n.SetCveFixedIn(v.CveFixedIn)
n.SetCveId(v.CveId)
n.SetCveId(v.CveID)
n.SetCveLink(v.CveLink)
n.SetCveOverallScore(float32(v.CveOverallScore))
n.SetCveSeverity(v.CveSeverity)
Expand Down Expand Up @@ -299,7 +299,7 @@ func TableOutput(report *[]scanner.VulnerabilityScanReport) error {
if r.CveCausedByPackage == "" {
r.CveCausedByPackage = r.CveCausedByPackagePath
}
table.Append([]string{r.CveId, r.CveSeverity, r.CveType, r.CveCausedByPackage, r.CveLink})
table.Append([]string{r.CveID, r.CveSeverity, r.CveType, r.CveCausedByPackage, r.CveLink})
}
table.Render()
return nil
Expand Down
Loading

0 comments on commit fd5412b

Please sign in to comment.