diff --git a/go.mod b/go.mod index 38df83ef..052034f8 100644 --- a/go.mod +++ b/go.mod @@ -63,7 +63,7 @@ require ( github.com/fatih/color v1.18.0 // indirect github.com/gabriel-vasile/mimetype v1.4.12 // indirect github.com/gin-contrib/sse v1.1.0 // indirect - github.com/go-logr/logr v1.4.3 // indirect + github.com/go-logr/logr v1.4.4 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/go-playground/locales v0.14.1 // indirect github.com/go-playground/universal-translator v0.18.1 // indirect @@ -116,8 +116,9 @@ require ( github.com/urfave/cli/v3 v3.11.0 // indirect go.mongodb.org/mongo-driver/v2 v2.5.0 // indirect go.opentelemetry.io/auto/sdk v1.2.1 // indirect - go.opentelemetry.io/otel v1.44.0 // indirect - go.opentelemetry.io/otel/metric v1.44.0 // indirect + go.opentelemetry.io/otel v1.47.0 // indirect + go.opentelemetry.io/otel/log v1.47.0 // indirect + go.opentelemetry.io/otel/metric v1.47.0 // indirect go.opentelemetry.io/otel/trace v1.47.0 // indirect go.uber.org/atomic v1.9.0 // indirect go.uber.org/multierr v1.11.0 // indirect diff --git a/go.sum b/go.sum index 9e4f1904..fc99fae2 100644 --- a/go.sum +++ b/go.sum @@ -95,8 +95,8 @@ github.com/gkampitakis/go-snaps v0.5.15/go.mod h1:HNpx/9GoKisdhw9AFOBT1N7DBs9DiH github.com/go-co-op/gocron v1.37.0 h1:ZYDJGtQ4OMhTLKOKMIch+/CY70Brbb1dGdooLEhh7b0= github.com/go-co-op/gocron v1.37.0/go.mod h1:3L/n6BkO7ABj+TrfSVXLRzsP26zmikL4ISkLQ0O8iNY= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= -github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= -github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8= +github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= @@ -319,16 +319,18 @@ go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0 h1:F7Jx+6hwnZ41NSFTO5q4LYDtJRXBf2PD0rNBkeB/lus= go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0/go.mod h1:UHB22Z8QsdRDrnAtX4PntOl36ajSxcdUMt1sF7Y6E7Q= -go.opentelemetry.io/otel v1.44.0 h1:JjwHmHpA4iZ3wBxluu2fbbE7j4kqlE8jXyAyPXH7HqU= -go.opentelemetry.io/otel v1.44.0/go.mod h1:BMgjTHL9WPRlRjL2oZCBTL4whCGtXch2H4BhOPIAyYc= -go.opentelemetry.io/otel/metric v1.44.0 h1:1w0gILTcHdr3YI+ixLyjemwrVnsMURbTZFrSYCdDdmc= -go.opentelemetry.io/otel/metric v1.44.0/go.mod h1:8O7hanEPBNgEMmybD3s2VBKcgWOCsA6tzHBPODAiquo= +go.opentelemetry.io/otel v1.47.0 h1:j7ALJ/zgkS7Z6aeJW09p8VC9804bC+PpeTfCD4XPnOM= +go.opentelemetry.io/otel v1.47.0/go.mod h1:8wS9O2qfXrYrzp6hIF/HOYJJf/wIhFPhR2xLuP+iXQU= +go.opentelemetry.io/otel/log v1.47.0 h1:cOTS1CcLbSQeZKanGJ+0JpF/+t4PELi3O3bbl2lqCcI= +go.opentelemetry.io/otel/log v1.47.0/go.mod h1:9byitSQ5pLC6PpqwGXjqdMKya6ZTswHRZh2vvXT33nw= +go.opentelemetry.io/otel/metric v1.47.0 h1:4PptaldXx3Eat1XjMZ68pPJEs5wrhlemctZE9a3UdWY= +go.opentelemetry.io/otel/metric v1.47.0/go.mod h1:ADGSXxRrXM6bjbvLo535EstVFlPpPYZm4LBKixjDHwU= go.opentelemetry.io/otel/sdk v1.44.0 h1:nHYwb9lK+fJPU/dnT6s7W7Z8itMWyqrnVfbheVYrZ58= go.opentelemetry.io/otel/sdk v1.44.0/go.mod h1:Osuydd3Se74nqjAKxid74N5eC+jfEqfTegHRnq58oK0= go.opentelemetry.io/otel/sdk/metric v1.44.0 h1:3LlKgI+VjbVsjNRFZJZAJ30WjXC5VkNRks6si09iEfI= go.opentelemetry.io/otel/sdk/metric v1.44.0/go.mod h1:5B5pMARnXxKhltooO4xUuCBorl65a4EpnTalObqOigA= -go.opentelemetry.io/otel/trace v1.44.0 h1:jxF5CsGYCe74MCRx2X4g7WsY/VBKRqqpNvXlX/6gtIk= -go.opentelemetry.io/otel/trace v1.44.0/go.mod h1:oLl1jrMQAVo6v3GAggN+1VH9VIz9iUSvW53sW1Q8PIE= +go.opentelemetry.io/otel/trace v1.47.0 h1:JOjX/Oci8K94QHddo+bbfya/Ai/nf6/dt9ZfrFNWSrM= +go.opentelemetry.io/otel/trace v1.47.0/go.mod h1:jNaSLa2PZEYFG6fRjJABAu+bw4FS08uDmPg28lTghu0= go.uber.org/atomic v1.9.0 h1:ECmE8Bn/WFTYwEW/bpKD3M8VtR/zQVbavAoalC1PYyE= go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= diff --git a/scanner/keppel/processor/batch.go b/scanner/keppel/processor/batch.go new file mode 100644 index 00000000..33c365a1 --- /dev/null +++ b/scanner/keppel/processor/batch.go @@ -0,0 +1,284 @@ +// SPDX-FileCopyrightText: 2026 SAP SE or an SAP affiliate company and Greenhouse contributors +// SPDX-License-Identifier: Apache-2.0 + +package processor + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "strings" + + "github.com/cloudoperators/heureka/scanners/keppel/client" + "github.com/cloudoperators/heureka/scanners/keppel/models" + log "github.com/sirupsen/logrus" +) + +// newVuln holds the data needed to create an Issue + IssueVariant for a CVE +// that does not yet exist in Heureka. +type newVuln struct { primaryName string + description string + cvssVector string + severity string +} + +type linkPair struct { + primaryName string + issueId string + componentVersionId string +} + +// batchGQLResponse is the raw GraphQL response envelope for multi-alias +// mutations where partial failures are expected. +type batchGQLResponse struct { + Data map[string]json.RawMessage `json:"data"` + Errors []batchGQLError `json:"errors"` +} + +type batchGQLError struct { + Message string `json:"message"` + Path []string `json:"path"` +} + +func errByAlias(errs []batchGQLError) map[string]string { + m := make(map[string]string, len(errs)) + for _, e := range errs { + if len(e.Path) > 0 { + m[e.Path[0]] = e.Message + } + } + return m +} + +// doRawGQL sends a raw GraphQL mutation string to the Heureka endpoint and +// returns the decoded envelope. A non-empty errors[] is not treated as fatal — +// the caller inspects partial results itself. +func (p *Processor) doRawGQL(ctx context.Context, query string) (batchGQLResponse, error) { + body, err := json.Marshal(map[string]string{"query": query}) + if err != nil { + return batchGQLResponse{}, fmt.Errorf("marshal batch request: %w", err) + } + + req, err := http.NewRequestWithContext(ctx, http.MethodPost, p.heurekaURL, bytes.NewReader(body)) + if err != nil { + return batchGQLResponse{}, fmt.Errorf("create batch request: %w", err) + } + req.Header.Set("Content-Type", "application/json") + + resp, err := p.httpClient.Do(req) + if err != nil { + return batchGQLResponse{}, fmt.Errorf("execute batch request: %w", err) + } + defer resp.Body.Close() + + respBody, err := io.ReadAll(resp.Body) + if err != nil { + return batchGQLResponse{}, fmt.Errorf("read batch response: %w", err) + } + + if resp.StatusCode != http.StatusOK { + return batchGQLResponse{}, fmt.Errorf("batch request HTTP %d: %s", resp.StatusCode, respBody) + } + + var gqlResp batchGQLResponse + if err := json.Unmarshal(respBody, &gqlResp); err != nil { + return batchGQLResponse{}, fmt.Errorf("decode batch response: %w", err) + } + return gqlResp, nil +} + +// gqlString JSON-encodes s, producing a valid quoted GraphQL string literal. +func gqlString(s string) string { + b, _ := json.Marshal(s) + return string(b) +} + +func chunks[T any](s []T, n int) [][]T { + if n <= 0 || len(s) == 0 { + return nil + } + result := make([][]T, 0, (len(s)+n-1)/n) + for len(s) > 0 { + k := n + if k > len(s) { + k = len(s) + } + result = append(result, s[:k]) + s = s[k:] + } + return result +} + +func (p *Processor) batchCreateIssues(ctx context.Context, vulns []newVuln) map[string]*client.Issue { + results := make(map[string]*client.Issue, len(vulns)) + + for _, chunk := range chunks(vulns, p.BatchSize) { + var sb strings.Builder + sb.WriteString("mutation {") + for i, v := range chunk { + fmt.Fprintf(&sb, + " i%d: createIssue(input: {primaryName: %s, description: %s, type: Vulnerability, uuid: %s}) { id primaryName description type }", + i, + gqlString(v.primaryName), + gqlString(v.description), + gqlString(p.uuid), + ) + } + sb.WriteString(" }") + + gqlResp, err := p.doRawGQL(ctx, sb.String()) + if err != nil { + for _, v := range chunk { + log.WithFields(log.Fields{ + "primaryName": v.primaryName, + }).WithError(err).Error("batch createIssue request failed") + } + continue + } + + aliasErrors := errByAlias(gqlResp.Errors) + for i, v := range chunk { + alias := fmt.Sprintf("i%d", i) + raw, ok := gqlResp.Data[alias] + if !ok || string(raw) == "null" { + log.WithFields(log.Fields{ + "primaryName": v.primaryName, + "error": aliasErrors[alias], + }).Error("createIssue failed in batch") + continue + } + var issue client.Issue + if err := json.Unmarshal(raw, &issue); err != nil { + log.WithFields(log.Fields{ + "primaryName": v.primaryName, + }).WithError(err).Error("decode createIssue batch result") + continue + } + log.WithFields(log.Fields{ + "issueId": issue.Id, + "primaryName": issue.PrimaryName, + }).Info("Issue created (batch)") + results[v.primaryName] = &issue + } + } + + return results +} + +// batchCreateIssueVariants returns the set of primaryNames for which variant creation failed. +func (p *Processor) batchCreateIssueVariants( + ctx context.Context, + vulns []newVuln, + issueIDByName map[string]string, +) map[string]struct{} { + failed := make(map[string]struct{}) + + for _, chunk := range chunks(vulns, p.BatchSize) { + var sb strings.Builder + sb.WriteString("mutation {") + for i, v := range chunk { + severityValue := string(models.GetSeverityValue(v.severity)) + fmt.Fprintf(&sb, + " i%d: createIssueVariant(input: {secondaryName: %s, description: %s, externalUrl: %s, issueId: %s, issueRepositoryId: %s, severity: {vector: %s, rating: %s}}) { id secondaryName issueId }", + i, + gqlString(v.primaryName), + gqlString(v.description), + gqlString(p.CveDetailsUrl+v.primaryName), + gqlString(issueIDByName[v.primaryName]), + gqlString(p.IssueRepositoryId), + gqlString(v.cvssVector), + severityValue, // enum value — no quotes in GraphQL + ) + } + sb.WriteString(" }") + + gqlResp, err := p.doRawGQL(ctx, sb.String()) + if err != nil { + for _, v := range chunk { + log.WithFields(log.Fields{ + "primaryName": v.primaryName, + }).WithError(err).Error("batch createIssueVariant request failed") + failed[v.primaryName] = struct{}{} + } + continue + } + + aliasErrors := errByAlias(gqlResp.Errors) + for i, v := range chunk { + alias := fmt.Sprintf("i%d", i) + raw, ok := gqlResp.Data[alias] + if !ok || string(raw) == "null" { + log.WithFields(log.Fields{ + "primaryName": v.primaryName, + "issueId": issueIDByName[v.primaryName], + "error": aliasErrors[alias], + }).Error("createIssueVariant failed in batch") + failed[v.primaryName] = struct{}{} + continue + } + var variant client.IssueVariant + if err := json.Unmarshal(raw, &variant); err != nil { + log.WithFields(log.Fields{ + "primaryName": v.primaryName, + }).WithError(err).Error("decode createIssueVariant batch result") + failed[v.primaryName] = struct{}{} + continue + } + log.WithFields(log.Fields{ + "issueVariantId": variant.Id, + }).Info("IssueVariant created (batch)") + } + } + + return failed +} + +func (p *Processor) batchAddComponentVersionToIssue(ctx context.Context, pairs []linkPair) { + for _, chunk := range chunks(pairs, p.BatchSize) { + var sb strings.Builder + sb.WriteString("mutation {") + for i, pair := range chunk { + fmt.Fprintf(&sb, + " i%d: addComponentVersionToIssue(issueId: %s, componentVersionId: %s) { id }", + i, + gqlString(pair.issueId), + gqlString(pair.componentVersionId), + ) + } + sb.WriteString(" }") + + gqlResp, err := p.doRawGQL(ctx, sb.String()) + if err != nil { + for _, pair := range chunk { + log.WithFields(log.Fields{ + "primaryName": pair.primaryName, + "issueId": pair.issueId, + "componentVersionId": pair.componentVersionId, + }).WithError(err).Error("batch addComponentVersionToIssue request failed") + } + continue + } + + aliasErrors := errByAlias(gqlResp.Errors) + for i, pair := range chunk { + alias := fmt.Sprintf("i%d", i) + raw, ok := gqlResp.Data[alias] + if !ok || string(raw) == "null" { + log.WithFields(log.Fields{ + "primaryName": pair.primaryName, + "issueId": pair.issueId, + "componentVersionId": pair.componentVersionId, + "error": aliasErrors[alias], + }).Error("addComponentVersionToIssue failed in batch") + continue + } + log.WithFields(log.Fields{ + "issueId": pair.issueId, + "componentVersionId": pair.componentVersionId, + }).Info("Added issue to componentVersion (batch)") + } + } +} diff --git a/scanner/keppel/processor/batch_test.go b/scanner/keppel/processor/batch_test.go new file mode 100644 index 00000000..52a8904e --- /dev/null +++ b/scanner/keppel/processor/batch_test.go @@ -0,0 +1,616 @@ +// SPDX-FileCopyrightText: 2026 SAP SE or an SAP affiliate company and Greenhouse contributors +// SPDX-License-Identifier: Apache-2.0 + +package processor + +import ( + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "sync/atomic" + "testing" + + "github.com/aquasecurity/trivy/pkg/types" + "github.com/cloudoperators/heureka/scanners/keppel/models" +) + +// gqlHandler is a test helper that captures each incoming request body and +// responds with a pre-recorded JSON payload. +type gqlHandler struct { + // responses is consumed in order; the last entry is reused once exhausted. + responses []string + mu sync.Mutex + bodies []string + idx int32 +} + +func (h *gqlHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + h.mu.Lock() + h.bodies = append(h.bodies, string(body)) + h.mu.Unlock() + + idx := int(atomic.AddInt32(&h.idx, 1)) - 1 + if idx >= len(h.responses) { + idx = len(h.responses) - 1 + } + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(h.responses[idx])) +} + +func newTestProcessor(t *testing.T, srv *httptest.Server, batchSize int) *Processor { + t.Helper() + cfg := Config{ + HeurekaUrl: srv.URL, + IssueRepositoryName: "nvd", + IssueRepositoryUrl: "https://nvd.nist.gov/", + CveDetailsUrl: "https://nvd.nist.gov/vuln/detail/", + HeurekaRateLimit: 1000, + HeurekaRateBurst: 1000, + BatchSize: batchSize, + } + p := NewProcessor(cfg, "test-tag") + p.IssueRepositoryId = "repo-1" + return p +} + +func issueJSON(id, primaryName string) string { + return `{"id":"` + id + `","primaryName":"` + primaryName + `","description":"desc","type":"Vulnerability"}` +} + +func variantJSON(id, secondaryName, issueId string) string { + return `{"id":"` + id + `","secondaryName":"` + secondaryName + `","issueId":"` + issueId + `"}` +} + +func linkJSON(id string) string { + return `{"id":"` + id + `"}` +} + +func buildDataPayload(data map[string]string) string { + b, _ := json.Marshal(map[string]interface{}{"data": jsonRawMap(data), "errors": []interface{}{}}) + return string(b) +} + +func buildPartialPayload(data map[string]string, errAliases map[string]string) string { + rawData := make(map[string]interface{}, len(data)) + for k, v := range data { + rawData[k] = json.RawMessage(v) + } + for alias := range errAliases { + rawData[alias] = json.RawMessage("null") + } + var errors []map[string]interface{} + for alias, msg := range errAliases { + errors = append(errors, map[string]interface{}{ + "message": msg, + "path": []string{alias}, + }) + } + b, _ := json.Marshal(map[string]interface{}{"data": rawData, "errors": errors}) + return string(b) +} + +// jsonRawMap embeds values verbatim rather than as double-encoded strings. +func jsonRawMap(m map[string]string) map[string]json.RawMessage { + out := make(map[string]json.RawMessage, len(m)) + for k, v := range m { + out[k] = json.RawMessage(v) + } + return out +} + +// --------------------------------------------------------------------------- +// chunks +// --------------------------------------------------------------------------- + +func TestChunks_EmptySlice(t *testing.T) { + result := chunks([]int{}, 5) + if result != nil { + t.Fatalf("expected nil for empty input, got %v", result) + } +} + +func TestChunks_ZeroSize(t *testing.T) { + result := chunks([]int{1, 2, 3}, 0) + if result != nil { + t.Fatalf("expected nil for n=0, got %v", result) + } +} + +func TestChunks_NegativeSize(t *testing.T) { + result := chunks([]int{1, 2, 3}, -1) + if result != nil { + t.Fatalf("expected nil for n<0, got %v", result) + } +} + +func TestChunks_SingleItem(t *testing.T) { + result := chunks([]int{42}, 10) + if len(result) != 1 || len(result[0]) != 1 || result[0][0] != 42 { + t.Fatalf("unexpected result: %v", result) + } +} + +func TestChunks_ExactMultiple(t *testing.T) { + result := chunks([]int{1, 2, 3, 4}, 2) + if len(result) != 2 { + t.Fatalf("expected 2 chunks, got %d", len(result)) + } + if result[0][0] != 1 || result[0][1] != 2 { + t.Fatalf("unexpected first chunk: %v", result[0]) + } + if result[1][0] != 3 || result[1][1] != 4 { + t.Fatalf("unexpected second chunk: %v", result[1]) + } +} + +func TestChunks_WithRemainder(t *testing.T) { + result := chunks([]int{1, 2, 3, 4, 5}, 2) + if len(result) != 3 { + t.Fatalf("expected 3 chunks, got %d", len(result)) + } + if len(result[2]) != 1 || result[2][0] != 5 { + t.Fatalf("unexpected last chunk: %v", result[2]) + } +} + +func TestChunks_SizeEqualsLength(t *testing.T) { + result := chunks([]int{1, 2, 3}, 3) + if len(result) != 1 || len(result[0]) != 3 { + t.Fatalf("expected single chunk of 3, got %v", result) + } +} + +// --------------------------------------------------------------------------- +// batchCreateIssues +// --------------------------------------------------------------------------- + +func TestBatchCreateIssues_AllSucceed(t *testing.T) { + h := &gqlHandler{ + responses: []string{ + buildDataPayload(map[string]string{ + "i0": issueJSON("id-1", "CVE-2024-0001"), + "i1": issueJSON("id-2", "CVE-2024-0002"), + }), + }, + } + srv := httptest.NewServer(h) + defer srv.Close() + + p := newTestProcessor(t, srv, 25) + vulns := []newVuln{ + {primaryName: "CVE-2024-0001", description: "desc1"}, + {primaryName: "CVE-2024-0002", description: "desc2"}, + } + + results := p.batchCreateIssues(context.Background(), vulns) + + if len(results) != 2 { + t.Fatalf("expected 2 results, got %d", len(results)) + } + if results["CVE-2024-0001"].Id != "id-1" { + t.Errorf("wrong id for CVE-2024-0001: %s", results["CVE-2024-0001"].Id) + } + if results["CVE-2024-0002"].Id != "id-2" { + t.Errorf("wrong id for CVE-2024-0002: %s", results["CVE-2024-0002"].Id) + } +} + +func TestBatchCreateIssues_PartialAliasFail(t *testing.T) { + h := &gqlHandler{ + responses: []string{ + buildPartialPayload( + map[string]string{"i1": issueJSON("id-2", "CVE-2024-0002")}, + map[string]string{"i0": "already exists"}, + ), + }, + } + srv := httptest.NewServer(h) + defer srv.Close() + + p := newTestProcessor(t, srv, 25) + vulns := []newVuln{ + {primaryName: "CVE-2024-0001", description: "desc1"}, + {primaryName: "CVE-2024-0002", description: "desc2"}, + } + + results := p.batchCreateIssues(context.Background(), vulns) + + if _, ok := results["CVE-2024-0001"]; ok { + t.Error("CVE-2024-0001 should be absent (alias failed)") + } + if results["CVE-2024-0002"].Id != "id-2" { + t.Errorf("CVE-2024-0002 should succeed, got %v", results["CVE-2024-0002"]) + } +} + +func TestBatchCreateIssues_WholeChunkHTTPError(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusInternalServerError) + _, _ = w.Write([]byte("internal error")) + })) + defer srv.Close() + + p := newTestProcessor(t, srv, 25) + vulns := []newVuln{ + {primaryName: "CVE-2024-0001"}, + {primaryName: "CVE-2024-0002"}, + } + + results := p.batchCreateIssues(context.Background(), vulns) + + if len(results) != 0 { + t.Fatalf("expected empty results on HTTP error, got %v", results) + } +} + +func TestBatchCreateIssues_ChunkBoundary(t *testing.T) { + singleChunkResp := func() string { + return buildDataPayload(map[string]string{ + "i0": issueJSON("id-x", "CVE-X"), + "i1": issueJSON("id-y", "CVE-Y"), + }) + } + + var callCount int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + atomic.AddInt32(&callCount, 1) + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(singleChunkResp())) + })) + defer srv.Close() + + p := newTestProcessor(t, srv, 2) + vulns := make([]newVuln, 5) + for i := range vulns { + vulns[i] = newVuln{primaryName: "CVE-placeholder"} + } + + p.batchCreateIssues(context.Background(), vulns) + + if got := atomic.LoadInt32(&callCount); got != 3 { + t.Fatalf("expected 3 HTTP calls for 5 vulns with batchSize=2, got %d", got) + } +} + +func TestBatchCreateIssues_ZeroBatchSize(t *testing.T) { + h := &gqlHandler{ + responses: []string{ + buildDataPayload(map[string]string{ + "i0": issueJSON("id-1", "CVE-2024-0001"), + }), + }, + } + srv := httptest.NewServer(h) + defer srv.Close() + + // BatchSize=0 is clamped to 1; vulnerabilities must still be processed. + p := newTestProcessor(t, srv, 0) + if p.BatchSize != 1 { + t.Fatalf("expected BatchSize clamped to 1, got %d", p.BatchSize) + } + + vulns := []newVuln{{primaryName: "CVE-2024-0001"}} + results := p.batchCreateIssues(context.Background(), vulns) + + if len(results) != 1 { + t.Fatalf("expected 1 result after clamp, got %d", len(results)) + } +} + +func TestBatchCreateIssues_RequestContainsAlias(t *testing.T) { + var captured string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + captured = string(body) + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(buildDataPayload(map[string]string{ + "i0": issueJSON("id-1", "CVE-2024-0001"), + }))) + })) + defer srv.Close() + + p := newTestProcessor(t, srv, 25) + p.batchCreateIssues(context.Background(), []newVuln{{primaryName: "CVE-2024-0001", description: "desc"}}) + + if !strings.Contains(captured, `i0: createIssue`) { + t.Errorf("request body missing alias i0: createIssue, got: %s", captured) + } + if !strings.Contains(captured, "CVE-2024-0001") { + t.Errorf("request body missing CVE name, got: %s", captured) + } +} + +// --------------------------------------------------------------------------- +// batchCreateIssueVariants +// --------------------------------------------------------------------------- + +func TestBatchCreateIssueVariants_AllSucceed(t *testing.T) { + h := &gqlHandler{ + responses: []string{ + buildDataPayload(map[string]string{ + "i0": variantJSON("v-1", "CVE-2024-0001", "id-1"), + "i1": variantJSON("v-2", "CVE-2024-0002", "id-2"), + }), + }, + } + srv := httptest.NewServer(h) + defer srv.Close() + + p := newTestProcessor(t, srv, 25) + vulns := []newVuln{ + {primaryName: "CVE-2024-0001", severity: "HIGH"}, + {primaryName: "CVE-2024-0002", severity: "LOW"}, + } + issueIDByName := map[string]string{ + "CVE-2024-0001": "id-1", + "CVE-2024-0002": "id-2", + } + + failed := p.batchCreateIssueVariants(context.Background(), vulns, issueIDByName) + + if len(failed) != 0 { + t.Fatalf("expected no failures, got %v", failed) + } +} + +func TestBatchCreateIssueVariants_VariantFailedSetPopulated(t *testing.T) { + h := &gqlHandler{ + responses: []string{ + buildPartialPayload( + map[string]string{"i1": variantJSON("v-2", "CVE-2024-0002", "id-2")}, + map[string]string{"i0": "constraint violation"}, + ), + }, + } + srv := httptest.NewServer(h) + defer srv.Close() + + p := newTestProcessor(t, srv, 25) + vulns := []newVuln{ + {primaryName: "CVE-2024-0001", severity: "HIGH"}, + {primaryName: "CVE-2024-0002", severity: "LOW"}, + } + issueIDByName := map[string]string{ + "CVE-2024-0001": "id-1", + "CVE-2024-0002": "id-2", + } + + failed := p.batchCreateIssueVariants(context.Background(), vulns, issueIDByName) + + if _, ok := failed["CVE-2024-0001"]; !ok { + t.Error("CVE-2024-0001 should be in failed set") + } + if _, ok := failed["CVE-2024-0002"]; ok { + t.Error("CVE-2024-0002 should not be in failed set") + } +} + +func TestBatchCreateIssueVariants_WholeChunkHTTPError(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusInternalServerError) + })) + defer srv.Close() + + p := newTestProcessor(t, srv, 25) + vulns := []newVuln{ + {primaryName: "CVE-2024-0001", severity: "HIGH"}, + {primaryName: "CVE-2024-0002", severity: "LOW"}, + } + issueIDByName := map[string]string{ + "CVE-2024-0001": "id-1", + "CVE-2024-0002": "id-2", + } + + failed := p.batchCreateIssueVariants(context.Background(), vulns, issueIDByName) + + if _, ok := failed["CVE-2024-0001"]; !ok { + t.Error("CVE-2024-0001 should be in failed set on HTTP error") + } + if _, ok := failed["CVE-2024-0002"]; !ok { + t.Error("CVE-2024-0002 should be in failed set on HTTP error") + } +} + +func TestBatchCreateIssueVariants_SeverityEnumNotQuoted(t *testing.T) { + var captured string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + captured = string(body) + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(buildDataPayload(map[string]string{ + "i0": variantJSON("v-1", "CVE-2024-0001", "id-1"), + }))) + })) + defer srv.Close() + + p := newTestProcessor(t, srv, 25) + p.batchCreateIssueVariants( + context.Background(), + []newVuln{{primaryName: "CVE-2024-0001", severity: "HIGH"}}, + map[string]string{"CVE-2024-0001": "id-1"}, + ) + + // SeverityValues is a GQL enum — must appear without surrounding quotes. + // e.g. "rating: High" not "rating: \"High\"" + if strings.Contains(captured, `rating: \"`) { + t.Errorf("severity rating should not be quoted as a string in GQL, got: %s", captured) + } + if !strings.Contains(captured, "High") { + t.Errorf("severity High missing from request, got: %s", captured) + } +} + +// --------------------------------------------------------------------------- +// batchAddComponentVersionToIssue +// --------------------------------------------------------------------------- + +func TestBatchAddComponentVersionToIssue_AllSucceed(t *testing.T) { + h := &gqlHandler{ + responses: []string{ + buildDataPayload(map[string]string{ + "i0": linkJSON("link-1"), + "i1": linkJSON("link-2"), + }), + }, + } + srv := httptest.NewServer(h) + defer srv.Close() + + p := newTestProcessor(t, srv, 25) + pairs := []linkPair{ + {primaryName: "CVE-2024-0001", issueId: "id-1", componentVersionId: "cv-1"}, + {primaryName: "CVE-2024-0002", issueId: "id-2", componentVersionId: "cv-1"}, + } + + var callCount int32 + srv.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + atomic.AddInt32(&callCount, 1) + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(buildDataPayload(map[string]string{ + "i0": linkJSON("link-1"), + "i1": linkJSON("link-2"), + }))) + }) + + p.batchAddComponentVersionToIssue(context.Background(), pairs) + + if got := atomic.LoadInt32(&callCount); got != 1 { + t.Fatalf("expected 1 HTTP call, got %d", got) + } +} + +func TestBatchAddComponentVersionToIssue_PartialAliasFail(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(buildPartialPayload( + map[string]string{"i1": linkJSON("link-2")}, + map[string]string{"i0": "not found"}, + ))) + })) + defer srv.Close() + + p := newTestProcessor(t, srv, 25) + pairs := []linkPair{ + {primaryName: "CVE-2024-0001", issueId: "id-1", componentVersionId: "cv-1"}, + {primaryName: "CVE-2024-0002", issueId: "id-2", componentVersionId: "cv-1"}, + } + + p.batchAddComponentVersionToIssue(context.Background(), pairs) +} + +func TestBatchAddComponentVersionToIssue_ChunkBoundary(t *testing.T) { + var callCount int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + atomic.AddInt32(&callCount, 1) + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(buildDataPayload(map[string]string{ + "i0": linkJSON("link-x"), + "i1": linkJSON("link-y"), + }))) + })) + defer srv.Close() + + p := newTestProcessor(t, srv, 2) + pairs := make([]linkPair, 5) + for i := range pairs { + pairs[i] = linkPair{issueId: "id-x", componentVersionId: "cv-1"} + } + + p.batchAddComponentVersionToIssue(context.Background(), pairs) + + if got := atomic.LoadInt32(&callCount); got != 3 { + t.Fatalf("expected 3 HTTP calls, got %d", got) + } +} + +func TestBatchAddComponentVersionToIssue_EmptyPairs(t *testing.T) { + var callCount int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + atomic.AddInt32(&callCount, 1) + })) + defer srv.Close() + + p := newTestProcessor(t, srv, 25) + p.batchAddComponentVersionToIssue(context.Background(), nil) + + if got := atomic.LoadInt32(&callCount); got != 0 { + t.Fatalf("expected 0 HTTP calls for empty pairs, got %d", got) + } +} + +// --------------------------------------------------------------------------- +// ProcessReport — dedup across Results entries +// --------------------------------------------------------------------------- + +// TestProcessReport_DuplicateCVEAcrossResults verifies that a CVE appearing in +// more than one Results entry is only created once. +func TestProcessReport_DuplicateCVEAcrossResults(t *testing.T) { + var mu sync.Mutex + var bodies []string + + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + mu.Lock() + bodies = append(bodies, string(body)) + mu.Unlock() + + w.Header().Set("Content-Type", "application/json") + + // Determine which operation this is by inspecting the body. + s := string(body) + switch { + case strings.Contains(s, "ListIssues"): + _, _ = w.Write([]byte(`{"data":{"Issues":{"edges":[]}}}`)) + case strings.Contains(s, "createIssue"): + _, _ = w.Write([]byte(buildDataPayload(map[string]string{ + "i0": issueJSON("id-1", "CVE-2024-0001"), + }))) + case strings.Contains(s, "createIssueVariant"): + _, _ = w.Write([]byte(buildDataPayload(map[string]string{ + "i0": variantJSON("v-1", "CVE-2024-0001", "id-1"), + }))) + case strings.Contains(s, "addComponentVersionToIssue"): + _, _ = w.Write([]byte(buildDataPayload(map[string]string{ + "i0": linkJSON("link-1"), + }))) + default: + w.WriteHeader(http.StatusBadRequest) + } + })) + defer srv.Close() + + p := newTestProcessor(t, srv, 25) + + report := models.TrivyReport{ + ArtifactName: "test-image", + Results: []types.Result{ + {Vulnerabilities: []types.DetectedVulnerability{ + {VulnerabilityID: "CVE-2024-0001"}, + }}, + // Same CVE in a second result entry — must be deduplicated. + {Vulnerabilities: []types.DetectedVulnerability{ + {VulnerabilityID: "CVE-2024-0001"}, + }}, + }, + } + + p.ProcessReport(report, "cv-1") + + createIssueCount := 0 + mu.Lock() + for _, b := range bodies { + if strings.Contains(b, "createIssue") && !strings.Contains(b, "createIssueVariant") { + createIssueCount++ + } + } + mu.Unlock() + + if createIssueCount != 1 { + t.Fatalf("expected exactly 1 createIssue batch request, got %d", createIssueCount) + } +} diff --git a/scanner/keppel/processor/config.go b/scanner/keppel/processor/config.go index 48e81277..932a6069 100644 --- a/scanner/keppel/processor/config.go +++ b/scanner/keppel/processor/config.go @@ -1,4 +1,4 @@ -// SPDX-FileCopyrightText: 2024 SAP SE or an SAP affiliate company and Greenhouse contributors +// SPDX-FileCopyrightText: 2026 SAP SE or an SAP affiliate company and Greenhouse contributors // SPDX-License-Identifier: Apache-2.0 package processor @@ -10,4 +10,7 @@ type Config struct { CveDetailsUrl string `envconfig:"CVE_DETAILS_URL" required:"true" json:"-" default:"https://nvd.nist.gov/vuln/detail/"` HeurekaRateLimit float64 `envconfig:"HEUREKA_RATE_LIMIT" json:"-" default:"100.0"` HeurekaRateBurst int `envconfig:"HEUREKA_RATE_BURST" json:"-" default:"100"` + // BatchSize controls how many GraphQL aliases are sent per batched mutation. + // Must not exceed the server's GQL_BATCH_LIMIT (default 30). + BatchSize int `envconfig:"HEUREKA_BATCH_SIZE" json:"-" default:"25"` } diff --git a/scanner/keppel/processor/processor.go b/scanner/keppel/processor/processor.go index e885287f..4fe19cd4 100644 --- a/scanner/keppel/processor/processor.go +++ b/scanner/keppel/processor/processor.go @@ -1,4 +1,4 @@ -// SPDX-FileCopyrightText: 2024 SAP SE or an SAP affiliate company and Greenhouse contributors +// SPDX-FileCopyrightText: 2026 SAP SE or an SAP affiliate company and Greenhouse contributors // SPDX-License-Identifier: Apache-2.0 package processor @@ -6,6 +6,7 @@ package processor import ( "context" "fmt" + "net/http" "strings" "github.com/Khan/genqlient/graphql" @@ -25,6 +26,9 @@ type Processor struct { uuid string tag string Client *graphql.Client + httpClient *http.Client + heurekaURL string + BatchSize int CveDetailsUrl string IssueRepositoryUrl string IssueRepositoryName string @@ -32,6 +36,12 @@ type Processor struct { } func NewProcessor(cfg Config, tag string) *Processor { + if cfg.BatchSize <= 0 { + log.WithField("batchSize", cfg.BatchSize). + Warn("HEUREKA_BATCH_SIZE must be > 0; clamping to 1") + cfg.BatchSize = 1 + } + httpClient := util.NewRateLimitedHTTPClient( rate.Limit(cfg.HeurekaRateLimit), cfg.HeurekaRateBurst, @@ -40,6 +50,9 @@ func NewProcessor(cfg Config, tag string) *Processor { gClient := graphql.NewClient(cfg.HeurekaUrl, httpClient) return &Processor{ Client: &gClient, + httpClient: httpClient, + heurekaURL: cfg.HeurekaUrl, + BatchSize: cfg.BatchSize, uuid: uuid.New().String(), tag: tag, IssueRepositoryName: cfg.IssueRepositoryName, @@ -166,8 +179,22 @@ func (p *Processor) ProcessManifest( } func (p *Processor) ProcessReport(report models.TrivyReport, componentVersionId string) { + ctx := context.Background() + + // Phase 0: classify vulnerabilities into known (already in Heureka) vs new. + // seenCVE deduplicates across Results entries: a CVE seen more than once in + // the same report is only created/linked once per componentVersion. + seenCVE := make(map[string]struct{}) + var toCreate []newVuln + var toLink []linkPair + for _, result := range report.Results { for _, vulnerability := range result.Vulnerabilities { + if _, seen := seenCVE[vulnerability.VulnerabilityID]; seen { + continue + } + seenCVE[vulnerability.VulnerabilityID] = struct{}{} + issue, err := p.GetIssue(vulnerability.VulnerabilityID) if err != nil { fields := log.Fields{ @@ -177,7 +204,6 @@ func (p *Processor) ProcessReport(report models.TrivyReport, componentVersionId "issueID": "", "issuePrimaryName": "", } - if issue != nil { fields["issueID"] = issue.Id fields["issuePrimaryName"] = issue.PrimaryName @@ -185,63 +211,67 @@ func (p *Processor) ProcessReport(report models.TrivyReport, componentVersionId log.WithFields(fields).WithError(err).Error("Error while getting issue") continue } + if issue == nil { - // create only cve issues if !strings.HasPrefix(strings.ToLower(vulnerability.VulnerabilityID), "cve") { log.WithFields(log.Fields{ "vulnerabilityID": vulnerability.VulnerabilityID, }).Warning("VulnerabilityID does not start with 'CVE'") continue } - i, err := p.CreateIssue(vulnerability.VulnerabilityID, vulnerability.Description) - if err != nil { - log.Error(err) - continue - } - issue = i cvssVector := "" - // check if nvd CVSS vector is available if vulnerability.CVSS != nil { - if _, ok := vulnerability.CVSS["nvd"]; ok { - cvssVector = vulnerability.CVSS["nvd"].V3Vector + if nvd, ok := vulnerability.CVSS["nvd"]; ok { + cvssVector = nvd.V3Vector } } - _, err = p.CreateIssueVariant( - vulnerability.VulnerabilityID, - vulnerability.Description, - issue.Id, - cvssVector, - vulnerability.Severity, - ) - if err != nil { - log.Error(err) - continue - } - } - _, err = client.AddComponentVersionToIssue( - context.Background(), - *p.Client, - issue.Id, - componentVersionId, - ) - - if err != nil { - log.WithFields(log.Fields{ - "issueId": issue.Id, - "componentVersionId": componentVersionId, - }).WithError(err).Error("Could not add component version to issue") + toCreate = append(toCreate, newVuln{ + primaryName: vulnerability.VulnerabilityID, + description: vulnerability.Description, + cvssVector: cvssVector, + severity: vulnerability.Severity, + }) } else { - log.WithFields(log.Fields{ - "issueId": issue.Id, - "componentVersionId": componentVersionId, - }).Info("Added issue to componentVersion") + toLink = append(toLink, linkPair{ + primaryName: vulnerability.VulnerabilityID, + issueId: issue.Id, + componentVersionId: componentVersionId, + }) } } } + // Phase 1: batch-create Issues for new CVEs. + createdIssues := p.batchCreateIssues(ctx, toCreate) + + // Phase 2: batch-create IssueVariants for the successfully created Issues. + issueIDByName := make(map[string]string, len(createdIssues)) + var vulnsWithIssue []newVuln + for _, v := range toCreate { + if issue, ok := createdIssues[v.primaryName]; ok { + issueIDByName[v.primaryName] = issue.Id + vulnsWithIssue = append(vulnsWithIssue, v) + } + } + variantFailed := p.batchCreateIssueVariants(ctx, vulnsWithIssue, issueIDByName) + + // Phase 3: batch-link all CVEs that have a resolved issue ID. + // Mirrors the serial behaviour: skip linking if IssueVariant creation failed. + for _, v := range vulnsWithIssue { + if _, failed := variantFailed[v.primaryName]; failed { + continue + } + toLink = append(toLink, linkPair{ + primaryName: v.primaryName, + issueId: issueIDByName[v.primaryName], + componentVersionId: componentVersionId, + }) + } + p.batchAddComponentVersionToIssue(ctx, toLink) + if report.Metadata.OS != nil && report.Metadata.OS.Eosl { _, err := client.UpdateComponentVersion( - context.Background(), + ctx, *p.Client, componentVersionId, &client.ComponentVersionInput{