Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
7 changes: 4 additions & 3 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
18 changes: 10 additions & 8 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -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=
Expand Down Expand Up @@ -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=
Expand Down
284 changes: 284 additions & 0 deletions scanner/keppel/processor/batch.go
Original file line number Diff line number Diff line change
@@ -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)")
}
}
}
Loading
Loading