diff --git a/docs/v0s_console_migration.md b/docs/v0s_console_migration.md index 6c3cf8926..29a7d5846 100644 --- a/docs/v0s_console_migration.md +++ b/docs/v0s_console_migration.md @@ -378,15 +378,26 @@ query GlobalVulnerabilityPage($first: Int, $after: Cursor, $last: Int, $before: } ``` -### CVE-only request cost - -The global query above does not fetch a findings page (`ListFindings`). Adding -`summary` uses `GetSummary` independently and still does not fetch findings. -Selecting parent `nodes`, `edges`, `pageInfo` or `facets` keeps the existing -findings-page loading. In particular, package-type facets need the -`PackageTypeCounts` from `ListFindings`; they are not replaced with empty facets. +### Findings-page dependencies + +The same loading rules apply to `vulnerabilityFindings` on Query, Team, +TeamEnvironment, Application and Job. Selecting only `summary`, `vulnerabilities`, +`affectedWorkloads` or `__typename` does not fetch the parent findings page +(`ListFindings`). `summary` uses `GetSummary`, `vulnerabilities` uses +`ListVulnerabilities`, and `affectedWorkloads` uses workload overviews. +Parent pagination arguments are optional: `first: 1` is not necessary for +aggregate-only queries, and omitting it does not fetch a default findings page. + +Selecting parent `nodes`, `edges`, `pageInfo` or `facets` retains findings-page +loading. In particular, package-type facets need `PackageTypeCounts` from +`ListFindings`; they are not replaced with empty facets. CLI team summaries +that request both `summary` and `facets` therefore still need findings. Aliases, fragments and `@skip`/`@include` follow the effective field selection. -Scoped findings fields retain their existing loading behavior. + +Console CVE details select `summary` and `affectedWorkloads`, then finding rows +inside each returned application or job. Those per-workload finding pages remain +necessary; only the redundant parent page is skipped. Nested `nodes` or +`pageInfo` do not force their ancestor connection to load a findings page. Authorization, current workload/image selection and parent argument/cursor validation still run even when the findings page is unused. The nested CVE @@ -394,17 +405,20 @@ connection retains its own cursor, bidirectional pagination and exact filtered total. This optimization requires only an API rollout, with no Console, GraphQL or v0s server change and no additional cursor restart. -To measure without tracing, use the same global GraphiQL query, variables and -page traversal before and after deployment, first without and then with -`summary`. Record client latency and Grafana counter deltas for -`ListFindings` and `ListVulnerabilities` over a bounded measurement window: -compare RPC counts and cumulative duration, not just duration per RPC. -These requests should contribute zero `ListFindings` calls after rollout; -`ListVulnerabilities` remains necessary. A mixed query selecting findings/facets -should still contribute findings calls. Counters aggregate all traffic, so use -a quiet window and record background traffic; the deltas cannot attribute -individual calls to GraphiQL. Do not promise a fixed latency reduction or treat -this as an optimization of `ListVulnerabilities` or workload inventory lookups. +To measure without tracing, compare the same global/team overview and CVE detail +queries, variables and page traversal before and after deployment. Summary-only +or CVE-list-only requests should contribute zero `ListFindings` calls. CVE details +should lose the parent findings-page call but retain requested workload pages; +mixed queries selecting parent findings/facets still need findings calls. +Record client latency, existing GraphQL field timing +(`Query/vulnerabilityFindings` or the corresponding scoped field), and Grafana +deltas for RPC counts and cumulative duration of `ListFindings` and +`ListVulnerabilities` over a bounded measurement window. +Counters aggregate all traffic, so use a quiet window and record background +traffic; the deltas cannot attribute individual calls to GraphiQL. +Fewer RPCs alone do not prove lower end-to-end latency. Do not promise a fixed +reduction or treat this as an optimization of `ListVulnerabilities` or inventory +lookups. Console can use `endCursor` for Next and `startCursor` for Previous with the same filter and order: @@ -1118,3 +1132,28 @@ available; Console must not present one as functional. Rolling Console back does not copy newer v0s assessments into v13s. Preserve assessment state; explicitly reconcile any data transfer instead of claiming consistency between independent models. + +### Remaining cutover coordination + +Merged changes are not evidence of deployment to every tenant. API +[#670](https://github.com/nais/api/pull/670) accepts workload overviews without +`total_count`; [nais/v0s#26](https://github.com/nais/v0s/pull/26) removes that field +and the deprecated workload-order shell, and optimizes vulnerability totals and +PageInfo probes. Retain the client-first rollout and rollback constraints above. +UNKNOWN ordering is already documented as first in ASC and last in DESC. + +[nais/console-frontend#797](https://github.com/nais/console-frontend/pull/797) +uses `V0S_VULNERABILITIES_ENABLED` for direct assessment writes. Coordinate it +with API's `v0s.suppressionsEnabled` per tenant, verify create/edit/delete, and +do not use legacy writes as fallback for a v0s view. + +CLI already consumes v0s findings, summaries and workload overviews through this +GraphQL contract. Keep those consumers compatible; source support does not by +itself establish CLI release adoption or completed user migration. + +Before full cutover, explicitly decide and communicate the future of +`nais_workload_vulnerabilities`, `nais_workload_vulnerabilities_kev`, +`nais_workload_vulnerabilities_priority` and `nais_workload_risk_score`, including +count/suppression semantics and update delay. Do not silently redefine existing +alerts or reintroduce priority/risk score merely to preserve old metric names. +This coordination is separate from skipping unused findings pages. diff --git a/internal/graph/helpers.go b/internal/graph/helpers.go index 7574a8750..31bc23940 100644 --- a/internal/graph/helpers.go +++ b/internal/graph/helpers.go @@ -3,6 +3,7 @@ package graph import ( "context" "maps" + "strings" "github.com/99designs/gqlgen/graphql" ) @@ -31,6 +32,19 @@ func getPreloadString(prefix, name string) string { return name } +func needsVulnerabilityFindingPage(ctx context.Context) bool { + for _, field := range getPreloads(ctx) { + switch field { + case "vulnerabilities", "summary", "affectedWorkloads", "__typename": + default: + if !strings.Contains(field, ".") { + return true + } + } + } + return false +} + func onlyAsksForPageInfoTotalCount(ctx context.Context) bool { preloads := make(map[string]struct{}) for _, preload := range getPreloads(ctx) { diff --git a/internal/graph/v0s.resolvers.go b/internal/graph/v0s.resolvers.go index dd0fca7b9..c1d0bfa5c 100644 --- a/internal/graph/v0s.resolvers.go +++ b/internal/graph/v0s.resolvers.go @@ -2,7 +2,6 @@ package graph import ( "context" - "strings" "github.com/nais/api/internal/graph/gengql" "github.com/nais/api/internal/graph/pagination" @@ -14,7 +13,7 @@ import ( ) func (r *applicationResolver) VulnerabilityFindings(ctx context.Context, obj *application.Application, filter *v0s.WorkloadVulnerabilityFindingsFilter, first *int, after *pagination.Cursor, last *int, before *pagination.Cursor, orderBy *v0s.VulnerabilityFindingOrder) (*v0s.VulnerabilityFindingConnection, error) { - return v0s.FindingsForWorkloads(ctx, v0s.WorkloadScope(obj), []workload.Workload{obj}, (*v0s.VulnerabilityFindingFilter)(filter), first, after, last, before, orderBy) + return v0s.FindingsForSelection(ctx, v0s.WorkloadScope(obj), []workload.Workload{obj}, nil, (*v0s.VulnerabilityFindingFilter)(filter), first, after, last, before, orderBy, needsVulnerabilityFindingPage(ctx)) } func (r *applicationResolver) VulnerabilityCoverage(ctx context.Context, obj *application.Application) (*v0s.VulnerabilityCoverage, error) { @@ -26,7 +25,7 @@ func (r *applicationResolver) VulnerabilityOverview(ctx context.Context, obj *ap } func (r *jobResolver) VulnerabilityFindings(ctx context.Context, obj *job.Job, filter *v0s.WorkloadVulnerabilityFindingsFilter, first *int, after *pagination.Cursor, last *int, before *pagination.Cursor, orderBy *v0s.VulnerabilityFindingOrder) (*v0s.VulnerabilityFindingConnection, error) { - return v0s.FindingsForWorkloads(ctx, v0s.WorkloadScope(obj), []workload.Workload{obj}, (*v0s.VulnerabilityFindingFilter)(filter), first, after, last, before, orderBy) + return v0s.FindingsForSelection(ctx, v0s.WorkloadScope(obj), []workload.Workload{obj}, nil, (*v0s.VulnerabilityFindingFilter)(filter), first, after, last, before, orderBy, needsVulnerabilityFindingPage(ctx)) } func (r *jobResolver) VulnerabilityCoverage(ctx context.Context, obj *job.Job) (*v0s.VulnerabilityCoverage, error) { @@ -56,17 +55,7 @@ func (r *queryResolver) VulnerabilityFindings(ctx context.Context, filter *v0s.V if err != nil { return nil, err } - includePage := false - for _, field := range getPreloads(ctx) { - switch field { - case "vulnerabilities", "summary", "__typename": - default: - if !strings.Contains(field, ".") { - includePage = true - } - } - } - return v0s.FindingsForSelection(ctx, v0s.Scope{}, selected, metadata, findings, first, after, last, before, orderBy, includePage) + return v0s.FindingsForSelection(ctx, v0s.Scope{}, selected, metadata, findings, first, after, last, before, orderBy, needsVulnerabilityFindingPage(ctx)) } func (r *queryResolver) Vulnerability(ctx context.Context, identifier string) (*v0s.Vulnerability, error) { @@ -87,7 +76,7 @@ func (r *teamResolver) VulnerabilityFindings(ctx context.Context, obj *team.Team metadata = &v0s.VulnerabilityWorkloadFilter{Environments: filter.Environments, Labels: filter.Labels} findings = &filter.VulnerabilityFindingFilter } - return v0s.FindingsForSelection(ctx, scope, selectTeamWorkloads(ctx, obj.Slug, workloadFilter), metadata, findings, first, after, last, before, orderBy, true) + return v0s.FindingsForSelection(ctx, scope, selectTeamWorkloads(ctx, obj.Slug, workloadFilter), metadata, findings, first, after, last, before, orderBy, needsVulnerabilityFindingPage(ctx)) } func (r *teamResolver) VulnerabilitySuppressions(ctx context.Context, obj *team.Team, filter *v0s.TeamVulnerabilitySuppressionsFilter, first *int, after *pagination.Cursor, last *int, before *pagination.Cursor) (*pagination.Connection[*v0s.VulnerabilitySuppression], error) { @@ -96,7 +85,7 @@ func (r *teamResolver) VulnerabilitySuppressions(ctx context.Context, obj *team. func (r *teamEnvironmentResolver) VulnerabilityFindings(ctx context.Context, obj *team.TeamEnvironment, filter *v0s.TeamEnvironmentVulnerabilityFindingsFilter, first *int, after *pagination.Cursor, last *int, before *pagination.Cursor, orderBy *v0s.VulnerabilityFindingOrder) (*v0s.VulnerabilityFindingConnection, error) { selected := selectTeamWorkloads(ctx, obj.TeamSlug, &workload.TeamWorkloadsFilter{Environments: []string{obj.EnvironmentName}}) - return v0s.FindingsForWorkloads(ctx, v0s.Scope{Team: obj.TeamSlug, Environment: obj.EnvironmentName}, selected, (*v0s.VulnerabilityFindingFilter)(filter), first, after, last, before, orderBy) + return v0s.FindingsForSelection(ctx, v0s.Scope{Team: obj.TeamSlug, Environment: obj.EnvironmentName}, selected, nil, (*v0s.VulnerabilityFindingFilter)(filter), first, after, last, before, orderBy, needsVulnerabilityFindingPage(ctx)) } func (r *teamEnvironmentResolver) VulnerabilitySuppressions(ctx context.Context, obj *team.TeamEnvironment, filter *v0s.TeamEnvironmentVulnerabilitySuppressionsFilter, first *int, after *pagination.Cursor, last *int, before *pagination.Cursor) (*pagination.Connection[*v0s.VulnerabilitySuppression], error) { diff --git a/internal/graph/v0s.resolvers_test.go b/internal/graph/v0s.resolvers_test.go index f1be1dfb7..12414c962 100644 --- a/internal/graph/v0s.resolvers_test.go +++ b/internal/graph/v0s.resolvers_test.go @@ -18,6 +18,8 @@ import ( "github.com/nais/api/internal/kubernetes" "github.com/nais/api/internal/kubernetes/fake" "github.com/nais/api/internal/kubernetes/watcher" + "github.com/nais/api/internal/slug" + "github.com/nais/api/internal/team" "github.com/nais/api/internal/v0s" "github.com/nais/api/internal/workload/application" "github.com/nais/api/internal/workload/job" @@ -35,6 +37,7 @@ type findingSelectionClient struct { manager *v0s.Manager findings, groups atomic.Int32 summaries, workloads atomic.Int32 + extraWorkloads []*protoapi.Workload } func (c *findingSelectionClient) checkSelector(selector *protoapi.WorkloadSelector) { @@ -43,7 +46,11 @@ func (c *findingSelectionClient) checkSelector(selector *protoapi.WorkloadSelect c.t.Error("missing explicit workload selector") } for _, ref := range selector.GetWorkloads() { - if ref.Environment != "dev" || ref.Team != "team" || ref.Name != "app" { + allowed := false + for _, row := range c.extraWorkloads { + allowed = allowed || row.Environment == ref.Environment && row.Team == ref.Team && row.Name == ref.Name + } + if !allowed && (ref.Environment != "dev" || ref.Team != "team" || ref.Name != "app") { c.t.Errorf("invalid current selection: %v", selector) } } @@ -56,9 +63,14 @@ func selectionImage() *protoapi.Image { func (c *findingSelectionClient) ListWorkloads(_ context.Context, req *protoapi.ListWorkloadsRequest, _ ...grpc.CallOption) (*protoapi.ListWorkloadsResponse, error) { c.workloads.Add(1) c.checkSelector(req.WorkloadSelector) - return &protoapi.ListWorkloadsResponse{Workloads: []*protoapi.Workload{{ + rows := append([]*protoapi.Workload{{ Environment: "dev", Team: "team", Name: "app", ImageReference: "repo/app:2", Image: selectionImage(), - }}}, nil + FindingCounts: &protoapi.WorkloadFindingCounts{ + FindingCount: 1, UniqueVulnerabilityCount: 1, + SeverityCounts: &protoapi.VulnerabilitySeverityCounts{High: 1}, + }, + }}, c.extraWorkloads...) + return &protoapi.ListWorkloadsResponse{Workloads: rows}, nil } func (c *findingSelectionClient) ListFindings(_ context.Context, req *protoapi.ListFindingsRequest, _ ...grpc.CallOption) (*protoapi.ListFindingsResponse, error) { @@ -71,7 +83,7 @@ func (c *findingSelectionClient) ListFindings(_ context.Context, req *protoapi.L resp.PackageTypeCounts = []*protoapi.PackageTypeCount{{Value: "npm", Count: 1}} if req.PageToken == "" { resp.Findings = []*protoapi.Finding{{ - Workload: &protoapi.WorkloadRef{Environment: "dev", Team: "team", Name: "app"}, Image: selectionImage(), + Workload: req.WorkloadSelector.Workloads[0], Image: selectionImage(), VulnerabilityId: "CVE-A", Purl: "pkg:npm/example@1", Severity: protoapi.Severity_SEVERITY_HIGH, }} resp.Cursors = []string{"finding-a"} @@ -116,7 +128,13 @@ func (c *findingSelectionClient) CountFindings(_ context.Context, req *protoapi. if len(req.Filter.Severities) == 1 && req.Filter.Severities[0] != protoapi.Severity_SEVERITY_HIGH { count = 0 } - return &protoapi.CountFindingsResponse{Buckets: []*protoapi.CountFindingsResponse_Bucket{{Key: "dev/team/app", Count: count}}}, nil + buckets := []*protoapi.CountFindingsResponse_Bucket{{Key: "dev/team/app", Count: count}} + for _, row := range c.extraWorkloads { + buckets = append(buckets, &protoapi.CountFindingsResponse_Bucket{ + Key: row.Environment + "/" + row.Team + "/" + row.Name, Count: count, + }) + } + return &protoapi.CountFindingsResponse{Buckets: buckets}, nil } func (c *findingSelectionClient) GetSummary(_ context.Context, req *protoapi.GetSummaryRequest, _ ...grpc.CallOption) (*protoapi.GetSummaryResponse, error) { @@ -130,35 +148,81 @@ func (c *findingSelectionClient) GetSummary(_ context.Context, req *protoapi.Get }, nil } +type findingSelectionFields struct { + Nodes []struct{ VulnerabilityIdentifier string } + PageInfo struct { + TotalCount int + EndCursor string + } + Facets struct { + PackageTypes []struct { + Value string + Count int + } + } + Summary struct { + FindingCount int64 + Coverage struct{ TotalWorkloads, Scanned, Pending int } + } + Vulnerabilities struct { + Nodes []struct{ VulnerabilityIdentifier string } + PageInfo struct { + TotalCount int + HasNextPage, HasPreviousPage bool + StartCursor, EndCursor string + } + } + AffectedWorkloads struct { + Nodes []struct { + Name string + Selection *findingSelectionFields + } + PageInfo struct{ TotalCount int } + } +} + type findingSelectionResponse struct { Errors []json.RawMessage Data struct { - Selection struct { - Nodes []struct{ VulnerabilityIdentifier string } - PageInfo struct { - TotalCount int - EndCursor string - } - Facets struct { - PackageTypes []struct { - Value string - Count int - } - } - Summary struct{ FindingCount int64 } - Vulnerabilities struct { - Nodes []struct{ VulnerabilityIdentifier string } - PageInfo struct { - TotalCount int - HasNextPage, HasPreviousPage bool - StartCursor, EndCursor string - } + Selection findingSelectionFields + Team struct { + Selection findingSelectionFields + Environment struct { + Selection findingSelectionFields + Workload struct{ Selection findingSelectionFields } } } } } func newFindingSelectionQuery(t *testing.T) (*findingSelectionClient, func(string, map[string]any) findingSelectionResponse) { + t.Helper() + return newFindingSelectionQueryWithFixtures(t, nil) +} + +type findingSelectionResolvers struct{ *Resolver } + +func (r findingSelectionResolvers) Query() gengql.QueryResolver { + return findingSelectionQueryResolver{QueryResolver: r.Resolver.Query()} +} + +func (r findingSelectionResolvers) Team() gengql.TeamResolver { + return findingSelectionTeamResolver{TeamResolver: r.Resolver.Team()} +} + +type findingSelectionQueryResolver struct{ gengql.QueryResolver } + +func (findingSelectionQueryResolver) Team(_ context.Context, name slug.Slug) (*team.Team, error) { + return &team.Team{Slug: name}, nil +} + +type findingSelectionTeamResolver struct{ gengql.TeamResolver } + +func (findingSelectionTeamResolver) Environment(_ context.Context, obj *team.Team, name string) (*team.TeamEnvironment, error) { + return &team.TeamEnvironment{TeamSlug: obj.Slug, EnvironmentName: name}, nil +} + +func newFindingSelectionQueryWithFixtures(t *testing.T, extraFixtures fstest.MapFS) (*findingSelectionClient, func(string, map[string]any) findingSelectionResponse) { t.Helper() log, _ := logrustest.NewNullLogger() scheme, err := kubernetes.NewScheme() @@ -173,7 +237,15 @@ metadata: spec: image: repo/app:2 `)}} - mgr, err := watcher.NewManager(scheme, kubernetes.ClusterConfigMap{"dev": nil}, log, watcher.WithClientCreator(fake.Clients(fixtures))) + for path, fixture := range extraFixtures { + fixtures[path] = fixture + } + clusters := kubernetes.ClusterConfigMap{"dev": nil} + for path := range extraFixtures { + cluster, _, _ := strings.Cut(path, "/") + clusters[cluster] = nil + } + mgr, err := watcher.NewManager(scheme, clusters, log, watcher.WithClientCreator(fake.Clients(fixtures))) if err != nil { t.Fatal(err) } @@ -192,7 +264,7 @@ spec: c := &findingSelectionClient{t: t} c.manager = &v0s.Manager{Vulnerabilities: c, LiveSelectionEnabled: true} ctx = v0s.WithManager(ctx, c.manager) - server := handler.New(gengql.NewExecutableSchema(gengql.Config{Resolvers: NewResolver("test", nil)})) + server := handler.New(gengql.NewExecutableSchema(gengql.Config{Resolvers: findingSelectionResolvers{NewResolver("test", nil)}})) server.AddTransport(transport.POST{}) return c, func(query string, variables map[string]any) findingSelectionResponse { t.Helper() @@ -403,3 +475,305 @@ func TestGlobalCVESelectionAliasesSkipFindingsPage(t *testing.T) { t.Fatalf("aliased independent fields fetched findings or failed: %+v", got) } } + +func scopedFindingQuery(scope, args, fields string) string { + selection := `selection: vulnerabilityFindings` + if args != "" { + selection += `(` + args + `)` + } + selection += ` { ` + fields + ` }` + switch scope { + case "Query": + return `query { selection: vulnerabilityFindings(filter: {teamScope: {teamSlugs: ["team"]}}, ` + args + `) { ` + fields + ` } }` + case "Team": + return `query { team(slug: "team") { ` + selection + ` } }` + case "TeamEnvironment": + return `query { team(slug: "team") { environment(name: "dev") { ` + selection + ` } } }` + case "Application": + return `query { team(slug: "team") { environment(name: "dev") { workload(name: "app") { + ... on Application { ` + selection + ` } + } } } }` + case "Job": + return `query { team(slug: "team") { environment(name: "dev") { workload(name: "job") { + ... on Job { ` + selection + ` } + } } } }` + default: + panic("unknown test scope") + } +} + +func (r findingSelectionResponse) scopedFields(scope string) findingSelectionFields { + switch scope { + case "Query": + return r.Data.Selection + case "Team": + return r.Data.Team.Selection + case "TeamEnvironment": + return r.Data.Team.Environment.Selection + default: + return r.Data.Team.Environment.Workload.Selection + } +} + +func newScopedFindingSelectionQuery(t *testing.T, scope string) (*findingSelectionClient, func(string, map[string]any) findingSelectionResponse) { + t.Helper() + if scope != "Job" { + return newFindingSelectionQuery(t) + } + c, query := newFindingSelectionQueryWithFixtures(t, fstest.MapFS{ + "dev/team/job.yaml": {Data: []byte(`apiVersion: nais.io/v1 +kind: Naisjob +metadata: + name: job + namespace: team +spec: + image: repo/app:2 +`)}, + }) + c.extraWorkloads = []*protoapi.Workload{{ + Environment: "dev", Team: "team", Name: "job", ImageReference: "repo/app:2", Image: selectionImage(), + FindingCounts: &protoapi.WorkloadFindingCounts{ + FindingCount: 1, UniqueVulnerabilityCount: 1, + SeverityCounts: &protoapi.VulnerabilitySeverityCounts{High: 1}, + }, + }} + return c, query +} + +func TestScopedFindingSelectionsSkipIndependentPages(t *testing.T) { + for _, scope := range []string{"Query", "Team", "TeamEnvironment", "Application", "Job"} { + t.Run(scope, func(t *testing.T) { + for _, fields := range []string{ + `summary { findingCount }`, + `vulnerabilities(first: 1) { nodes { vulnerabilityIdentifier } pageInfo { totalCount } }`, + `affectedWorkloads { nodes { name } pageInfo { totalCount } }`, + `summary { findingCount } + vulnerabilities(first: 1) { nodes { vulnerabilityIdentifier } pageInfo { totalCount } } + affectedWorkloads { nodes { name } pageInfo { totalCount } }`, + } { + t.Run(fields, func(t *testing.T) { + c, query := newScopedFindingSelectionQuery(t, scope) + got := query(scopedFindingQuery(scope, "", fields), nil) + if len(got.Errors) != 0 || c.findings.Load() != 0 { + t.Fatalf("independent fields fetched findings or failed: RPCs=%d, response=%+v", c.findings.Load(), got) + } + selection := got.scopedFields(scope) + if strings.Contains(fields, "summary") && (c.summaries.Load() != 1 || selection.Summary.FindingCount != 1) { + t.Fatalf("summary changed: %+v", selection.Summary) + } + if strings.Contains(fields, "vulnerabilities") && (c.groups.Load() != 1 || + selection.Vulnerabilities.PageInfo.TotalCount != 2 || len(selection.Vulnerabilities.Nodes) != 1 || + selection.Vulnerabilities.Nodes[0].VulnerabilityIdentifier != "CVE-A") { + t.Fatalf("CVE page changed: %+v", selection.Vulnerabilities) + } + if strings.Contains(fields, "affectedWorkloads") { + expected := "app" + if scope == "Job" { + expected = "job" + } + affected := selection.AffectedWorkloads + if affected.PageInfo.TotalCount != 1 || len(affected.Nodes) != 1 || affected.Nodes[0].Name != expected { + t.Fatalf("affected workloads changed: %+v", affected) + } + } + }) + } + }) + } +} + +func TestScopedFindingSelectionsKeepRequiredPages(t *testing.T) { + for _, scope := range []string{"Query", "Team", "TeamEnvironment", "Application", "Job"} { + t.Run(scope, func(t *testing.T) { + c, query := newScopedFindingSelectionQuery(t, scope) + got := query(scopedFindingQuery(scope, "first: 1", ` + nodes { vulnerabilityIdentifier } + edges { node { vulnerabilityIdentifier } } + pageInfo { totalCount } + summary { findingCount } + facets { packageTypes { value count } } + other: facets { packageTypes { value count } } + `), nil) + if len(got.Errors) != 0 || c.findings.Load() != 1 { + t.Fatalf("required page failed or loaded twice: RPCs=%d, response=%+v", c.findings.Load(), got) + } + selection := got.scopedFields(scope) + if len(selection.Nodes) != 1 || selection.Nodes[0].VulnerabilityIdentifier != "CVE-A" || + selection.PageInfo.TotalCount != 1 || selection.Summary.FindingCount != 1 { + t.Fatalf("findings/counts changed: %+v", selection) + } + packages := selection.Facets.PackageTypes + if len(packages) != 1 || packages[0].Value != "npm" || packages[0].Count != 1 { + t.Fatalf("package facets changed: %+v", packages) + } + }) + } +} + +func TestScopedFindingSelectionsRespectDirectivesAndAliases(t *testing.T) { + for _, scope := range []string{"Query", "Team", "TeamEnvironment", "Application", "Job"} { + t.Run(scope, func(t *testing.T) { + for _, include := range []bool{false, true} { + c, query := newScopedFindingSelectionQuery(t, scope) + text := scopedFindingQuery(scope, "", ` + groups: affectedWorkloads { nodes { name } } + aggregate: summary { findingCount } + ...Findings @include(if: $include) + ... on VulnerabilityFindingConnection { + nodes @skip(if: $skip) { vulnerabilityIdentifier } + } + `) + text = strings.Replace(text, "query {", "query($include: Boolean!, $skip: Boolean!) {", 1) + text += `fragment Findings on VulnerabilityFindingConnection { + facets { packageTypes { value count } } + edges { node { vulnerabilityIdentifier } } + pageInfo { totalCount } + }` + got := query(text, map[string]any{"include": include, "skip": !include}) + want := int32(0) + if include { + want = 1 + } + if len(got.Errors) != 0 || c.findings.Load() != want || c.summaries.Load() != 1 { + t.Fatalf("directive include=%t: findings=%d, response=%+v", include, c.findings.Load(), got) + } + } + }) + } +} + +func TestCVEDetailsFetchOnlyNestedFindingPages(t *testing.T) { + for _, scope := range []string{"Query", "Team"} { + t.Run(scope, func(t *testing.T) { + c, query := newScopedFindingSelectionQuery(t, "Job") + got := query(scopedFindingQuery(scope, "", ` + summary { findingCount } + affectedWorkloads { + pageInfo { totalCount } + nodes { + name + ... on Application { + selection: vulnerabilityFindings(first: 5) { nodes { vulnerabilityIdentifier } pageInfo { totalCount } } + } + ... on Job { + selection: vulnerabilityFindings(first: 5) { nodes { vulnerabilityIdentifier } pageInfo { totalCount } } + } + } + } + `), nil) + if len(got.Errors) != 0 || c.findings.Load() != 2 { + t.Fatalf("expected only the two nested finding pages, got %d: %+v", c.findings.Load(), got) + } + selection := got.scopedFields(scope) + affected := selection.AffectedWorkloads + if selection.Summary.FindingCount != 2 || affected.PageInfo.TotalCount != 2 || len(affected.Nodes) != 2 { + t.Fatalf("CVE detail aggregates changed: %+v", selection) + } + for _, row := range affected.Nodes { + if row.Selection == nil || len(row.Selection.Nodes) != 1 || + row.Selection.Nodes[0].VulnerabilityIdentifier != "CVE-A" || row.Selection.PageInfo.TotalCount != 1 { + t.Fatalf("nested findings changed: %+v", row) + } + } + }) + } +} + +func TestScopedFindingSelectionsValidateUnusedParentPage(t *testing.T) { + for _, scope := range []string{"Query", "Team", "TeamEnvironment", "Application", "Job"} { + t.Run(scope, func(t *testing.T) { + c, query := newScopedFindingSelectionQuery(t, scope) + for _, args := range []string{"first: 0", "last: 1", `after: "invalid"`, `first: 1, before: "invalid"`} { + got := query(scopedFindingQuery(scope, args, `summary { findingCount }`), nil) + if len(got.Errors) == 0 || c.findings.Load() != 0 || c.summaries.Load() != 0 { + t.Fatalf("unused parent arguments %q not validated: %+v", args, got) + } + } + first := query(scopedFindingQuery(scope, "first: 1", `pageInfo { endCursor }`), nil) + cursor := first.scopedFields(scope).PageInfo.EndCursor + if len(first.Errors) != 0 || cursor == "" { + t.Fatalf("failed to obtain a finding cursor: %+v", first) + } + text := strings.Replace(scopedFindingQuery(scope, + `after: $after, orderBy: {field: IDENTIFIER, direction: DESC}`, `summary { findingCount }`), + "query {", "query($after: Cursor) {", 1) + got := query(text, map[string]any{"after": cursor}) + if len(got.Errors) == 0 || c.findings.Load() != 1 || c.summaries.Load() != 0 { + t.Fatalf("unused parent binding was not validated: %+v", got) + } + }) + } +} + +func TestIndependentFindingSelectionsKeepCurrentScopedInventory(t *testing.T) { + fixtures := fstest.MapFS{ + "prod/team/prod-app.yaml": {Data: []byte(`apiVersion: nais.io/v1alpha1 +kind: Application +metadata: + name: prod-app + namespace: team +spec: + image: repo/app:2 +`)}, + "dev/team/stale.yaml": {Data: []byte(`apiVersion: nais.io/v1alpha1 +kind: Application +metadata: + name: stale + namespace: team +spec: + image: repo/app:2 +`)}, + "dev/other/outsider.yaml": {Data: []byte(`apiVersion: nais.io/v1alpha1 +kind: Application +metadata: + name: outsider + namespace: other +spec: + image: repo/app:2 +`)}, + } + for _, scope := range []string{"Query", "Team", "TeamEnvironment"} { + t.Run(scope, func(t *testing.T) { + c, query := newFindingSelectionQueryWithFixtures(t, fixtures) + for _, ref := range []struct{ env, team, name, image string }{ + {"prod", "team", "prod-app", "repo/app:2"}, + {"dev", "team", "stale", "repo/app:1"}, + {"dev", "other", "outsider", "repo/app:2"}, + } { + c.extraWorkloads = append(c.extraWorkloads, &protoapi.Workload{ + Environment: ref.env, Team: ref.team, Name: ref.name, ImageReference: ref.image, Image: selectionImage(), + FindingCounts: &protoapi.WorkloadFindingCounts{ + FindingCount: 1, + SeverityCounts: &protoapi.VulnerabilitySeverityCounts{High: 1}, + }, + }) + } + text := scopedFindingQuery(scope, "", ` + summary { findingCount coverage { totalWorkloads scanned pending } } + affectedWorkloads { nodes { name } pageInfo { totalCount } } + `) + switch scope { + case "Query": + text = strings.Replace(text, `teamSlugs: ["team"]}`, `teamSlugs: ["team"]}, environments: ["dev"]`, 1) + case "Team": + text = strings.Replace(text, `selection: vulnerabilityFindings`, `selection: vulnerabilityFindings(filter: {environments: ["dev"]})`, 1) + } + got := query(text, nil) + selection := got.scopedFields(scope) + if len(got.Errors) != 0 || c.findings.Load() != 0 || selection.Summary.FindingCount != 1 || + selection.Summary.Coverage.TotalWorkloads != 2 || selection.Summary.Coverage.Scanned != 1 || + selection.Summary.Coverage.Pending != 1 || len(selection.AffectedWorkloads.Nodes) != 1 || + selection.AffectedWorkloads.Nodes[0].Name != "app" { + t.Fatalf("scope/image reconciliation changed: %+v", got) + } + empty := strings.ReplaceAll(text, `"dev"`, `"missing"`) + got = query(empty, nil) + selection = got.scopedFields(scope) + if len(got.Errors) != 0 || c.findings.Load() != 0 || selection.Summary.FindingCount != 0 || + selection.Summary.Coverage.TotalWorkloads != 0 || len(selection.AffectedWorkloads.Nodes) != 0 || + selection.AffectedWorkloads.PageInfo.TotalCount != 0 { + t.Fatalf("empty scoped selection leaked: %+v", got) + } + }) + } +}