Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add graph for vulnerabilities over time and daily imports #7

Merged
merged 99 commits into from
Feb 13, 2024
Merged
Show file tree
Hide file tree
Changes from 88 commits
Commits
Show all changes
99 commits
Select commit Hold shift + click to select a range
efc8567
feat(dependencytrack): calc vuln like dptrack
ybelMekk Feb 1, 2024
9a475c4
Add vulnerability-related database tables
rbjornstad Feb 1, 2024
5d6de0b
WIP
ybelMekk Feb 4, 2024
c50532c
fix: values
ybelMekk Feb 5, 2024
8fb5648
uodate vulnerability scheme
ybelMekk Feb 5, 2024
9f675f0
add tests
ybelMekk Feb 5, 2024
ed1b434
Merge remote-tracking branch 'origin/rm_reconciler_state' into vuln_c…
ybelMekk Feb 6, 2024
5ce22ae
Use application status conditions to render user-friendly error messa…
kimtore Feb 5, 2024
f103e35
update(vulnerability): add tests
ybelMekk Feb 6, 2024
a9e44ea
Add vulnerabilityMetrics field to Team type
rbjornstad Feb 6, 2024
a706adb
Add VulnerabilityMetrics resolver to teamResolver
rbjornstad Feb 6, 2024
78e1022
Refactor resolver types in app and users packages
rbjornstad Feb 6, 2024
a505fda
Add .graphqlrc.yaml file with project configuration
rbjornstad Feb 6, 2024
696a0da
Add date range filter to vulnerabilityMetrics
rbjornstad Feb 6, 2024
0fab53b
Update vulnerability metrics function signature
rbjornstad Feb 6, 2024
0eddf79
Update project ID type in VulnerabilityMetrics
rbjornstad Feb 6, 2024
264ca6d
update(vulnerability): update db
ybelMekk Feb 7, 2024
24c5731
Refactor resolver types in app, github_repo, and users
rbjornstad Feb 7, 2024
4781acc
Update vulnerability SQL queries and vulnerability updater
rbjornstad Feb 7, 2024
e05dd90
Merge remote-tracking branch 'origin/rm_reconciler_state' into app_co…
kimtore Feb 7, 2024
29f3217
Update vulnerabilityMetrics return type to non-null
rbjornstad Feb 7, 2024
8790195
add(main): setup_local vulns for devteam
ybelMekk Feb 7, 2024
19ba249
Merge remote-tracking branch 'origin/rm_reconciler_state' into app_co…
kimtore Feb 7, 2024
bacb71d
Revert "Upgrade to Go 1.22"
kimtore Feb 7, 2024
4066455
make pubsub requirement optional for setup-local
kimtore Feb 7, 2024
b63684a
make pubsub requirement optional for setup-local
kimtore Feb 7, 2024
e72c3b9
Merge remote-tracking branch 'origin/rm_reconciler_state' into app_co…
kimtore Feb 7, 2024
1a6332c
add(main): vuln config
ybelMekk Feb 7, 2024
f26d8f0
Merge branch 'app_conditions' into vuln_count
rbjornstad Feb 7, 2024
dc96109
Revert "Merge branch 'app_conditions' into vuln_count"
rbjornstad Feb 7, 2024
684066b
Merge branch 'main' into vuln_count
rbjornstad Feb 7, 2024
25c4853
Fix import statement in main.go
rbjornstad Feb 7, 2024
279e1a0
initial commit of GitHub workflows
christeredvartsen Feb 7, 2024
a5c9734
remove dep
christeredvartsen Feb 7, 2024
728ce00
Revert "Revert "Merge branch 'app_conditions' into vuln_count""
rbjornstad Feb 7, 2024
acc2aa4
Add DeleteAllReconcilerResources mock function
rbjornstad Feb 7, 2024
724944e
fix(vuln): clean up vulnerability updater and tests
ybelMekk Feb 7, 2024
97ca3e5
Add VulnerabilityMetricsDateRangeForTeam resolver
rbjornstad Feb 7, 2024
3a4e3c7
Refactor vuln metrics graph
rbjornstad Feb 8, 2024
afb2b4a
fix(vuln): extend interface
ybelMekk Feb 8, 2024
e1d22f1
add(vuln): g func to updater
ybelMekk Feb 8, 2024
fb447a9
initial commit of GitHub workflows
christeredvartsen Feb 7, 2024
828a793
remove dep
christeredvartsen Feb 7, 2024
050de49
specify go version
christeredvartsen Feb 7, 2024
f1ce80c
use before_install to install latest golang version prior to asdf ins…
christeredvartsen Feb 7, 2024
feb29b6
try without using the setup-go action
christeredvartsen Feb 7, 2024
97cfc23
set the version after installing
christeredvartsen Feb 7, 2024
d5e9179
no need to run helm lint yet
christeredvartsen Feb 7, 2024
665ed66
don't depend on pubsub emulator in tests
christeredvartsen Feb 7, 2024
3250659
fix incorrect error types in the tests
christeredvartsen Feb 7, 2024
b26bf60
remove for now as this never fails
christeredvartsen Feb 7, 2024
1576776
use new field, and ignore deprecated error for now
christeredvartsen Feb 7, 2024
a69357f
add caching
christeredvartsen Feb 7, 2024
49d7316
no need for this anymore
christeredvartsen Feb 7, 2024
18d2c54
name step
christeredvartsen Feb 7, 2024
d371989
dump go version
christeredvartsen Feb 7, 2024
5068930
setup asdf
christeredvartsen Feb 7, 2024
1e6ca4f
build and push image
christeredvartsen Feb 7, 2024
53c70e6
try large runner
christeredvartsen Feb 7, 2024
5aa04a2
test pubsub messages
christeredvartsen Feb 8, 2024
337784c
this has been done
christeredvartsen Feb 8, 2024
bb5dac2
add resolvers for optional target service account and team instead of…
christeredvartsen Feb 8, 2024
0210dfc
make fields optional
christeredvartsen Feb 8, 2024
ec9874a
Clean up Naiserator error state handling
kimtore Feb 8, 2024
0d1b3ac
Update dependencies in go.mod and go.sum files
rbjornstad Feb 8, 2024
ec9b462
Add VulnerabilityMetricsMaxDate query
rbjornstad Feb 8, 2024
6ae90c2
Add teamSlug parameter to VulnerabilityMetricsMaxDate
rbjornstad Feb 9, 2024
ea8198a
Refactor vulnerability metrics queries to use project ID instead of t…
rbjornstad Feb 9, 2024
2d18f62
Update vulnerability metrics query parameters
rbjornstad Feb 9, 2024
be423f6
add(vuln): fix logic for upsert, eventually consistent is ok
ybelMekk Feb 10, 2024
fab1993
add(vuln): missing Unassigned
ybelMekk Feb 11, 2024
3366b78
fix(vuln): rename function
ybelMekk Feb 12, 2024
f399879
fix(vuln): fix failing tests
ybelMekk Feb 12, 2024
daeabe1
Add support for querying vulnerability metrics by environment
rbjornstad Feb 12, 2024
49cf424
Update protoc-gen-go to v1.32.0
rbjornstad Feb 12, 2024
be00f94
Merge branch 'main' into vuln_count
rbjornstad Feb 12, 2024
1b50413
update go version
rbjornstad Feb 12, 2024
80debbf
update(vuln): tests
ybelMekk Feb 12, 2024
09021e6
Update dependency versions in go.mod
rbjornstad Feb 12, 2024
2dcddd9
test(vuln): remove print
ybelMekk Feb 12, 2024
2dd8ce6
fix(vuln): staticcheck errors
ybelMekk Feb 12, 2024
fd9442f
Add imports and error handling in vulnerability_updater_test.go
rbjornstad Feb 12, 2024
2fdd6b9
Fix variable declaration in seedVulnerabilities function
rbjornstad Feb 12, 2024
26696b8
Update vulnerability_metrics_updater.go to import the "time" package
rbjornstad Feb 12, 2024
a101b68
Update dependencytrack.go
rbjornstad Feb 12, 2024
cac551a
Refactor variable declaration in fake.go
rbjornstad Feb 12, 2024
e005923
Add missing test case for updater
rbjornstad Feb 12, 2024
8a3d6d3
Refactor vulnerability_updater.go
rbjornstad Feb 12, 2024
58d65a0
Move vuln metric import to dependencyTrackConfig struct
rbjornstad Feb 13, 2024
fb20940
Refactor runVulnerabilityUpdater
rbjornstad Feb 13, 2024
fd0bcad
Update vulnerabilityMetrics date arguments to non-nullable.
rbjornstad Feb 13, 2024
6d83ff8
Refactor project ID variable names in Dependencytrack client
rbjornstad Feb 13, 2024
44f411d
Add recover function to handle panics in vulnerability updater
rbjornstad Feb 13, 2024
90ebd0a
Add github.com/sourcegraph/conc v0.3.0 as a required dependency***
rbjornstad Feb 13, 2024
de5e050
Add .env to .gitignore
rbjornstad Feb 13, 2024
e6f04c1
Use github.com/sourcegraph/conc/pool in upsert
rbjornstad Feb 13, 2024
7c3daae
remove duplicate
christeredvartsen Feb 13, 2024
d7d5335
remove newline
christeredvartsen Feb 13, 2024
5b92e21
minor changes before merge
christeredvartsen Feb 13, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/pr.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -42,4 +42,4 @@ jobs:
run: |
make fmt
make generate
git diff --exit-code --name-only
git diff --exit-code --name-only
4 changes: 4 additions & 0 deletions .graphqlrc.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
projects:
default:
schema:
- ./internal/graph/graphgls/*.graphqls
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ local:
env bash -c 'source local.env; go run ./cmd/api'

test:
go test ./...
go test -cover ./...

check: staticcheck vulncheck deadcode

Expand Down
68 changes: 67 additions & 1 deletion cmd/setup_local/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ import (
"time"
"unicode"

"github.com/jackc/pgx/v5/pgtype"

"cloud.google.com/go/pubsub"
"github.com/google/uuid"
"github.com/nais/api/internal/database"
Expand All @@ -36,10 +38,16 @@ type seedConfig struct {
NumTeams *int
NumOwnersPerTeam *int
NumMembersPerTeam *int
VulnSeed *VulnSeed
ForceSeed *bool
ProvisionPubSub *bool
}

type VulnSeed struct {
NumVulnAppsForTeam *int
NumVulnPerApp *int
}

func newSeedConfig(ctx context.Context) (*seedConfig, error) {
cfg := &seedConfig{}
err := envconfig.Process(ctx, cfg)
Expand All @@ -53,6 +61,8 @@ func newSeedConfig(ctx context.Context) (*seedConfig, error) {
cfg.NumMembersPerTeam = flag.Int("members", 10, "number of members per team")
cfg.ForceSeed = flag.Bool("force", false, "seed regardless of existing database content")
cfg.ProvisionPubSub = flag.Bool("provision_pub_sub", true, "set up pubsub credentials")
cfg.VulnSeed.NumVulnAppsForTeam = flag.Int("vuln-apps", 5, "number of vulnerable apps per team")
cfg.VulnSeed.NumVulnPerApp = flag.Int("vuln-per-app", 10, "number of vulnerabilities per app")
flag.Parse()

return cfg, nil
Expand Down Expand Up @@ -83,7 +93,7 @@ func run(ctx context.Context, cfg *seedConfig, log logrus.FieldLogger) error {
ctx, cancel := context.WithCancel(ctx)
defer cancel()

if false {
if *cfg.ProvisionPubSub {
if err := os.Setenv("PUBSUB_EMULATOR_HOST", "localhost:3004"); err != nil {
return err
}
Expand Down Expand Up @@ -225,6 +235,11 @@ func run(ctx context.Context, cfg *seedConfig, log logrus.FieldLogger) error {
}
}

err = seedVulnerabilities(ctx, *cfg, dbtx, devteam, log)
if err != nil {
return err
}

err = dbtx.SetTeamMemberRole(ctx, devUser.ID, devteam.Slug, gensql.RoleNameTeamowner)
if err != nil {
return err
Expand Down Expand Up @@ -269,6 +284,57 @@ func run(ctx context.Context, cfg *seedConfig, log logrus.FieldLogger) error {
return nil
}

func seedVulnerabilities(ctx context.Context, cfg seedConfig, dbtx database.Database, team *database.Team, log logrus.FieldLogger) error {
numbOfErrors := 0
for j := 0; j < *cfg.VulnSeed.NumVulnAppsForTeam; j++ {
appName := fmt.Sprintf("app-%d", j)
projectId := uuid.New()
err := dbtx.CreateDependencytrackProject(ctx, gensql.CreateDependencytrackProjectParams{
Environment: "dev",
TeamSlug: team.Slug,
App: appName,
Projectid: projectId,
})
if err != nil {
return err
}

var vulnbBatch []gensql.VulnerabilityMetricsUpsertParams
date := time.Now()
var critical int
var high int
var medium int
var low int
var unassigned int
for k := 0; k < *cfg.VulnSeed.NumVulnPerApp; k++ {
critical = rand.Intn(10)
high = rand.Intn(10)
medium = rand.Intn(10)
low = rand.Intn(10)
unassigned = rand.Intn(10)
vulnbBatch = append(vulnbBatch, gensql.VulnerabilityMetricsUpsertParams{
Date: pgtype.Date{Time: date.AddDate(0, 0, -k).UTC(), Valid: true},
DependencytrackProjectID: projectId,
RiskScore: float64((critical * 10) + (high * 5) + (medium * 3) + (low * 1) + (unassigned * 5)),
Critical: int32(critical),
High: int32(high),
Medium: int32(medium),
Low: int32(low),
Unassigned: int32(unassigned),
})
}

dbtx.VulnerabilityMetricsUpsert(ctx, vulnbBatch).Exec(func(i int, err error) {
if err != nil {
log.Errorf("error updating vulnerability metrics for team %s: %v", team.Slug, err)
numbOfErrors++
}
})
}
log.Infof("vulnerability metrics for team %s seeded", team.Slug)
return nil
}

func teamName() string {
letters := []byte("abcdefghijklmnopqrstuvwxyz")
b := make([]byte, 10)
Expand Down
61 changes: 61 additions & 0 deletions data/k8s/dev/devteam/deploy-canary.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
apiVersion: nais.io/v1alpha1
kind: Application
metadata:
annotations:
deploy.nais.io/client-version: 2023-01-23-7071cd7
nais.io/deploymentCorrelationID: f8c04f82-6a84-4a8e-9f8b-563b5894d0cf
nais.io/skipDeploymentMessage: "true"
creationTimestamp: "2023-01-20T10:51:47Z"
finalizers:
- naiserator.nais.io/finalizer
generation: 407981
name: nais-deploy-canary
resourceVersion: "3701834314"
uid: 91ba6c9d-0199-4123-aff6-aa27ce5d2056
spec:
env:
- name: DEPLOY_START
value: "1704981602000000000"
image: ghcr.io/nais/testapp/testapp:2020-02-25-f61e7b7
liveness:
path: /ping
port: 8080
prometheus:
enabled: true
path: /metrics
readiness:
path: /ping
replicas:
max: 1
min: 1
resources:
limits:
cpu: 250m
memory: 256Mi
requests:
cpu: 100m
memory: 128Mi
skipCaBundle: true
status:
conditions:
- lastTransitionTime: "2024-01-11T14:00:04Z"
message: complete
reason: RolloutComplete
status: "True"
type: Ready
- lastTransitionTime: "2024-01-11T14:00:04Z"
message: complete
reason: RolloutComplete
status: "False"
type: Stalled
- lastTransitionTime: "2024-01-11T14:00:04Z"
message: complete
reason: RolloutComplete
status: "False"
type: Reconciling
correlationID: f8c04f82-6a84-4a8e-9f8b-563b5894d0cf
deploymentRolloutStatus: complete
rolloutCompleteTime: 1704981612597504354
synchronizationHash: 7fc5fa83f2ae4eaa
synchronizationState: RolloutComplete
synchronizationTime: 1704981603962494011
4 changes: 3 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ require (
github.com/jackc/pgx/v5 v5.5.3
github.com/joho/godotenv v1.5.1
github.com/lithammer/fuzzysearch v1.1.8
github.com/nais/dependencytrack v0.0.0-20240131225920-a6a8df4c0ad2
github.com/nais/dependencytrack v0.0.0-20240208124913-513b3ad1d961
github.com/nais/liberator v0.0.0-20240208114703-a4ddc1dd2ffa
github.com/patrickmn/go-cache v2.1.0+incompatible
github.com/pressly/goose/v3 v3.18.0
Expand Down Expand Up @@ -80,6 +80,7 @@ require (
github.com/evanphx/json-patch/v5 v5.9.0 // indirect
github.com/fatih/structtag v1.2.0 // indirect
github.com/felixge/httpsnoop v1.0.4 // indirect
github.com/frankban/quicktest v1.14.6 // indirect
github.com/fsnotify/fsnotify v1.7.0 // indirect
github.com/go-jose/go-jose/v3 v3.0.1 // indirect
github.com/go-logr/logr v1.4.1 // indirect
Expand Down Expand Up @@ -147,6 +148,7 @@ require (
github.com/prometheus/procfs v0.12.0 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
github.com/riza-io/grpc-go v0.2.0 // indirect
github.com/rogpeppe/go-internal v1.12.0 // indirect
github.com/rs/zerolog v1.30.0 // indirect
github.com/russross/blackfriday/v2 v2.1.0 // indirect
github.com/sagikazarmark/locafero v0.3.0 // indirect
Expand Down
15 changes: 9 additions & 6 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ github.com/coreos/go-oidc/v3 v3.9.0/go.mod h1:rTKz2PYwftcrtoCzV5g5kvfJoWcm0Mk8AF
github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
github.com/cpuguy83/go-md2man/v2 v2.0.3 h1:qMCsGGgs+MAzDFyp9LpAe1Lqy/fY/qCovCm0qnXZOBM=
github.com/cpuguy83/go-md2man/v2 v2.0.3/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/cubicdaiya/gonp v1.0.4 h1:ky2uIAJh81WiLcGKBVD5R7KsM/36W6IqqTy6Bo6rGws=
github.com/cubicdaiya/gonp v1.0.4/go.mod h1:iWGuP/7+JVTn02OWhRemVbMmG1DOUnmrGTYYACpOI0I=
github.com/cznic/mathutil v0.0.0-20181122101859-297441e03548 h1:iwZdTE0PVqJCos1vaoKsclOGD3ADKpshg3SRtYBbwso=
Expand Down Expand Up @@ -162,8 +163,8 @@ github.com/fatih/structtag v1.2.0 h1:/OdNE99OxoI/PqaW/SuSK9uxxT3f/tcSZgon/ssNSx4
github.com/fatih/structtag v1.2.0/go.mod h1:mBJUNpUnHmRKrKlQQlmCrh5PuhftFbNv8Ys4/aAZl94=
github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=
github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
github.com/frankban/quicktest v1.14.4 h1:g2rn0vABPOOXmZUj+vbmUp0lPoXEMuhTpIluN0XL9UY=
github.com/frankban/quicktest v1.14.4/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA=
github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM=
github.com/go-chi/chi/v5 v5.0.11 h1:BnpYbFZ3T3S1WMpD79r7R5ThWX40TaFB7L31Y8xqSwA=
Expand Down Expand Up @@ -400,8 +401,8 @@ github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f h1:KUppIJq7/+SVif2QVs3tOP0zanoHgBEVAwHxUSIzRqU=
github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
github.com/nais/dependencytrack v0.0.0-20240131225920-a6a8df4c0ad2 h1:4LNq0LISYLyJSC3hAxNCe1YM0QU7y5QiAbLIMeXVZ7o=
github.com/nais/dependencytrack v0.0.0-20240131225920-a6a8df4c0ad2/go.mod h1:zC59yj0La1TS291o/9XSVZ0XAY9UlJS6pUFD3ouHmjU=
github.com/nais/dependencytrack v0.0.0-20240208124913-513b3ad1d961 h1:FtfEwEQq2hWEZFmg3F8Ix9vq6x8o0PF4bEvCn7qwCxw=
github.com/nais/dependencytrack v0.0.0-20240208124913-513b3ad1d961/go.mod h1:zC59yj0La1TS291o/9XSVZ0XAY9UlJS6pUFD3ouHmjU=
github.com/nais/liberator v0.0.0-20240208114703-a4ddc1dd2ffa h1:AkBC8XlZH+VvZRrHHnjiaTl/mkDRYNMRq6qpfZslUlk=
github.com/nais/liberator v0.0.0-20240208114703-a4ddc1dd2ffa/go.mod h1:cWThp1WBBbkRFhMI2DQMvBTTEN+6GPzmmh+Xjv8vffE=
github.com/onsi/ginkgo/v2 v2.14.0 h1:vSmGj2Z5YPb9JwCWT6z6ihcUvDhuXLc3sJiqd3jMKAY=
Expand Down Expand Up @@ -436,6 +437,7 @@ github.com/pingcap/log v1.1.0 h1:ELiPxACz7vdo1qAvvaWJg1NrYFoY6gqAh/+Uo6aXdD8=
github.com/pingcap/log v1.1.0/go.mod h1:DWQW5jICDR7UJh4HtxXSM20Churx4CQL0fwL/SoOSA4=
github.com/pingcap/tidb/pkg/parser v0.0.0-20231103154709-4f00ece106b1 h1:SwGY3zMnK4wO85vvRIqrR3Yh6VpIC9pydG0QNOUPHCY=
github.com/pingcap/tidb/pkg/parser v0.0.0-20231103154709-4f00ece106b1/go.mod h1:yRkiqLFwIqibYg2P7h4bclHjHcJiIFRLKhGRyBcKYus=
github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
Expand All @@ -461,8 +463,9 @@ github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qq
github.com/riza-io/grpc-go v0.2.0 h1:2HxQKFVE7VuYstcJ8zqpN84VnAoJ4dCL6YFhJewNcHQ=
github.com/riza-io/grpc-go v0.2.0/go.mod h1:2bDvR9KkKC3KhtlSHfR3dAXjUMT86kg4UfWFyVGWqi8=
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M=
github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA=
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8=
github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4=
github.com/rs/cors v1.10.1 h1:L0uuZVXIKlI1SShY2nhFfo44TYvDPQ1w4oFkUJNfhyo=
github.com/rs/cors v1.10.1/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU=
github.com/rs/xid v1.5.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg=
Expand Down
5 changes: 4 additions & 1 deletion internal/cmd/api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import (
"github.com/nais/api/internal/thirdparty/hookd"
fakehookd "github.com/nais/api/internal/thirdparty/hookd/fake"
"github.com/nais/api/internal/usersync"
"github.com/nais/api/internal/vulnerability"
"github.com/sethvargo/go-envconfig"
"github.com/sirupsen/logrus"
"golang.org/x/oauth2/google"
Expand Down Expand Up @@ -153,7 +154,7 @@ func run(ctx context.Context, cfg *Config, log logrus.FieldLogger) error {
pubsubTopic := pubsubClient.Topic("nais-api")

var hookdClient graph.HookdClient
var dependencyTrackClient graph.DependencytrackClient
var dependencyTrackClient vulnerability.DependencytrackClient
if cfg.WithFakeClients {
hookdClient = fakehookd.New()
dependencyTrackClient = faketrack.New()
Expand Down Expand Up @@ -214,6 +215,8 @@ func run(ctx context.Context, cfg *Config, log logrus.FieldLogger) error {
return costUpdater(ctx, cfg, db, log)
})

wg.Go(func() error { return vulnerabilityMetricUpdater(ctx, cfg, db, k8sClient, dependencyTrackClient, log) })

authHandler, err := setupAuthHandler(cfg.OAuth, db, log)
if err != nil {
return err
Expand Down
3 changes: 3 additions & 0 deletions internal/cmd/api/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,9 @@ type Config struct {
// ResourceUtilization is the configuration for the resource utilization service
ResourceUtilizationImportEnabled bool `env:"RESOURCE_UTILIZATION_IMPORT_ENABLED"`

// VulnerabilityMetricsImportEnabled is the configuration for the vulnerability metrics service
VulnerabilityMetricsImportEnabled bool `env:"VULNERABILITY_METRICS_IMPORT_ENABLED"`
rbjornstad marked this conversation as resolved.
Show resolved Hide resolved

// WithFakeKubernetes When set to true, the api will use a fake kubernetes client.
WithFakeClients bool `env:"WITH_FAKE_CLIENTS"`

Expand Down
54 changes: 54 additions & 0 deletions internal/cmd/api/vulnerability_metrics_updater.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package api

import (
"context"
"time"

"github.com/nais/api/internal/database"
"github.com/nais/api/internal/k8s"
"github.com/nais/api/internal/vulnerability"
"github.com/sirupsen/logrus"
)

const (
vulnerabilityUpdateSchedule = time.Hour
)

func vulnerabilityMetricUpdater(ctx context.Context, cfg *Config, db database.Database, k8sClient *k8s.Client, dTrackClient vulnerability.DependencytrackClient, log logrus.FieldLogger) error {
if !cfg.VulnerabilityMetricsImportEnabled {
log.Warningf(`vulnerability metrics import is not enabled. Enable by setting the "VULNERABILITY_METRICS_IMPORT_ENABLED" environment variable to "true"`)
return nil
}

vulnerabilityMetricUpdater := vulnerability.NewMetricUpdater(k8sClient, dTrackClient, db, log)
if err := runVulnerabilityUpdater(ctx, vulnerabilityMetricUpdater, log.WithField("task", "vulnerability_updater")); err != nil {
log.WithError(err).Errorf("error in vulnerability updater")
}
return nil
}

func runVulnerabilityUpdater(ctx context.Context, updater *vulnerability.Updater, log logrus.FieldLogger) error {
ticker := time.NewTicker(time.Second)
defer ticker.Stop()

rbjornstad marked this conversation as resolved.
Show resolved Hide resolved
for {
select {
case <-ctx.Done():
return ctx.Err()
case <-ticker.C:
ticker.Reset(vulnerabilityUpdateSchedule * 24) // schedule next run, same time next day
start := time.Now()
log.Infof("start scheduled vulnerability update run")
rows, err := updater.UpdateVulnerabilityMetrics(ctx)
if err != nil {
log = log.WithError(err)
}
log.
WithFields(logrus.Fields{
"rows_upserted": rows,
"duration": time.Since(start),
}).
Infof("finished scheduled vulnerability metrics update run")
}
}
}
rbjornstad marked this conversation as resolved.
Show resolved Hide resolved
1 change: 1 addition & 0 deletions internal/database/database.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ type Database interface {
SessionRepo
TeamRepo
UserRepo
VulnerabilityMetricsRepo

Transaction(ctx context.Context, fn DatabaseTransactionFunc) error
}
Expand Down
Loading