diff --git a/AGENTS.md b/AGENTS.md index c023723eaf0..7ac906f9c98 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -331,7 +331,7 @@ All Go microservices are compiled using a single, unified multi-target Dockerfil - Long-running metrics collector daemon (`go/cmd/custommetrics/`) that periodically reads batch/dataset state from Datastore (`JobData`, `SourceRepository`, `ImportFindings`) and GCS (`all.zip`, `modified_id.csv`) and exposes dataset, drift, reconciler, deleter, and linter state metrics on `:9090/metrics` for GMP/Grafana. 13. **`vanir_signatures`**: - - Cron job orchestrated in Go (`go/cmd/vanir_signatures/` and `go/internal/vanir/`) that queries modified vulnerabilities, generates Vanir signatures, and writes them back to the database. Supports both remote Cloud Run `vanir-sandbox` execution (via `VANIR_SANDBOX_URL`) and local `generate_signatures.py` fallback. + - Distroless Go cron job (`go/cmd/vanir_signatures/` and `go/internal/vanir/`) that queries modified vulnerabilities, delegates signature generation to the remote Cloud Run `vanir-sandbox` service (required `VANIR_SANDBOX_URL`), and writes results back to the database. Local non-sandbox execution is disabled. 14. **`vanir_sandbox`**: - Untrusted Cloud Run Gen2 HTTP service (`go/cmd/vanir_sandbox/`) that executes `generate_signatures.py` for a single vulnerability record per request under a unique non-root Linux UID, isolated `0700` work directory, and fail-closed post-request `kill(-1, SIGKILL)` UID reaping, running with a zero-IAM-role service account and no VPC access. diff --git a/deployment/build-and-stage.yaml b/deployment/build-and-stage.yaml index 85cae3ec233..c09c6950608 100644 --- a/deployment/build-and-stage.yaml +++ b/deployment/build-and-stage.yaml @@ -287,7 +287,7 @@ steps: # Build/push vanir-signatures images to gcr.io/oss-vdb. - name: gcr.io/cloud-builders/docker - args: ['buildx', 'build', '--load', '-t', 'gcr.io/oss-vdb/vanir-signatures:latest', '-t', 'gcr.io/oss-vdb/vanir-signatures:$COMMIT_SHA', '--target', 'vanir-signatures', '--build-context', 'bindings=../bindings', '--build-context', 'poetry=../docker/poetry', '-f', 'Dockerfile', '--pull', '.'] + args: ['buildx', 'build', '--load', '-t', 'gcr.io/oss-vdb/vanir-signatures:latest', '-t', 'gcr.io/oss-vdb/vanir-signatures:$COMMIT_SHA', '--target', 'vanir-signatures', '--build-context', 'bindings=../bindings', '-f', 'Dockerfile', '--pull', '.'] dir: 'go' id: 'build-vanir-signatures' waitFor: ['build-importer'] diff --git a/deployment/clouddeploy/gke-workers/base/extra/vanir-signatures.yaml b/deployment/clouddeploy/gke-workers/base/extra/vanir-signatures.yaml index a30408b0225..735feab95a1 100644 --- a/deployment/clouddeploy/gke-workers/base/extra/vanir-signatures.yaml +++ b/deployment/clouddeploy/gke-workers/base/extra/vanir-signatures.yaml @@ -18,11 +18,11 @@ spec: imagePullPolicy: Always resources: requests: - cpu: "12" - memory: "100Gi" + cpu: "1" + memory: "2Gi" limits: - cpu: "28" - memory: "220Gi" + cpu: "2" + memory: "4Gi" env: - name: POSTGRES_PORT value: "6432" @@ -37,10 +37,4 @@ spec: secretKeyRef: name: osv-db-worker-password key: password - nodeSelector: - cloud.google.com/gke-nodepool: highend - tolerations: - - key: workloadType - operator: Equal - value: highend restartPolicy: Never diff --git a/deployment/clouddeploy/gke-workers/environments/oss-vdb-test/vanir-signatures.yaml b/deployment/clouddeploy/gke-workers/environments/oss-vdb-test/vanir-signatures.yaml index 28a22d62eeb..2eafc6d0342 100644 --- a/deployment/clouddeploy/gke-workers/environments/oss-vdb-test/vanir-signatures.yaml +++ b/deployment/clouddeploy/gke-workers/environments/oss-vdb-test/vanir-signatures.yaml @@ -17,3 +17,6 @@ spec: value: osv-test-vulnerabilities - name: POSTGRES_HOST value: "172.24.1.3" + # Deterministic Cloud Run URL: https://-..run.app + - name: VANIR_SANDBOX_URL + value: "https://vanir-sandbox-175272184261.us-west2.run.app" diff --git a/deployment/clouddeploy/gke-workers/environments/oss-vdb/vanir-signatures.yaml b/deployment/clouddeploy/gke-workers/environments/oss-vdb/vanir-signatures.yaml index a35cc211c2a..9071dc93de4 100644 --- a/deployment/clouddeploy/gke-workers/environments/oss-vdb/vanir-signatures.yaml +++ b/deployment/clouddeploy/gke-workers/environments/oss-vdb/vanir-signatures.yaml @@ -17,3 +17,6 @@ spec: value: osv-vulnerabilities - name: POSTGRES_HOST value: "10.25.1.3" + # Deterministic Cloud Run URL: https://-..run.app + - name: VANIR_SANDBOX_URL + value: "https://vanir-sandbox-651737493649.us-west2.run.app" diff --git a/go/Dockerfile b/go/Dockerfile index 3924a14f5e9..2850e1da89f 100644 --- a/go/Dockerfile +++ b/go/Dockerfile @@ -234,6 +234,18 @@ RUN --mount=type=cache,target=/go/pkg/mod \ --mount=type=cache,target=/root/.cache/go-build \ CGO_ENABLED=0 go build -o /app/vanir_signatures ./cmd/vanir_signatures/ +FROM gcr.io/distroless/static-debian12@sha256:d75cdd72874d4790092fcb1b058493ecf6bb5bf2b2b897045b00ff01d91843f2 AS vanir-signatures +COPY --from=vanir-signatures-build /app/vanir_signatures / +ENTRYPOINT ["/vanir_signatures"] + +# ======================================================== +# Target: Vanir Sandbox +# ======================================================== +FROM builder AS vanir-sandbox-build +RUN --mount=type=cache,target=/go/pkg/mod \ + --mount=type=cache,target=/root/.cache/go-build \ + CGO_ENABLED=0 go build -o /app/vanir_sandbox ./cmd/vanir_sandbox/ + FROM python:3.13-slim@sha256:8d9d0b8bcf6506481eae4907c18f5e3e7902e629f5f6d684f9e7c32e85e3ddf0 AS vanir-python-deps ENV POETRY_HOME="/opt/poetry" COPY --from=poetry requirements.txt ./poetry-requirements.txt @@ -245,23 +257,6 @@ COPY cmd/vanir_signatures/pyproject.toml cmd/vanir_signatures/poetry.lock ./ COPY cmd/vanir_signatures/osv/pyproject.toml cmd/vanir_signatures/osv/README.md cmd/vanir_signatures/osv/vulnerability_pb2.py ./osv/ RUN POETRY_VIRTUALENVS_IN_PROJECT=true poetry install --only main --no-interaction --no-ansi -FROM python:3.13-slim@sha256:8d9d0b8bcf6506481eae4907c18f5e3e7902e629f5f6d684f9e7c32e85e3ddf0 AS vanir-signatures -RUN apt-get update && apt-get install -y --no-install-recommends git ca-certificates && rm -rf /var/lib/apt/lists/* -COPY --from=vanir-python-deps /app/.venv /app/.venv -ENV PATH="/app/.venv/bin:$PATH" -COPY --from=vanir-signatures-build /app/vanir_signatures /usr/local/bin/vanir_signatures -COPY cmd/vanir_signatures/generate_signatures.py /usr/local/bin/generate_signatures.py -RUN chmod 755 /usr/local/bin/generate_signatures.py -ENTRYPOINT ["/usr/local/bin/vanir_signatures"] - -# ======================================================== -# Target: Vanir Sandbox -# ======================================================== -FROM builder AS vanir-sandbox-build -RUN --mount=type=cache,target=/go/pkg/mod \ - --mount=type=cache,target=/root/.cache/go-build \ - CGO_ENABLED=0 go build -o /app/vanir_sandbox ./cmd/vanir_sandbox/ - FROM python:3.13-slim@sha256:8d9d0b8bcf6506481eae4907c18f5e3e7902e629f5f6d684f9e7c32e85e3ddf0 AS vanir-sandbox RUN apt-get update && apt-get install -y --no-install-recommends git ca-certificates tini && \ rm -rf /var/lib/apt/lists/* && \ diff --git a/go/cmd/vanir_signatures/main.go b/go/cmd/vanir_signatures/main.go index dd017cf79ad..686bbd5b8f9 100644 --- a/go/cmd/vanir_signatures/main.go +++ b/go/cmd/vanir_signatures/main.go @@ -40,47 +40,25 @@ func main() { maxWorkers int dryRun bool hours int - pythonBin string - scriptPath string sandboxURL string ) - flag.IntVar(&batchSize, "batch-size", 100, "Number of vulnerabilities to process in each batch.") - flag.IntVar(&maxWorkers, "max-workers", 10, "Maximum number of parallel batch workers.") + flag.IntVar(&batchSize, "batch-size", 1, "Number of vulnerabilities to process serially per worker batch.") + flag.IntVar(&maxWorkers, "max-workers", 15, "Maximum number of parallel workers calling vanir-sandbox.") flag.BoolVar(&dryRun, "dry-run", false, "Perform a dry run without modifying GCS or Datastore.") flag.IntVar(&hours, "hours", 0, "Number of hours back to process modified records.") - flag.StringVar(&pythonBin, "python-bin", "python3", "Python interpreter binary to use.") - flag.StringVar(&scriptPath, "script-path", "/usr/local/bin/generate_signatures.py", "Path to the Python Vanir signature generation script.") - flag.StringVar(&sandboxURL, "sandbox-url", os.Getenv("VANIR_SANDBOX_URL"), "URL of the remote Cloud Run vanir-sandbox service (defaults to VANIR_SANDBOX_URL). If empty, runs generate_signatures.py locally.") + flag.StringVar(&sandboxURL, "sandbox-url", os.Getenv("VANIR_SANDBOX_URL"), "Required URL of the remote Cloud Run vanir-sandbox service (defaults to VANIR_SANDBOX_URL).") flag.Parse() - batchSizeSet := false - maxWorkersSet := false - flag.Visit(func(f *flag.Flag) { - switch f.Name { - case "batch-size": - batchSizeSet = true - case "max-workers": - maxWorkersSet = true - } - }) - // Cloud Run vanir-sandbox processes one vulnerability per request (concurrency=1); - // default to batch-size=1 and max-workers=15 so Runner fans out across instances - // and isolates retries. - if sandboxURL != "" { - if !batchSizeSet { - batchSize = 1 - } - if !maxWorkersSet { - maxWorkers = 15 - } - } - logger.InitGlobalLogger() defer logger.Close() ctx := context.Background() + if strings.TrimSpace(sandboxURL) == "" { + logger.FatalContext(ctx, "VANIR_SANDBOX_URL environment variable or -sandbox-url flag must be set (local non-sandbox execution is disabled)") + } + projectID := os.Getenv("GOOGLE_CLOUD_PROJECT") if projectID == "" { logger.FatalContext(ctx, "GOOGLE_CLOUD_PROJECT environment variable not set") @@ -124,17 +102,11 @@ func main() { } jobStore := osvdatastore.NewJobDataStore(dsClient) - var generator vanir.SignatureGenerator - if sandboxURL != "" { - httpGen, err := vanir.NewHTTPSignatureGenerator(ctx, sandboxURL) - if err != nil { - logger.FatalContext(ctx, "Failed to create HTTP Vanir sandbox generator", slog.Any("error", err)) - } - generator = httpGen - logger.InfoContext(ctx, "Using remote Vanir sandbox generator", slog.String("sandbox_url", sandboxURL)) - } else { - generator = vanir.NewPythonGenerator(pythonBin, scriptPath) + generator, err := vanir.NewHTTPSignatureGenerator(ctx, sandboxURL) + if err != nil { + logger.FatalContext(ctx, "Failed to create HTTP Vanir sandbox generator", slog.Any("error", err)) } + logger.InfoContext(ctx, "Using remote Vanir sandbox generator", slog.String("sandbox_url", generator.SandboxURL)) runner := &vanir.Runner{ VulnStore: vulnStore, diff --git a/go/internal/vanir/generator.go b/go/internal/vanir/generator.go index 2ca984472e5..177fb24a047 100644 --- a/go/internal/vanir/generator.go +++ b/go/internal/vanir/generator.go @@ -15,21 +15,10 @@ package vanir import ( - "bytes" "context" - "encoding/json" - "fmt" - "log/slog" - "os" - "os/exec" - "path/filepath" - "strconv" - "strings" "time" - "github.com/google/osv.dev/go/logger" "github.com/ossf/osv-schema/bindings/go/osvschema" - "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/types/known/structpb" ) @@ -40,152 +29,5 @@ type SignatureMap map[string]map[int][]*structpb.Value // SignatureGenerator abstracts the Vanir signature generation engine. type SignatureGenerator interface { - GenerateBatch(ctx context.Context, vulns []*osvschema.Vulnerability, gitWorkingDir string) (SignatureMap, error) -} - -// PythonGenerator shells out to the Python Vanir helper script to generate signatures for a batch. -type PythonGenerator struct { - PythonBin string - ScriptPath string - Timeout time.Duration -} - -var _ SignatureGenerator = (*PythonGenerator)(nil) - -func NewPythonGenerator(pythonBin, scriptPath string) *PythonGenerator { - if pythonBin == "" { - pythonBin = "python3" - } - if scriptPath == "" { - scriptPath = "/usr/local/bin/generate_signatures.py" - } - - return &PythonGenerator{ - PythonBin: pythonBin, - ScriptPath: scriptPath, - Timeout: defaultBatchTimeout, - } -} - -func (g *PythonGenerator) GenerateBatch(ctx context.Context, vulns []*osvschema.Vulnerability, workingDir string) (SignatureMap, error) { - if len(vulns) == 0 { - return SignatureMap{}, nil - } - - ipcDir, err := os.MkdirTemp(workingDir, "vanir-ipc-*") - if err != nil { - return nil, fmt.Errorf("failed to create IPC temp dir: %w", err) - } - defer os.RemoveAll(ipcDir) - gitDir, err := os.MkdirTemp(workingDir, "vanir-git-*") - if err != nil { - return nil, fmt.Errorf("failed to create git temp dir: %w", err) - } - defer os.RemoveAll(gitDir) - - inputPath := filepath.Join(ipcDir, "input.json") - outputPath := filepath.Join(ipcDir, "output.json") - - marshaler := protojson.MarshalOptions{UseProtoNames: true} - rawMessages := make([]json.RawMessage, 0, len(vulns)) - for _, v := range vulns { - b, err := marshaler.Marshal(v) - if err != nil { - return nil, fmt.Errorf("failed to marshal vulnerability %s to JSON: %w", v.GetId(), err) - } - rawMessages = append(rawMessages, json.RawMessage(b)) - } - - inputData, err := json.Marshal(rawMessages) - if err != nil { - return nil, fmt.Errorf("failed to marshal batch JSON array: %w", err) - } - - if err := os.WriteFile(inputPath, inputData, 0600); err != nil { - return nil, fmt.Errorf("failed to write input JSON file: %w", err) - } - - timeout := g.Timeout - if timeout <= 0 { - timeout = defaultBatchTimeout - } - cmdCtx, cancel := context.WithTimeout(ctx, timeout) - defer cancel() - - //nolint:gosec // G204: PythonBin and ScriptPath are trusted service configuration paths. - cmd := exec.CommandContext( - cmdCtx, - g.PythonBin, - g.ScriptPath, - "--input", inputPath, - "--output", outputPath, - "--git-working-dir", gitDir, - ) - cmd.Env = filteredEnv(os.Environ()) - cmd.WaitDelay = 10 * time.Second - var stderr bytes.Buffer - cmd.Stdout = &stderr - cmd.Stderr = &stderr - - if err := cmd.Run(); err != nil { - logger.ErrorContext(ctx, "Python Vanir signature generation failed", - slog.Any("error", err), - slog.String("output", stderr.String())) - - return nil, fmt.Errorf("vanir python runner failed: %w", err) - } - - if stderr.Len() > 0 { - logger.DebugContext(ctx, "Python Vanir runner output", slog.String("output", stderr.String())) - } - - outputData, err := os.ReadFile(outputPath) - if err != nil { - return nil, fmt.Errorf("failed to read output JSON file: %w", err) - } - - var rawOutput map[string]map[string][]any - if err := json.Unmarshal(outputData, &rawOutput); err != nil { - return nil, fmt.Errorf("failed to unmarshal output JSON: %w", err) - } - - result := make(SignatureMap, len(rawOutput)) - for vulnID, affectedMap := range rawOutput { - idxMap := make(map[int][]*structpb.Value, len(affectedMap)) - for idxStr, sigList := range affectedMap { - idx, err := strconv.Atoi(idxStr) - if err != nil { - return nil, fmt.Errorf("invalid affected index %q for %s: %w", idxStr, vulnID, err) - } - vals := make([]*structpb.Value, 0, len(sigList)) - for _, rawSig := range sigList { - val, err := structpb.NewValue(rawSig) - if err != nil { - return nil, fmt.Errorf("failed to convert signature to structpb.Value for %s: %w", vulnID, err) - } - vals = append(vals, val) - } - if len(vals) > 0 { - idxMap[idx] = vals - } - } - if len(idxMap) > 0 { - result[vulnID] = idxMap - } - } - - return result, nil -} - -// filteredEnv strips PostgreSQL connection variables (including POSTGRES_PASSWORD) -// so database credentials are not exposed to the Python Vanir subprocess. -func filteredEnv(env []string) []string { - out := make([]string, 0, len(env)) - for _, entry := range env { - if !strings.HasPrefix(entry, "POSTGRES_") { - out = append(out, entry) - } - } - - return out + GenerateBatch(ctx context.Context, vulns []*osvschema.Vulnerability) (SignatureMap, error) } diff --git a/go/internal/vanir/http_generator.go b/go/internal/vanir/http_generator.go index 5b1c9c01301..b154cb115d9 100644 --- a/go/internal/vanir/http_generator.go +++ b/go/internal/vanir/http_generator.go @@ -94,7 +94,7 @@ func NewHTTPSignatureGenerator(ctx context.Context, sandboxURL string) (*HTTPSig }, nil } -func (g *HTTPSignatureGenerator) GenerateBatch(ctx context.Context, vulns []*osvschema.Vulnerability, _ string) (SignatureMap, error) { +func (g *HTTPSignatureGenerator) GenerateBatch(ctx context.Context, vulns []*osvschema.Vulnerability) (SignatureMap, error) { result := make(SignatureMap, len(vulns)) for _, v := range vulns { if v == nil { diff --git a/go/internal/vanir/http_generator_test.go b/go/internal/vanir/http_generator_test.go index 8e07e67601a..527fd610719 100644 --- a/go/internal/vanir/http_generator_test.go +++ b/go/internal/vanir/http_generator_test.go @@ -79,7 +79,7 @@ func TestHTTPSignatureGenerator(t *testing.T) { testVuln("OSV-NONCANON-IDX"), testVuln("OSV-BAD-SIG"), testVuln("OSV-EMPTY"), - }, "") + }) if err != nil { t.Fatalf("GenerateBatch: %v", err) } @@ -122,7 +122,7 @@ func TestHTTPSignatureGenerator_RetriesAndErrors(t *testing.T) { })) t.Cleanup(flaky.Close) gen := &HTTPSignatureGenerator{SandboxURL: flaky.URL, HTTPClient: flaky.Client(), retryBackoff: time.Millisecond} - got, err := gen.GenerateBatch(context.Background(), []*osvschema.Vulnerability{testVuln("OSV-RETRY")}, "") + got, err := gen.GenerateBatch(context.Background(), []*osvschema.Vulnerability{testVuln("OSV-RETRY")}) if err != nil || len(got["OSV-RETRY"][0]) != 1 || attempts.Load() != 3 { t.Fatalf("retry failed: got=%+v err=%v attempts=%d", got, err, attempts.Load()) } @@ -143,7 +143,7 @@ func TestHTTPSignatureGenerator_RetriesAndErrors(t *testing.T) { })) t.Cleanup(dropper.Close) dropGen := &HTTPSignatureGenerator{SandboxURL: dropper.URL, HTTPClient: dropper.Client(), retryBackoff: time.Millisecond} - got, err = dropGen.GenerateBatch(context.Background(), []*osvschema.Vulnerability{testVuln("OSV-DROP")}, "") + got, err = dropGen.GenerateBatch(context.Background(), []*osvschema.Vulnerability{testVuln("OSV-DROP")}) if err != nil || len(got["OSV-DROP"][0]) != 1 || transportAttempts.Load() != 3 { t.Fatalf("transport retry failed: got=%+v err=%v attempts=%d", got, err, transportAttempts.Load()) } @@ -156,7 +156,7 @@ func TestHTTPSignatureGenerator_RetriesAndErrors(t *testing.T) { })) t.Cleanup(timedOut.Close) _, err = (&HTTPSignatureGenerator{SandboxURL: timedOut.URL, HTTPClient: timedOut.Client(), retryBackoff: time.Millisecond}). - GenerateBatch(context.Background(), []*osvschema.Vulnerability{testVuln("OSV-TIMEOUT")}, "") + GenerateBatch(context.Background(), []*osvschema.Vulnerability{testVuln("OSV-TIMEOUT")}) if err == nil || !strings.Contains(err.Error(), "status 504") || timeoutAttempts.Load() != 1 { t.Fatalf("expected 504 to fail without retry: err=%v attempts=%d", err, timeoutAttempts.Load()) } @@ -174,7 +174,7 @@ func TestHTTPSignatureGenerator_RetriesAndErrors(t *testing.T) { })) t.Cleanup(redir.Close) - _, err := (&HTTPSignatureGenerator{SandboxURL: redir.URL}).GenerateBatch(context.Background(), []*osvschema.Vulnerability{testVuln("OSV-REDIR")}, "") + _, err := (&HTTPSignatureGenerator{SandboxURL: redir.URL}).GenerateBatch(context.Background(), []*osvschema.Vulnerability{testVuln("OSV-REDIR")}) if err == nil || redirectHit.Load() || !strings.Contains(err.Error(), fmt.Sprintf("status %d", code)) { t.Errorf("redirect %d should be refused without hitting target (err=%v hit=%v)", code, err, redirectHit.Load()) } @@ -196,7 +196,7 @@ func TestHTTPSignatureGenerator_RetriesAndErrors(t *testing.T) { _, _ = w.Write([]byte(tc.body)) })) t.Cleanup(srv.Close) - _, err := (&HTTPSignatureGenerator{SandboxURL: srv.URL}).GenerateBatch(context.Background(), []*osvschema.Vulnerability{testVuln("OSV-ERR")}, "") + _, err := (&HTTPSignatureGenerator{SandboxURL: srv.URL}).GenerateBatch(context.Background(), []*osvschema.Vulnerability{testVuln("OSV-ERR")}) if err == nil || !strings.Contains(err.Error(), tc.wantSub) { t.Errorf("%s: got err=%v, want substring %q", tc.name, err, tc.wantSub) } diff --git a/go/internal/vanir/runner.go b/go/internal/vanir/runner.go index 6b2fc20d6d5..1879a436f6f 100644 --- a/go/internal/vanir/runner.go +++ b/go/internal/vanir/runner.go @@ -18,7 +18,6 @@ import ( "context" "errors" "log/slog" - "os" "slices" "sync" "time" @@ -58,11 +57,11 @@ func (r *Runner) now() time.Time { func (r *Runner) Run(ctx context.Context) error { batchSize := r.Config.BatchSize if batchSize <= 0 { - batchSize = 100 + batchSize = 1 } maxWorkers := r.Config.MaxWorkers if maxWorkers <= 0 { - maxWorkers = 10 + maxWorkers = 15 } currentRun := r.now() @@ -239,19 +238,7 @@ func (r *Runner) processBatch(ctx context.Context, batch []*osvschema.Vulnerabil logger.InfoContext(ctx, "Processing batch of vulnerabilities", slog.Int("count", len(batch))) - batchTempDir, err := os.MkdirTemp("", "vanir-batch-*") - if err != nil { - logger.ErrorContext(ctx, "Failed to create temporary directory for batch", slog.Any("error", err)) - ids := make([]string, 0, len(batch)) - for _, v := range batch { - ids = append(ids, v.GetId()) - } - - return 0, ids - } - defer os.RemoveAll(batchTempDir) - - sigMap, err := r.Generator.GenerateBatch(ctx, batch, batchTempDir) + sigMap, err := r.Generator.GenerateBatch(ctx, batch) if err != nil { logger.ErrorContext(ctx, "Failed to generate Vanir signatures for batch", slog.Int("count", len(batch)), slog.Any("error", err)) ids := make([]string, 0, len(batch)) diff --git a/go/internal/vanir/vanir_test.go b/go/internal/vanir/vanir_test.go index 01cc69a2ccf..4ee6c0d6c6a 100644 --- a/go/internal/vanir/vanir_test.go +++ b/go/internal/vanir/vanir_test.go @@ -19,8 +19,6 @@ import ( "errors" "fmt" "iter" - "os" - "path/filepath" "reflect" "slices" "sync" @@ -157,7 +155,7 @@ type fakeGenerator struct { results SignatureMap } -func (g *fakeGenerator) GenerateBatch(_ context.Context, vulns []*osvschema.Vulnerability, _ string) (SignatureMap, error) { +func (g *fakeGenerator) GenerateBatch(_ context.Context, vulns []*osvschema.Vulnerability) (SignatureMap, error) { g.mu.Lock() defer g.mu.Unlock() g.batches = append(g.batches, slices.Clone(vulns)) @@ -444,55 +442,3 @@ func TestRunner_GlobalBatching(t *testing.T) { t.Fatalf("expected 2 batches, got %d", len(gen.batches)) } } - -func TestPythonGenerator_GenerateBatch(t *testing.T) { - ctx := context.Background() - tempDir := t.TempDir() - t.Setenv("POSTGRES_PASSWORD", "super-secret") - - scriptPath := filepath.Join(tempDir, "mock_vanir.py") - scriptContent := `#!/usr/bin/env python3 -import argparse, json, os, sys -if any(k.startswith('POSTGRES_') for k in os.environ): - sys.exit('POSTGRES_* env leaked to subprocess') -parser = argparse.ArgumentParser() -parser.add_argument('--input', required=True) -parser.add_argument('--output', required=True) -parser.add_argument('--git-working-dir', required=True) -args = parser.parse_args() -with open(args.input) as f: - vulns = json.load(f) -out = {} -for v in vulns: - out[v['id']] = {'0': [{'id': 'SIG-' + v['id'], 'signature_type': 'Function', 'signature_version': 'v1'}]} -with open(args.output, 'w') as f: - json.dump(out, f) -` - if err := os.WriteFile(scriptPath, []byte(scriptContent), 0600); err != nil { - t.Fatalf("WriteFile: %v", err) - } - - gen := NewPythonGenerator("python3", scriptPath) - vulns := []*osvschema.Vulnerability{ - { - Id: "VULN-IPC-1", - Modified: timestamppb.New(time.Now()), - Affected: []*osvschema.Affected{ - {Ranges: []*osvschema.Range{{Type: osvschema.Range_GIT, Repo: "https://example.com/repo"}}}, - }, - }, - } - - res, err := gen.GenerateBatch(ctx, vulns, tempDir) - if err != nil { - t.Fatalf("GenerateBatch failed: %v", err) - } - - sigs := res["VULN-IPC-1"][0] - if len(sigs) != 1 { - t.Fatalf("expected 1 signature, got %d", len(sigs)) - } - if gotID := sigs[0].GetStructValue().GetFields()["id"].GetStringValue(); gotID != "SIG-VULN-IPC-1" { - t.Errorf("got signature ID %q, want SIG-VULN-IPC-1", gotID) - } -}