From 290d92389503d6484b63112033c9bf3ac3b64187 Mon Sep 17 00:00:00 2001 From: Rex P Date: Tue, 24 Nov 2026 15:43:07 +1100 Subject: [PATCH 1/7] feat(vanir): add vanir-sandbox Cloud Run service and HTTP orchestrator --- AGENTS.md | 7 +- deployment/build-and-stage.yaml | 23 + .../vanir-sandbox/clouddeploy.yaml | 39 ++ .../clouddeploy/vanir-sandbox/run-prod.yaml | 31 ++ .../vanir-sandbox/run-staging.yaml | 31 ++ .../clouddeploy/vanir-sandbox/skaffold.yaml | 18 + deployment/deploy-prod.yaml | 4 + .../environments/oss-vdb-test/main.tf | 5 + .../terraform/environments/oss-vdb/main.tf | 5 + deployment/terraform/modules/osv/outputs.tf | 5 + .../terraform/modules/osv/vanir_sandbox.tf | 72 +++ go/Dockerfile | 21 +- go/cmd/vanir_sandbox/main.go | 489 ++++++++++++++++++ go/cmd/vanir_sandbox/main_test.go | 141 +++++ go/cmd/vanir_signatures/main.go | 15 +- go/internal/vanir/http_generator.go | 288 +++++++++++ go/internal/vanir/http_generator_test.go | 157 ++++++ 17 files changed, 1347 insertions(+), 4 deletions(-) create mode 100644 deployment/clouddeploy/vanir-sandbox/clouddeploy.yaml create mode 100644 deployment/clouddeploy/vanir-sandbox/run-prod.yaml create mode 100644 deployment/clouddeploy/vanir-sandbox/run-staging.yaml create mode 100644 deployment/clouddeploy/vanir-sandbox/skaffold.yaml create mode 100644 deployment/terraform/modules/osv/vanir_sandbox.tf create mode 100644 go/cmd/vanir_sandbox/main.go create mode 100644 go/cmd/vanir_sandbox/main_test.go create mode 100644 go/internal/vanir/http_generator.go create mode 100644 go/internal/vanir/http_generator_test.go diff --git a/AGENTS.md b/AGENTS.md index c4e097266d0..3cce1b1f637 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -331,9 +331,12 @@ 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, shells out to a minimal Python helper script (`generate_signatures.py`) to run Vanir signature generation, and writes enriched signatures back to the database. + - 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. -14. **`ubuntubinarymapper`**: +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, IPC/UTS namespaces, and fail-closed post-request `kill(-1, SIGKILL)` UID reaping, running with a zero-IAM-role service account and no VPC access. + +15. **`ubuntubinarymapper`**: - Run as a cron job (`go/cmd/ubuntubinarymapper/`). - Reads `Ubuntu/modified_id.csv` from the exported GCS bucket (`gs://osv-vulnerabilities`) with a 1-hour lookback window, downloads modified Ubuntu vulnerability records (via `Ubuntu/all.zip` or individual `Ubuntu/.json` files), extracts binary-to-source package name mappings from `ecosystem_specific`, and persists them to Datastore (`UbuntuPackageMapping`) alongside a `JobData` execution checkpoint (or to a local JSON file via `-output-json`). diff --git a/deployment/build-and-stage.yaml b/deployment/build-and-stage.yaml index 685ac8cc451..a9e84c0a529 100644 --- a/deployment/build-and-stage.yaml +++ b/deployment/build-and-stage.yaml @@ -298,6 +298,19 @@ steps: args: ['push', '--all-tags', 'gcr.io/oss-vdb/vanir-signatures'] waitFor: ['build-vanir-signatures', 'cloud-build-queue'] +# Build/push vanir-sandbox images to gcr.io/oss-vdb. +- name: gcr.io/cloud-builders/docker + args: ['buildx', 'build', '--load', '-t', 'gcr.io/oss-vdb/vanir-sandbox:latest', '-t', 'gcr.io/oss-vdb/vanir-sandbox:$COMMIT_SHA', '--target', 'vanir-sandbox', '--build-context', 'bindings=../bindings', '--build-context', 'poetry=../docker/poetry', '-f', 'Dockerfile', '--pull', '.'] + dir: 'go' + id: 'build-vanir-sandbox' + waitFor: ['build-vanir-signatures'] + volumes: + - name: 'docker-config' + path: '/root/.docker' +- name: gcr.io/cloud-builders/docker + args: ['push', '--all-tags', 'gcr.io/oss-vdb/vanir-sandbox'] + waitFor: ['build-vanir-sandbox', 'cloud-build-queue'] + # Build/push cron job images. - name: gcr.io/cloud-builders/docker args: ['build', '-t', 'gcr.io/oss-vdb/cron:latest', '-t', 'gcr.io/oss-vdb/cron:$COMMIT_SHA', '.'] @@ -583,6 +596,16 @@ steps: id: 'deploy-osv-website' waitFor: ['goose-up'] +# Vanir Sandbox +- name: 'gcr.io/cloud-builders/gcloud' + args: ['deploy', 'releases', 'create', 'osv-$SHORT_SHA', '--project=oss-vdb', '--region=us-central1', + '--delivery-pipeline=vanir-sandbox', '--images', + "vanir-sandbox=gcr.io/oss-vdb/vanir-sandbox:$COMMIT_SHA" + ] + dir: deployment/clouddeploy/vanir-sandbox + id: 'deploy-vanir-sandbox' + waitFor: ['goose-up'] + timeout: 7200s # Also set in Cloud Build: serviceAccount: 'projects/oss-vdb/serviceAccounts/deployment@oss-vdb.iam.gserviceaccount.com' diff --git a/deployment/clouddeploy/vanir-sandbox/clouddeploy.yaml b/deployment/clouddeploy/vanir-sandbox/clouddeploy.yaml new file mode 100644 index 00000000000..5139eb21891 --- /dev/null +++ b/deployment/clouddeploy/vanir-sandbox/clouddeploy.yaml @@ -0,0 +1,39 @@ +apiVersion: deploy.cloud.google.com/v1 +kind: DeliveryPipeline +metadata: + name: vanir-sandbox +description: Vanir sandbox Cloud Run pipeline +serialPipeline: + stages: + - targetId: staging-vanir-sandbox + profiles: [ staging ] + - targetId: production-vanir-sandbox + profiles: [ prod ] +--- + +apiVersion: deploy.cloud.google.com/v1 +kind: Target +metadata: + name: staging-vanir-sandbox +description: oss-vdb-test vanir-sandbox instance +run: + location: projects/oss-vdb-test/locations/us-west2 +executionConfigs: +- usages: + - RENDER + - DEPLOY + serviceAccount: deployment@oss-vdb.iam.gserviceaccount.com +--- + +apiVersion: deploy.cloud.google.com/v1 +kind: Target +metadata: + name: production-vanir-sandbox +description: oss-vdb vanir-sandbox instance +run: + location: projects/oss-vdb/locations/us-west2 +executionConfigs: +- usages: + - RENDER + - DEPLOY + serviceAccount: deployment@oss-vdb.iam.gserviceaccount.com diff --git a/deployment/clouddeploy/vanir-sandbox/run-prod.yaml b/deployment/clouddeploy/vanir-sandbox/run-prod.yaml new file mode 100644 index 00000000000..19bb8fd2b52 --- /dev/null +++ b/deployment/clouddeploy/vanir-sandbox/run-prod.yaml @@ -0,0 +1,31 @@ +apiVersion: serving.knative.dev/v1 +kind: Service +metadata: + name: vanir-sandbox + annotations: + run.googleapis.com/ingress: all +spec: + template: + metadata: + annotations: + autoscaling.knative.dev/minScale: '0' + autoscaling.knative.dev/maxScale: '30' + run.googleapis.com/execution-environment: gen2 + spec: + serviceAccountName: vanir-sandbox@oss-vdb.iam.gserviceaccount.com + containerConcurrency: 1 + timeoutSeconds: 1800 + containers: + - image: vanir-sandbox + ports: + - containerPort: 8080 + startupProbe: + httpGet: + path: /healthz + livenessProbe: + httpGet: + path: /healthz + resources: + limits: + cpu: '4' + memory: 8Gi diff --git a/deployment/clouddeploy/vanir-sandbox/run-staging.yaml b/deployment/clouddeploy/vanir-sandbox/run-staging.yaml new file mode 100644 index 00000000000..837d30bc493 --- /dev/null +++ b/deployment/clouddeploy/vanir-sandbox/run-staging.yaml @@ -0,0 +1,31 @@ +apiVersion: serving.knative.dev/v1 +kind: Service +metadata: + name: vanir-sandbox + annotations: + run.googleapis.com/ingress: all +spec: + template: + metadata: + annotations: + autoscaling.knative.dev/minScale: '0' + autoscaling.knative.dev/maxScale: '30' + run.googleapis.com/execution-environment: gen2 + spec: + serviceAccountName: vanir-sandbox@oss-vdb-test.iam.gserviceaccount.com + containerConcurrency: 1 + timeoutSeconds: 1800 + containers: + - image: vanir-sandbox + ports: + - containerPort: 8080 + startupProbe: + httpGet: + path: /healthz + livenessProbe: + httpGet: + path: /healthz + resources: + limits: + cpu: '4' + memory: 8Gi diff --git a/deployment/clouddeploy/vanir-sandbox/skaffold.yaml b/deployment/clouddeploy/vanir-sandbox/skaffold.yaml new file mode 100644 index 00000000000..3b166782703 --- /dev/null +++ b/deployment/clouddeploy/vanir-sandbox/skaffold.yaml @@ -0,0 +1,18 @@ +apiVersion: skaffold/v3 +kind: Config +metadata: + name: vanir-sandbox + +profiles: +- name: staging + manifests: + rawYaml: + - run-staging.yaml + +- name: prod + manifests: + rawYaml: + - run-prod.yaml + +deploy: + cloudrun: {} diff --git a/deployment/deploy-prod.yaml b/deployment/deploy-prod.yaml index 0786f96a6af..2c84fe31f48 100644 --- a/deployment/deploy-prod.yaml +++ b/deployment/deploy-prod.yaml @@ -43,6 +43,8 @@ steps: args: ['deploy', 'releases', 'promote', '--quiet', '--release=osv-$SHORT_SHA', '--region=us-central1', '--delivery-pipeline=gke-indexer', '--to-target=production-indexer', '--annotations=tag=$TAG_NAME'] - name: gcr.io/cloud-builders/gcloud args: ['deploy', 'releases', 'promote', '--quiet', '--release=osv-$SHORT_SHA', '--region=us-central1', '--delivery-pipeline=osv-website', '--to-target=production-website', '--annotations=tag=$TAG_NAME'] +- name: gcr.io/cloud-builders/gcloud + args: ['deploy', 'releases', 'promote', '--quiet', '--release=osv-$SHORT_SHA', '--region=us-central1', '--delivery-pipeline=vanir-sandbox', '--to-target=production-vanir-sandbox', '--annotations=tag=$TAG_NAME'] # Deploy OSS-Fuzz workers - name: gcr.io/cloud-builders/gcloud @@ -88,6 +90,8 @@ steps: args: ['container', 'images', 'add-tag', '--quiet', 'gcr.io/oss-vdb/osv-website:$COMMIT_SHA', 'gcr.io/oss-vdb/osv-website:$TAG_NAME'] - name: gcr.io/cloud-builders/gcloud args: ['container', 'images', 'add-tag', '--quiet', 'gcr.io/oss-vdb/recoverer:$COMMIT_SHA', 'gcr.io/oss-vdb/recoverer:$TAG_NAME'] +- name: gcr.io/cloud-builders/gcloud + args: ['container', 'images', 'add-tag', '--quiet', 'gcr.io/oss-vdb/vanir-sandbox:$COMMIT_SHA', 'gcr.io/oss-vdb/vanir-sandbox:$TAG_NAME'] serviceAccount: 'projects/oss-vdb/serviceAccounts/deployment@oss-vdb.iam.gserviceaccount.com' options: diff --git a/deployment/terraform/environments/oss-vdb-test/main.tf b/deployment/terraform/environments/oss-vdb-test/main.tf index 852d1d9ad3d..4da0b67ea2e 100644 --- a/deployment/terraform/environments/oss-vdb-test/main.tf +++ b/deployment/terraform/environments/oss-vdb-test/main.tf @@ -150,6 +150,11 @@ output "postgres_read_pool_private_ip" { value = module.osv_api.read_pool_private_ip_address } +output "vanir_sandbox_uri" { + description = "HTTPS URI of the untrusted Vanir sandbox Cloud Run service" + value = module.osv_test.vanir_sandbox_uri +} + variable "deployment_service_account_email" { type = string description = "CI/CD deployment service account email." diff --git a/deployment/terraform/environments/oss-vdb/main.tf b/deployment/terraform/environments/oss-vdb/main.tf index cc70f4eb61c..0274bfc8d79 100644 --- a/deployment/terraform/environments/oss-vdb/main.tf +++ b/deployment/terraform/environments/oss-vdb/main.tf @@ -230,6 +230,11 @@ output "postgres_read_pool_private_ip" { value = module.osv_api.read_pool_private_ip_address } +output "vanir_sandbox_uri" { + description = "HTTPS URI of the untrusted Vanir sandbox Cloud Run service" + value = module.osv.vanir_sandbox_uri +} + terraform { backend "gcs" { bucket = "oss-vdb-tf" diff --git a/deployment/terraform/modules/osv/outputs.tf b/deployment/terraform/modules/osv/outputs.tf index 8e29f0afdf9..9d70cbc8a7b 100644 --- a/deployment/terraform/modules/osv/outputs.tf +++ b/deployment/terraform/modules/osv/outputs.tf @@ -12,3 +12,8 @@ output "public_import_logs_bucket_name" { value = google_storage_bucket.osv_public_import_logs.name description = "The name of the public import logs bucket." } + +output "vanir_sandbox_uri" { + value = google_cloud_run_v2_service.vanir_sandbox.uri + description = "The HTTPS URI of the vanir-sandbox Cloud Run service." +} diff --git a/deployment/terraform/modules/osv/vanir_sandbox.tf b/deployment/terraform/modules/osv/vanir_sandbox.tf new file mode 100644 index 00000000000..434b3953520 --- /dev/null +++ b/deployment/terraform/modules/osv/vanir_sandbox.tf @@ -0,0 +1,72 @@ +# Dedicated zero-privilege service account for the untrusted Vanir sandbox Cloud Run service. +# Intentionally granted ZERO IAM roles so querying the metadata server yields no GCP permissions. +resource "google_service_account" "vanir_sandbox" { + project = var.project_id + account_id = "vanir-sandbox" + display_name = "Vanir Sandbox Service Account (zero IAM roles)" +} + +# Allow CI/CD deployment and Terraform service accounts to attach vanir_sandbox to Cloud Run revisions. +# This grants permissions ON the service account to deployers, not TO the service account itself. +resource "google_service_account_iam_member" "vanir_sandbox_deployer_act_as" { + for_each = toset([ + for email in var.frontend_deployer_service_account_emails : "serviceAccount:${email}" + ]) + + service_account_id = google_service_account.vanir_sandbox.name + role = "roles/iam.serviceAccountUser" + member = each.value +} + +# Untrusted Cloud Run Gen2 microVM sandbox for running Vanir signature generation. +# Intentionally has NO vpc_access block (physically air-gapped from internal VPC / GKE / Redis / Cloud SQL). +resource "google_cloud_run_v2_service" "vanir_sandbox" { + project = var.project_id + name = "vanir-sandbox" + location = "us-west2" + ingress = "INGRESS_TRAFFIC_ALL" + + depends_on = [google_service_account_iam_member.vanir_sandbox_deployer_act_as] + + template { + service_account = google_service_account.vanir_sandbox.email + execution_environment = "EXECUTION_ENVIRONMENT_GEN2" + max_instance_request_concurrency = 1 + timeout = "1800s" + + scaling { + min_instance_count = 0 + max_instance_count = 30 + } + + containers { + image = "gcr.io/oss-vdb/vanir-sandbox:latest" # Placeholder image. + resources { + limits = { + cpu = "4" + memory = "8Gi" + } + } + } + } + + lifecycle { + ignore_changes = [ + # To be managed by Cloud Deploy. + template, + traffic, + labels, + client, + ] + } +} + +# Restrict invocation strictly to the GKE worker service account (never allUsers). +resource "google_cloud_run_v2_service_iam_member" "vanir_sandbox_invoker" { + count = var.worker_service_account_email != "" ? 1 : 0 + project = var.project_id + location = google_cloud_run_v2_service.vanir_sandbox.location + name = google_cloud_run_v2_service.vanir_sandbox.name + role = "roles/run.invoker" + member = "serviceAccount:${var.worker_service_account_email}" +} diff --git a/go/Dockerfile b/go/Dockerfile index 6bff44d9ce4..1cdbb842708 100644 --- a/go/Dockerfile +++ b/go/Dockerfile @@ -25,7 +25,7 @@ # # Select which service to build using the --target flag (e.g. importer, worker, exporter, exporter-deleter, # relations, recordchecker, generatesitemap, custommetrics, gitter, first_package_finder, -# api, recoverer, vanir-signatures, ubuntubinarymapper, staging-api-test, website, osv-linter). +# api, recoverer, vanir-signatures, vanir-sandbox, ubuntubinarymapper, staging-api-test, website, osv-linter). # ==================================================================================== # ======================================================== @@ -254,6 +254,25 @@ COPY cmd/vanir_signatures/generate_signatures.py /usr/local/bin/generate_signatu 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 && \ + rm -rf /var/lib/apt/lists/* && \ + find / -xdev -perm /6000 -exec chmod a-s {} + +COPY --from=vanir-python-deps /app/.venv /app/.venv +ENV PATH="/app/.venv/bin:$PATH" +COPY --from=vanir-sandbox-build /app/vanir_sandbox /usr/local/bin/vanir_sandbox +COPY cmd/vanir_signatures/generate_signatures.py /usr/local/bin/generate_signatures.py +RUN chmod 755 /usr/local/bin/vanir_sandbox /usr/local/bin/generate_signatures.py +ENTRYPOINT ["/usr/local/bin/vanir_sandbox"] + # ======================================================== # Target: Ubuntu Binary Mapper # ======================================================== diff --git a/go/cmd/vanir_sandbox/main.go b/go/cmd/vanir_sandbox/main.go new file mode 100644 index 00000000000..ba41c220564 --- /dev/null +++ b/go/cmd/vanir_sandbox/main.go @@ -0,0 +1,489 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Package main implements the untrusted Vanir sandbox HTTP server for Cloud Run Gen2. +// Each request processes a single vulnerability record under a unique non-root Linux UID, +// isolated work directory, stripped environment, IPC/UTS namespaces, and fail-closed +// post-request UID process reaping. Authentication is enforced by Cloud Run IAM +// (roles/run.invoker). +// +// TODO: Integrate with gitter's /commit-pack endpoint (--git-instead-ofs) so Git-only +// requests can run offline inside an empty CLONE_NEWNET network namespace. +package main + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "flag" + "fmt" + "io" + "log/slog" + "net" + "net/http" + "os" + "os/exec" + "os/signal" + "path/filepath" + "strconv" + "strings" + "sync" + "sync/atomic" + "syscall" + "time" + + "github.com/google/osv.dev/go/logger" +) + +const ( + maxRequestBytes = 4 << 20 // 4 MiB max HTTP request payload + maxOutputBytes = 4 << 20 // 4 MiB max output.json read from child + maxChildLogBytes = 64 << 10 // 64 KiB max child output logged on failure + defaultTimeout = 25 * time.Minute + shutdownTimeout = 8 * time.Second // Fits within Cloud Run's 10s SIGTERM grace period + uidBase = 10000 + uidSpan = 50000 + probeUID = 65534 // nobody +) + +// GenerateRequest is the JSON request body for POST /v1/generate. +type GenerateRequest struct { + Vulnerability json.RawMessage `json:"vulnerability"` // Single OSV JSON object +} + +// GenerateResponse is the JSON response body for POST /v1/generate. +type GenerateResponse struct { + Signatures json.RawMessage `json:"signatures"` // affected_idx_str -> signature objects +} + +type sandboxServer struct { + pythonBin string + scriptPath string + baseWorkDir string + timeout time.Duration + useSetuid bool + supportsIPCUTSNS bool + selfExe string + onShutdown func() + + execMu sync.Mutex + seq atomic.Int64 + shutdownOnce sync.Once +} + +func (s *sandboxServer) routes() http.Handler { + mux := http.NewServeMux() + mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte("ok\n")) + }) + mux.HandleFunc("POST /v1/generate", s.handleGenerate) + + return mux +} + +func (s *sandboxServer) handleGenerate(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + + // Reject concurrent requests immediately so an in-flight child cannot queue + // follow-up requests against loopback while running. + if !s.execMu.TryLock() { + http.Error(w, "sandbox busy", http.StatusServiceUnavailable) + return + } + defer s.execMu.Unlock() + + r.Body = http.MaxBytesReader(w, r.Body, maxRequestBytes) + defer r.Body.Close() + + var req GenerateRequest + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + if _, ok := errors.AsType[*http.MaxBytesError](err); ok { + http.Error(w, "request body too large", http.StatusRequestEntityTooLarge) + return + } + http.Error(w, fmt.Sprintf("invalid JSON request: %v", err), http.StatusBadRequest) + + return + } + + var meta struct { + ID string `json:"id"` + } + if err := json.Unmarshal(req.Vulnerability, &meta); err != nil || meta.ID == "" { + http.Error(w, "invalid vulnerability object: missing id", http.StatusBadRequest) + return + } + + n := s.seq.Add(1) + //nolint:gosec // G115: uidBase + (n % uidSpan) is always in [10000, 59999]. + uid := uint32(uidBase + (n % uidSpan)) + + sigs, statusCode, err := s.executeRequest(ctx, n, uid, meta.ID, &req) + if err != nil { + logger.ErrorContext(ctx, "Sandbox execution failed", + slog.String("vuln_id", meta.ID), + slog.Int64("seq", n), + slog.Int("status", statusCode), + slog.Any("error", err)) + http.Error(w, err.Error(), statusCode) + + return + } + + respBytes, err := json.Marshal(GenerateResponse{Signatures: sigs}) + if err != nil { + http.Error(w, fmt.Sprintf("failed to marshal response: %v", err), http.StatusInternalServerError) + return + } + + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + _, _ = w.Write(respBytes) +} + +func (s *sandboxServer) executeRequest(ctx context.Context, seq int64, uid uint32, vulnID string, req *GenerateRequest) (json.RawMessage, int, error) { + jobDir := filepath.Join(s.baseWorkDir, fmt.Sprintf("vanir-job-%d", seq)) + ipcDir := filepath.Join(jobDir, "ipc") + workDir := filepath.Join(jobDir, "work") + gitWorkDir := filepath.Join(workDir, "git-work") + + var childPGID int + var reaped bool + var reapErr error + reapAll := func() error { + if reaped { + return reapErr + } + reaped = true + if childPGID > 0 { + _ = syscall.Kill(-childPGID, syscall.SIGKILL) + } + if s.useSetuid { + reapErr = s.reapUID(context.WithoutCancel(ctx), uid) + } + + return reapErr + } + + defer func() { + _ = reapAll() + _ = os.RemoveAll(jobDir) + }() + + for _, d := range []struct { + path string + mode os.FileMode + }{ + {jobDir, 0711}, + {ipcDir, 0755}, + {workDir, 0700}, + {gitWorkDir, 0700}, + } { + if err := os.Mkdir(d.path, d.mode); err != nil { + return nil, http.StatusInternalServerError, fmt.Errorf("failed to create %s: %w", filepath.Base(d.path), err) + } + if err := os.Chmod(d.path, d.mode); err != nil { + return nil, http.StatusInternalServerError, fmt.Errorf("failed to chmod %s: %w", filepath.Base(d.path), err) + } + } + + inputPath := filepath.Join(ipcDir, "input.json") + outputPath := filepath.Join(ipcDir, "output.json") + + batchPayload, err := json.Marshal([]json.RawMessage{req.Vulnerability}) + if err != nil { + return nil, http.StatusInternalServerError, fmt.Errorf("failed to marshal input batch: %w", err) + } + if err := os.WriteFile(inputPath, batchPayload, 0600); err != nil { + return nil, http.StatusInternalServerError, fmt.Errorf("failed to write input.json: %w", err) + } + if err := os.WriteFile(outputPath, nil, 0600); err != nil { + return nil, http.StatusInternalServerError, fmt.Errorf("failed to pre-create output.json: %w", err) + } + + if s.useSetuid { + if err := os.Chown(inputPath, 0, int(uid)); err != nil { + return nil, http.StatusInternalServerError, fmt.Errorf("failed to chown input.json: %w", err) + } + if err := os.Chmod(inputPath, 0640); err != nil { + return nil, http.StatusInternalServerError, fmt.Errorf("failed to chmod input.json: %w", err) + } + for _, p := range []string{workDir, gitWorkDir, outputPath} { + if err := os.Chown(p, int(uid), int(uid)); err != nil { + return nil, http.StatusInternalServerError, fmt.Errorf("failed to chown %s: %w", p, err) + } + } + } + + timeout := s.timeout + if timeout <= 0 { + timeout = defaultTimeout + } + cmdCtx, cancel := context.WithTimeout(ctx, timeout) + defer cancel() + + //nolint:gosec // G204: pythonBin and scriptPath are trusted supervisor config paths. + cmd := exec.CommandContext( + cmdCtx, + s.pythonBin, + s.scriptPath, + "--input", inputPath, + "--output", outputPath, + "--git-working-dir", gitWorkDir, + ) + cmd.Env = []string{ + "PATH=/app/.venv/bin:/usr/local/bin:/usr/bin:/bin", + "HOME=" + workDir, + "TMPDIR=" + workDir, + "PYTHONDONTWRITEBYTECODE=1", + "GIT_TERMINAL_PROMPT=0", + "GIT_CONFIG_NOSYSTEM=1", + "GIT_CONFIG_GLOBAL=/dev/null", + "GIT_ALLOW_PROTOCOL=https:http", + } + + sysProcAttr := &syscall.SysProcAttr{Setpgid: true} + if s.useSetuid { + sysProcAttr.Credential = &syscall.Credential{Uid: uid, Gid: uid, Groups: []uint32{}} + } + if s.supportsIPCUTSNS { + sysProcAttr.Cloneflags |= syscall.CLONE_NEWIPC | syscall.CLONE_NEWUTS + } + cmd.SysProcAttr = sysProcAttr + cmd.Cancel = func() error { + if cmd.Process == nil { + return nil + } + + return syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL) + } + cmd.WaitDelay = 5 * time.Second + + var outBuf bytes.Buffer + cmd.Stdout = &outBuf + cmd.Stderr = &outBuf + + if err := cmd.Start(); err != nil { + return nil, http.StatusInternalServerError, fmt.Errorf("failed to start sandbox child: %w", err) + } + childPGID = cmd.Process.Pid + + waitErr := cmd.Wait() + if err := reapAll(); err != nil { + logger.ErrorContext(ctx, "UID process reaping failed; triggering shutdown", + slog.String("vuln_id", vulnID), + slog.Uint64("uid", uint64(uid)), + slog.Any("error", err)) + if s.onShutdown != nil { + s.shutdownOnce.Do(func() { go s.onShutdown() }) + } + + return nil, http.StatusInternalServerError, fmt.Errorf("sandbox process reaping failed: %w", err) + } + + if waitErr != nil { + outStr := outBuf.String() + if len(outStr) > maxChildLogBytes { + outStr = strings.ToValidUTF8(outStr[:maxChildLogBytes], "") + "... [truncated]" + } + logger.WarnContext(ctx, "Vanir sandbox child failed", + slog.String("vuln_id", vulnID), + slog.Any("error", waitErr), + slog.String("output", outStr)) + + return nil, http.StatusInternalServerError, fmt.Errorf("vanir sandbox execution failed: %w", waitErr) + } + + outFile, err := os.Open(outputPath) + if err != nil { + return nil, http.StatusInternalServerError, fmt.Errorf("failed to open output.json: %w", err) + } + defer outFile.Close() + outputBytes, err := io.ReadAll(io.LimitReader(outFile, maxOutputBytes+1)) + if err != nil { + return nil, http.StatusInternalServerError, fmt.Errorf("failed to read output.json: %w", err) + } + if len(outputBytes) > maxOutputBytes { + return nil, http.StatusInternalServerError, fmt.Errorf("output.json exceeds max size (%d bytes)", maxOutputBytes) + } + + var rawOutput map[string]json.RawMessage + if err := json.Unmarshal(outputBytes, &rawOutput); err != nil { + return nil, http.StatusInternalServerError, fmt.Errorf("failed to unmarshal output.json: %w", err) + } + + sigs := bytes.TrimSpace(rawOutput[vulnID]) + if len(sigs) == 0 || bytes.Equal(sigs, []byte("null")) { + sigs = json.RawMessage("{}") + } + + return sigs, http.StatusOK, nil +} + +// reapUID spawns a short-lived helper running as the given non-root UID that calls +// kill(-1, SIGKILL), atomically killing any surviving processes owned by that UID. +func (s *sandboxServer) reapUID(parentCtx context.Context, uid uint32) error { + if uid == 0 || s.selfExe == "" { + return errors.New("reapUID requires non-zero uid and selfExe") + } + ctx, cancel := context.WithTimeout(parentCtx, 5*time.Second) + defer cancel() + + //nolint:gosec // G204: selfExe is our own binary path resolved at startup. + cmd := exec.CommandContext(ctx, s.selfExe, "-reap-uid") + cmd.Env = []string{} + cmd.SysProcAttr = &syscall.SysProcAttr{ + Credential: &syscall.Credential{Uid: uid, Gid: uid, Groups: []uint32{}}, + } + if err := cmd.Run(); err != nil { + return fmt.Errorf("reap-uid helper failed for uid %d: %w", uid, err) + } + + return nil +} + +func probeCapability(selfExe string, cloneFlags uintptr) error { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + cmd := exec.CommandContext(ctx, selfExe, "-probe-noop") + cmd.Env = []string{} + cmd.SysProcAttr = &syscall.SysProcAttr{ + Credential: &syscall.Credential{Uid: probeUID, Gid: probeUID, Groups: []uint32{}}, + Cloneflags: cloneFlags, + } + + return cmd.Run() +} + +func main() { + defaultPort := 8080 + if p, err := strconv.Atoi(os.Getenv("PORT")); err == nil && p > 0 { + defaultPort = p + } + + port := flag.Int("port", defaultPort, "HTTP listen port.") + pythonBin := flag.String("python-bin", "python3", "Python interpreter binary.") + scriptPath := flag.String("script-path", "/usr/local/bin/generate_signatures.py", "Path to generate_signatures.py.") + timeout := flag.Duration("timeout", defaultTimeout, "Per-request child execution timeout.") + noSetuid := flag.Bool("no-setuid", false, "Allow running without UID switching (only permitted when non-root for local tests).") + reapUIDFlag := flag.Bool("reap-uid", false, "Internal helper: kill all processes owned by current non-root UID and exit.") + probeNoop := flag.Bool("probe-noop", false, "Internal helper: exit 0 immediately for startup capability probing.") + flag.Parse() + + if *probeNoop { + return + } + if *reapUIDFlag { + // Safety guard: NEVER call kill(-1, SIGKILL) as root (UID 0). + if os.Getuid() == 0 || os.Geteuid() == 0 { + os.Exit(2) + } + _ = syscall.Kill(-1, syscall.SIGKILL) + + return + } + + logger.InitGlobalLogger() + defer logger.Close() + + ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) + defer stop() + + selfExe, err := os.Executable() + if err != nil { + logger.FatalContext(ctx, "Failed to resolve executable path", slog.Any("error", err)) + } + + isRoot := os.Geteuid() == 0 + if isRoot && *noSetuid { + logger.FatalContext(ctx, "Refusing to run with -no-setuid as UID 0") + } + if !isRoot && !*noSetuid { + logger.FatalContext(ctx, "vanir_sandbox must run as UID 0 to isolate per-request UIDs (pass -no-setuid only for unprivileged local tests)") + } + + useSetuid := isRoot + supportsIPCUTSNS := false + if useSetuid { + syscall.Umask(0022) + if err := probeCapability(selfExe, 0); err != nil { + logger.FatalContext(ctx, "CAP_SETUID/CAP_SETGID probe failed (Cloud Run Gen2 is required for UID isolation)", slog.Any("error", err)) + } + if err := probeCapability(selfExe, syscall.CLONE_NEWIPC|syscall.CLONE_NEWUTS); err != nil { + logger.WarnContext(ctx, "CLONE_NEWIPC/CLONE_NEWUTS probe failed; continuing without IPC/UTS namespace isolation", slog.Any("error", err)) + } else { + supportsIPCUTSNS = true + } + } + + baseWorkDir, err := os.MkdirTemp("", "vanir-sandbox-root-*") + if err != nil { + logger.FatalContext(ctx, "Failed to create private sandbox base directory", slog.Any("error", err)) + } + baseMode := os.FileMode(0700) + if useSetuid { + baseMode = 0711 + } + if err := os.Chmod(baseWorkDir, baseMode); err != nil { + _ = os.RemoveAll(baseWorkDir) + logger.FatalContext(ctx, "Failed to chmod private sandbox base directory", slog.Any("error", err)) + } + defer os.RemoveAll(baseWorkDir) + + srvCtx, srvCancel := context.WithCancel(ctx) + defer srvCancel() + + sb := &sandboxServer{ + pythonBin: *pythonBin, + scriptPath: *scriptPath, + baseWorkDir: baseWorkDir, + timeout: *timeout, + useSetuid: useSetuid, + supportsIPCUTSNS: supportsIPCUTSNS, + selfExe: selfExe, + onShutdown: srvCancel, + } + + httpServer := &http.Server{ + Addr: fmt.Sprintf(":%d", *port), + Handler: sb.routes(), + ReadHeaderTimeout: 10 * time.Second, + IdleTimeout: 60 * time.Second, + BaseContext: func(net.Listener) context.Context { return ctx }, + } + + logger.InfoContext(ctx, "Starting vanir_sandbox server", + slog.Int("port", *port), + slog.Bool("use_setuid", useSetuid), + slog.Bool("supports_ipc_uts_ns", supportsIPCUTSNS)) + + go func() { + if err := httpServer.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { + logger.FatalContext(ctx, "vanir_sandbox server failed", slog.Any("error", err)) + } + }() + + <-srvCtx.Done() + stop() + logger.InfoContext(context.Background(), "Shutting down vanir_sandbox server") + + shutCtx, shutCancel := context.WithTimeout(context.Background(), shutdownTimeout) + defer shutCancel() + if err := httpServer.Shutdown(shutCtx); err != nil { + logger.ErrorContext(context.Background(), "Graceful shutdown failed", slog.Any("error", err)) + } +} diff --git a/go/cmd/vanir_sandbox/main_test.go b/go/cmd/vanir_sandbox/main_test.go new file mode 100644 index 00000000000..f54b93593d1 --- /dev/null +++ b/go/cmd/vanir_sandbox/main_test.go @@ -0,0 +1,141 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package main + +import ( + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strconv" + "strings" + "syscall" + "testing" + "time" +) + +func TestSandboxEndToEnd(t *testing.T) { + t.Setenv("SANDBOX_CANARY_SECRET", "must-not-leak") + + workRoot := t.TempDir() + pidFile := filepath.Join(t.TempDir(), "bg.pid") + + scriptPath := filepath.Join(t.TempDir(), "mock_vanir.py") + script := `#!/usr/bin/env python3 +import argparse, json, os, subprocess +p = argparse.ArgumentParser() +p.add_argument('--input', required=True) +p.add_argument('--output', required=True) +p.add_argument('--git-working-dir', required=True) +args = p.parse_args() + +assert 'SANDBOX_CANARY_SECRET' not in os.environ +assert os.environ.get('GIT_ALLOW_PROTOCOL') == 'https:http' + +v = json.load(open(args.input, encoding='utf-8'))[0] +bg = subprocess.Popen(['sleep', '60'], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) +open(` + strconv.Quote(pidFile) + `, 'w', encoding='utf-8').write(str(bg.pid)) + +json.dump({ + v['id']: {'0': [{'id': v['id'] + '-deadbeef', 'signature_type': 'Function', 'signature_version': 'v1'}]}, + 'CVE-SPOOFED': {'0': [{'id': 'CVE-SPOOFED-11111111'}]}, +}, open(args.output, 'w', encoding='utf-8')) +` + if err := os.WriteFile(scriptPath, []byte(script), 0600); err != nil { + t.Fatalf("write script: %v", err) + } + + sb := &sandboxServer{ + pythonBin: "python3", + scriptPath: scriptPath, + baseWorkDir: workRoot, + timeout: 30 * time.Second, + } + ts := httptest.NewServer(sb.routes()) + t.Cleanup(ts.Close) + + if resp, err := http.Get(ts.URL + "/healthz"); err != nil || resp.StatusCode != http.StatusOK { + t.Fatalf("GET /healthz failed: %v", err) + } else { + resp.Body.Close() + } + + reqBody, err := json.Marshal(GenerateRequest{ + Vulnerability: json.RawMessage(`{"id":"OSV-2026-999","affected":[{"ranges":[{"type":"GIT","repo":"https://github.com/example/repo","events":[{"fixed":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}]}]}]}`), + }) + if err != nil { + t.Fatalf("marshal: %v", err) + } + + resp, err := http.Post(ts.URL+"/v1/generate", "application/json", bytes.NewReader(reqBody)) + if err != nil { + t.Fatalf("POST /v1/generate: %v", err) + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + var b bytes.Buffer + _, _ = b.ReadFrom(resp.Body) + t.Fatalf("status=%d body=%s", resp.StatusCode, b.String()) + } + + var genResp GenerateResponse + if err := json.NewDecoder(resp.Body).Decode(&genResp); err != nil { + t.Fatalf("decode: %v", err) + } + if strings.Contains(string(genResp.Signatures), "CVE-SPOOFED") { + t.Fatalf("spoofed vuln leaked: %s", genResp.Signatures) + } + var sigsByIdx map[string][]map[string]any + if err := json.Unmarshal(genResp.Signatures, &sigsByIdx); err != nil || len(sigsByIdx["0"]) != 1 || sigsByIdx["0"][0]["id"] != "OSV-2026-999-deadbeef" { + t.Fatalf("unexpected signatures: %s", genResp.Signatures) + } + + // Verify background process was reaped and temp directories cleaned up. + pidBytes, _ := os.ReadFile(pidFile) + bgPID, _ := strconv.Atoi(strings.TrimSpace(string(pidBytes))) + isDead := func(pid int) bool { + if syscall.Kill(pid, 0) != nil { + return true + } + st, err := os.ReadFile(filepath.Join("/proc", strconv.Itoa(pid), "status")) + + return err != nil || strings.Contains(string(st), "\nState:\tZ") || strings.Contains(string(st), "\nState:\tX") + } + for deadline := time.Now().Add(2 * time.Second); time.Now().Before(deadline) && !isDead(bgPID); { + time.Sleep(20 * time.Millisecond) + } + if !isDead(bgPID) { + _ = syscall.Kill(bgPID, syscall.SIGKILL) + t.Errorf("background process %d survived", bgPID) + } + if entries, err := os.ReadDir(workRoot); err != nil || len(entries) != 0 { + t.Errorf("workRoot not empty: %v (%d entries)", err, len(entries)) + } +} + +func TestSandboxBusyReturns503(t *testing.T) { + sb := &sandboxServer{baseWorkDir: t.TempDir()} + sb.execMu.Lock() + defer sb.execMu.Unlock() + + rr := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, "/v1/generate", strings.NewReader(`{"vulnerability":{"id":"OSV-BUSY"}}`)) + sb.routes().ServeHTTP(rr, req) + if rr.Code != http.StatusServiceUnavailable { + t.Errorf("got %d, want 503", rr.Code) + } +} diff --git a/go/cmd/vanir_signatures/main.go b/go/cmd/vanir_signatures/main.go index 36b9f009a93..6929981dbd5 100644 --- a/go/cmd/vanir_signatures/main.go +++ b/go/cmd/vanir_signatures/main.go @@ -39,6 +39,7 @@ func main() { hours int pythonBin string scriptPath string + sandboxURL string ) flag.IntVar(&batchSize, "batch-size", 100, "Number of vulnerabilities to process in each batch.") @@ -47,6 +48,7 @@ func main() { 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.Parse() logger.InitGlobalLogger() @@ -83,7 +85,18 @@ func main() { GCS: gcsClient, }) jobStore := osvdatastore.NewJobDataStore(dsClient) - generator := vanir.NewPythonGenerator(pythonBin, scriptPath) + + 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) + } runner := &vanir.Runner{ VulnStore: vulnStore, diff --git a/go/internal/vanir/http_generator.go b/go/internal/vanir/http_generator.go new file mode 100644 index 00000000000..04d64a219b2 --- /dev/null +++ b/go/internal/vanir/http_generator.go @@ -0,0 +1,288 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package vanir + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "log/slog" + "net/http" + "net/url" + "regexp" + "strconv" + "strings" + "time" + + "github.com/google/osv.dev/go/logger" + "github.com/ossf/osv-schema/bindings/go/osvschema" + "google.golang.org/api/idtoken" + "google.golang.org/protobuf/encoding/protojson" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/types/known/structpb" +) + +const ( + maxSandboxResponseBytes = 4 << 20 // 4 MiB max HTTP response from vanir-sandbox + maxSandboxRequestBytes = 4 << 20 // Matches vanir-sandbox maxRequestBytes + maxSandboxErrBodyBytes = 1024 // Truncate error bodies before logging +) + +var commitHashRegex = regexp.MustCompile(`^[0-9a-f]{40}([0-9a-f]{24})?$`) + +func refuseRedirects(*http.Request, []*http.Request) error { + return http.ErrUseLastResponse +} + +var noRedirectHTTPClient = &http.Client{CheckRedirect: refuseRedirects} + +type sandboxGenerateRequest struct { + Vulnerability json.RawMessage `json:"vulnerability"` +} + +type sandboxGenerateResponse struct { + Signatures map[string][]json.RawMessage `json:"signatures"` +} + +func normalizeGitRepoURL(raw string) (string, bool) { + if raw == "" || strings.HasPrefix(raw, "-") || strings.ContainsFunc(raw, func(r rune) bool { return r <= 0x20 || r == 0x7f }) { + return "", false + } + u, err := url.Parse(raw) + if err != nil || u.Host == "" || u.Path == "" || u.Path == "/" { + return "", false + } + scheme := strings.ToLower(u.Scheme) + if scheme == "git" && strings.EqualFold(u.Hostname(), "github.com") { + scheme = "https" + } + if scheme != "https" && scheme != "http" { + return "", false + } + u.Scheme = scheme + u.Host = strings.ToLower(u.Host) + u.RawQuery = "" + u.Fragment = "" + + return u.String(), true +} + +// prepareVulnForSandbox clones v and strips non-URL Git repos and non-hash fixed events, +// returning whether any valid Git target or ecosystem_specific.fixes entry remains. +func prepareVulnForSandbox(v *osvschema.Vulnerability) (*osvschema.Vulnerability, bool) { + clone := proto.CloneOf(v) + hasWork := false + + for _, aff := range clone.GetAffected() { + if aff == nil { + continue + } + if len(aff.GetEcosystemSpecific().GetFields()["fixes"].GetListValue().GetValues()) > 0 { + hasWork = true + } + + keptRanges := make([]*osvschema.Range, 0, len(aff.GetRanges())) + for _, r := range aff.GetRanges() { + if r == nil { + continue + } + if r.GetType() != osvschema.Range_GIT { + keptRanges = append(keptRanges, r) + continue + } + repoURL, ok := normalizeGitRepoURL(r.GetRepo()) + if !ok { + continue + } + + validEvents := make([]*osvschema.Event, 0, len(r.GetEvents())) + for _, ev := range r.GetEvents() { + fixed := strings.ToLower(ev.GetFixed()) + if !commitHashRegex.MatchString(fixed) { + continue + } + validEvents = append(validEvents, &osvschema.Event{Fixed: fixed}) + } + if len(validEvents) == 0 { + continue + } + r.Repo = repoURL + r.Events = validEvents + keptRanges = append(keptRanges, r) + hasWork = true + } + aff.Ranges = keptRanges + } + + return clone, hasWork +} + +func parseSandboxSignatures(origVuln *osvschema.Vulnerability, rawAffected map[string][]json.RawMessage) (map[int][]*structpb.Value, error) { + affectedLen := len(origVuln.GetAffected()) + out := make(map[int][]*structpb.Value, len(rawAffected)) + for idxStr, sigList := range rawAffected { + idx, err := strconv.Atoi(idxStr) + if err != nil || idx < 0 || idx >= affectedLen { + return nil, fmt.Errorf("invalid affected index %q for %s (len=%d)", idxStr, origVuln.GetId(), affectedLen) + } + vals := make([]*structpb.Value, 0, len(sigList)) + for _, rawSig := range sigList { + var val structpb.Value + if err := protojson.Unmarshal(rawSig, &val); err != nil { + return nil, fmt.Errorf("failed to parse signature for %s: %w", origVuln.GetId(), err) + } + vals = append(vals, &val) + } + if len(vals) > 0 { + out[idx] = vals + } + } + + return out, nil +} + +// HTTPSignatureGenerator is the orchestrator-side SignatureGenerator used by +// vanir_signatures when VANIR_SANDBOX_URL is configured. For each vulnerability it +// strips invalid Git repo URLs, POSTs the record to the Cloud Run vanir-sandbox +// service over Google OIDC-authenticated HTTP (roles/run.invoker), and parses the +// returned signatures back into OSV structpb.Value entries. +// +// TODO: Integrate with gitter's /commit-pack endpoint to relay cached shallow commit +// packs instead of having vanir-sandbox fetch directly from upstream Git hosts. +type HTTPSignatureGenerator struct { + SandboxURL string + HTTPClient *http.Client + Timeout time.Duration +} + +var _ SignatureGenerator = (*HTTPSignatureGenerator)(nil) + +// NewHTTPSignatureGenerator creates an HTTPSignatureGenerator authenticated with Google OIDC +// identity tokens targeting sandboxURL (for Cloud Run IAM roles/run.invoker). +func NewHTTPSignatureGenerator(ctx context.Context, sandboxURL string) (*HTTPSignatureGenerator, error) { + sandboxURL = strings.TrimRight(strings.TrimSpace(sandboxURL), "/") + u, err := url.Parse(sandboxURL) + if sandboxURL == "" || err != nil || !strings.EqualFold(u.Scheme, "https") || u.Host == "" || u.User != nil { + return nil, fmt.Errorf("sandboxURL must be a valid https URL without userinfo: %q", sandboxURL) + } + + httpClient, err := idtoken.NewClient(ctx, sandboxURL) + if err != nil { + return nil, fmt.Errorf("failed to create OIDC HTTP client for %s: %w", sandboxURL, err) + } + httpClient.Timeout = defaultBatchTimeout + httpClient.CheckRedirect = refuseRedirects + + return &HTTPSignatureGenerator{ + SandboxURL: sandboxURL, + HTTPClient: httpClient, + Timeout: defaultBatchTimeout, + }, nil +} + +func (g *HTTPSignatureGenerator) GenerateBatch(ctx context.Context, vulns []*osvschema.Vulnerability, _ string) (SignatureMap, error) { + result := make(SignatureMap, len(vulns)) + for _, v := range vulns { + if v == nil { + continue + } + sigs, err := g.generateSingle(ctx, v) + if err != nil { + return nil, err + } + if len(sigs) > 0 { + result[v.GetId()] = sigs + } + } + + return result, nil +} + +func (g *HTTPSignatureGenerator) generateSingle(ctx context.Context, origVuln *osvschema.Vulnerability) (map[int][]*structpb.Value, error) { + sanitized, hasWork := prepareVulnForSandbox(origVuln) + if !hasWork { + return map[int][]*structpb.Value{}, nil + } + + vulnBytes, err := protojson.MarshalOptions{UseProtoNames: true}.Marshal(sanitized) + if err != nil { + return nil, fmt.Errorf("failed to marshal sanitized vulnerability %s: %w", origVuln.GetId(), err) + } + reqPayload, err := json.Marshal(sandboxGenerateRequest{ + Vulnerability: json.RawMessage(vulnBytes), + }) + if err != nil { + return nil, fmt.Errorf("failed to marshal sandbox request for %s: %w", origVuln.GetId(), err) + } + if len(reqPayload) > maxSandboxRequestBytes { + logger.WarnContext(ctx, "Skipping vulnerability exceeding sandbox request size", slog.String("id", origVuln.GetId()), slog.Int("bytes", len(reqPayload))) + return map[int][]*structpb.Value{}, nil + } + + timeout := g.Timeout + if timeout <= 0 { + timeout = defaultBatchTimeout + } + reqCtx, cancel := context.WithTimeout(ctx, timeout) + defer cancel() + + httpReq, err := http.NewRequestWithContext(reqCtx, http.MethodPost, strings.TrimRight(g.SandboxURL, "/")+"/v1/generate", bytes.NewReader(reqPayload)) + if err != nil { + return nil, fmt.Errorf("failed to create sandbox request for %s: %w", origVuln.GetId(), err) + } + httpReq.GetBody = nil + httpReq.Header.Set("Content-Type", "application/json") + + httpClient := g.HTTPClient + if httpClient == nil { + httpClient = noRedirectHTTPClient + } + resp, err := httpClient.Do(httpReq) + if err != nil { + return nil, fmt.Errorf("sandbox HTTP request failed for %s: %w", origVuln.GetId(), err) + } + defer resp.Body.Close() + + respBytes, err := io.ReadAll(io.LimitReader(resp.Body, maxSandboxResponseBytes+1)) + if err != nil { + return nil, fmt.Errorf("failed to read sandbox response for %s: %w", origVuln.GetId(), err) + } + if len(respBytes) > maxSandboxResponseBytes { + return nil, fmt.Errorf("sandbox response for %s exceeds maximum size (%d bytes)", origVuln.GetId(), maxSandboxResponseBytes) + } + if resp.StatusCode != http.StatusOK { + errBody := strings.TrimSpace(string(respBytes)) + if len(errBody) > maxSandboxErrBodyBytes { + errBody = strings.ToValidUTF8(errBody[:maxSandboxErrBodyBytes], "") + "... [truncated]" + } + + return nil, fmt.Errorf("sandbox returned status %d for %s: %s", resp.StatusCode, origVuln.GetId(), errBody) + } + + var genResp sandboxGenerateResponse + if err := json.Unmarshal(respBytes, &genResp); err != nil { + return nil, fmt.Errorf("failed to unmarshal sandbox response for %s: %w", origVuln.GetId(), err) + } + + parsed, err := parseSandboxSignatures(origVuln, genResp.Signatures) + if err != nil { + logger.ErrorContext(ctx, "Skipping vulnerability due to invalid sandbox signatures", slog.String("id", origVuln.GetId()), slog.Any("error", err)) + return map[int][]*structpb.Value{}, nil + } + + return parsed, nil +} diff --git a/go/internal/vanir/http_generator_test.go b/go/internal/vanir/http_generator_test.go new file mode 100644 index 00000000000..861fbd89c02 --- /dev/null +++ b/go/internal/vanir/http_generator_test.go @@ -0,0 +1,157 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package vanir + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + + "github.com/ossf/osv-schema/bindings/go/osvschema" + "google.golang.org/protobuf/types/known/structpb" +) + +const ( + validCommit1 = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + validCommit2 = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" +) + +func gitVuln(id, repo string) *osvschema.Vulnerability { + return &osvschema.Vulnerability{ + Id: id, + Affected: []*osvschema.Affected{{ + Ranges: []*osvschema.Range{{ + Type: osvschema.Range_GIT, + Repo: repo, + Events: []*osvschema.Event{{Fixed: validCommit1}}, + }}, + }}, + } +} + +func TestPrepareVulnForSandbox(t *testing.T) { + badRepos := []string{"--upload-pack=sh -c id", "ssh://git@github.com/a/b", "file:///etc/passwd", "not-a-url"} + ranges := make([]*osvschema.Range, 0, len(badRepos)+2) + for _, repo := range badRepos { + ranges = append(ranges, &osvschema.Range{ + Type: osvschema.Range_GIT, + Repo: repo, + Events: []*osvschema.Event{{Fixed: validCommit1}}, + }) + } + ranges = append(ranges, + &osvschema.Range{ + Type: osvschema.Range_GIT, + Repo: "https://github.com/example/good?q=1#frag", + Events: []*osvschema.Event{{Introduced: "0"}, {Fixed: "--upload-pack=x"}, {Fixed: strings.ToUpper(validCommit2)}}, + }, + &osvschema.Range{ + Type: osvschema.Range_GIT, + Repo: "git://github.com/example/git-scheme", + Events: []*osvschema.Event{{Fixed: validCommit1}}, + }, + ) + + sanitized, hasWork := prepareVulnForSandbox(&osvschema.Vulnerability{ + Id: "OSV-2026-100", + Affected: []*osvschema.Affected{{Ranges: ranges}}, + }) + gotRanges := sanitized.GetAffected()[0].GetRanges() + if !hasWork || len(gotRanges) != 2 || + gotRanges[0].GetRepo() != "https://github.com/example/good" || + gotRanges[0].GetEvents()[0].GetFixed() != validCommit2 || + gotRanges[1].GetRepo() != "https://github.com/example/git-scheme" { + t.Errorf("unexpected sanitized ranges: hasWork=%v ranges=%v", hasWork, gotRanges) + } + + ecoSpec, _ := structpb.NewStruct(map[string]any{"fixes": []any{"https://android.googlesource.com/platform/art/+/deadbeef"}}) + if _, ok := prepareVulnForSandbox(&osvschema.Vulnerability{ + Id: "ASB-A-1", + Affected: []*osvschema.Affected{{EcosystemSpecific: ecoSpec}}, + }); !ok { + t.Error("expected hasWork=true when ecosystem_specific.fixes is set") + } +} + +func TestHTTPSignatureGenerator(t *testing.T) { + var sandboxCalls atomic.Int32 + sandbox := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + sandboxCalls.Add(1) + var req sandboxGenerateRequest + _ = json.NewDecoder(r.Body).Decode(&req) + var v struct { + ID string `json:"id"` + } + _ = json.Unmarshal(req.Vulnerability, &v) + w.Header().Set("Content-Type", "application/json") + if v.ID == "OSV-BAD-IDX" { + _, _ = w.Write([]byte(`{"signatures":{"99":[{"id":"OSV-BAD-IDX-1"}]}}`)) + return + } + _, _ = fmt.Fprintf(w, `{"signatures":{"0":[{"id":"%s-11223344","signature_type":"Function","signature_version":"v1"}]}}`, v.ID) + })) + t.Cleanup(sandbox.Close) + + gen := &HTTPSignatureGenerator{SandboxURL: sandbox.URL, HTTPClient: sandbox.Client()} + vulns := []*osvschema.Vulnerability{ + gitVuln("GHSA-aaaa-bbbb-cccc", "https://github.com/example/repo"), + gitVuln("OSV-BAD-IDX", "https://github.com/example/repo"), + gitVuln("OSV-NO-WORK", "not-a-url"), + } + + got, err := gen.GenerateBatch(context.Background(), vulns, "") + if err != nil { + t.Fatalf("GenerateBatch: %v", err) + } + if len(got["GHSA-aaaa-bbbb-cccc"][0]) != 1 || len(got["OSV-BAD-IDX"]) != 0 || sandboxCalls.Load() != 2 { + t.Errorf("got=%+v sandboxCalls=%d", got, sandboxCalls.Load()) + } +} + +func TestHTTPSignatureGenerator_Errors(t *testing.T) { + if _, err := NewHTTPSignatureGenerator(context.Background(), "http://insecure.example.com"); err == nil { + t.Error("expected error for non-https sandboxURL") + } + + var redirectHit atomic.Bool + target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + redirectHit.Store(true) + w.WriteHeader(http.StatusOK) + })) + t.Cleanup(target.Close) + redir := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, target.URL, http.StatusTemporaryRedirect) + })) + t.Cleanup(redir.Close) + + v := gitVuln("OSV-2026-1", "https://github.com/example/repo") + if _, err := (&HTTPSignatureGenerator{SandboxURL: redir.URL}).GenerateBatch(context.Background(), []*osvschema.Vulnerability{v}, ""); err == nil || redirectHit.Load() { + t.Fatalf("redirect should be refused (err=%v hit=%v)", err, redirectHit.Load()) + } + + errSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusInternalServerError) + _, _ = w.Write([]byte(strings.Repeat("X", 4096))) + })) + t.Cleanup(errSrv.Close) + if _, err := (&HTTPSignatureGenerator{SandboxURL: errSrv.URL}).GenerateBatch(context.Background(), []*osvschema.Vulnerability{v}, ""); err == nil || !strings.Contains(err.Error(), "... [truncated]") { + t.Errorf("expected truncated 500 error, got %v", err) + } +} From 07b81311ec9090d3622dd144be90af87352ca646 Mon Sep 17 00:00:00 2001 From: Rex P Date: Wed, 25 Nov 2026 11:17:19 +1100 Subject: [PATCH 2/7] refactor(vanir): simplify http_generator to a thin OIDC HTTP client --- go/internal/vanir/http_generator.go | 171 +++++------------------ go/internal/vanir/http_generator_test.go | 75 ++-------- 2 files changed, 46 insertions(+), 200 deletions(-) diff --git a/go/internal/vanir/http_generator.go b/go/internal/vanir/http_generator.go index 04d64a219b2..db0d9377537 100644 --- a/go/internal/vanir/http_generator.go +++ b/go/internal/vanir/http_generator.go @@ -23,7 +23,6 @@ import ( "log/slog" "net/http" "net/url" - "regexp" "strconv" "strings" "time" @@ -32,18 +31,14 @@ import ( "github.com/ossf/osv-schema/bindings/go/osvschema" "google.golang.org/api/idtoken" "google.golang.org/protobuf/encoding/protojson" - "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/known/structpb" ) const ( maxSandboxResponseBytes = 4 << 20 // 4 MiB max HTTP response from vanir-sandbox - maxSandboxRequestBytes = 4 << 20 // Matches vanir-sandbox maxRequestBytes maxSandboxErrBodyBytes = 1024 // Truncate error bodies before logging ) -var commitHashRegex = regexp.MustCompile(`^[0-9a-f]{40}([0-9a-f]{24})?$`) - func refuseRedirects(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } @@ -58,108 +53,8 @@ type sandboxGenerateResponse struct { Signatures map[string][]json.RawMessage `json:"signatures"` } -func normalizeGitRepoURL(raw string) (string, bool) { - if raw == "" || strings.HasPrefix(raw, "-") || strings.ContainsFunc(raw, func(r rune) bool { return r <= 0x20 || r == 0x7f }) { - return "", false - } - u, err := url.Parse(raw) - if err != nil || u.Host == "" || u.Path == "" || u.Path == "/" { - return "", false - } - scheme := strings.ToLower(u.Scheme) - if scheme == "git" && strings.EqualFold(u.Hostname(), "github.com") { - scheme = "https" - } - if scheme != "https" && scheme != "http" { - return "", false - } - u.Scheme = scheme - u.Host = strings.ToLower(u.Host) - u.RawQuery = "" - u.Fragment = "" - - return u.String(), true -} - -// prepareVulnForSandbox clones v and strips non-URL Git repos and non-hash fixed events, -// returning whether any valid Git target or ecosystem_specific.fixes entry remains. -func prepareVulnForSandbox(v *osvschema.Vulnerability) (*osvschema.Vulnerability, bool) { - clone := proto.CloneOf(v) - hasWork := false - - for _, aff := range clone.GetAffected() { - if aff == nil { - continue - } - if len(aff.GetEcosystemSpecific().GetFields()["fixes"].GetListValue().GetValues()) > 0 { - hasWork = true - } - - keptRanges := make([]*osvschema.Range, 0, len(aff.GetRanges())) - for _, r := range aff.GetRanges() { - if r == nil { - continue - } - if r.GetType() != osvschema.Range_GIT { - keptRanges = append(keptRanges, r) - continue - } - repoURL, ok := normalizeGitRepoURL(r.GetRepo()) - if !ok { - continue - } - - validEvents := make([]*osvschema.Event, 0, len(r.GetEvents())) - for _, ev := range r.GetEvents() { - fixed := strings.ToLower(ev.GetFixed()) - if !commitHashRegex.MatchString(fixed) { - continue - } - validEvents = append(validEvents, &osvschema.Event{Fixed: fixed}) - } - if len(validEvents) == 0 { - continue - } - r.Repo = repoURL - r.Events = validEvents - keptRanges = append(keptRanges, r) - hasWork = true - } - aff.Ranges = keptRanges - } - - return clone, hasWork -} - -func parseSandboxSignatures(origVuln *osvschema.Vulnerability, rawAffected map[string][]json.RawMessage) (map[int][]*structpb.Value, error) { - affectedLen := len(origVuln.GetAffected()) - out := make(map[int][]*structpb.Value, len(rawAffected)) - for idxStr, sigList := range rawAffected { - idx, err := strconv.Atoi(idxStr) - if err != nil || idx < 0 || idx >= affectedLen { - return nil, fmt.Errorf("invalid affected index %q for %s (len=%d)", idxStr, origVuln.GetId(), affectedLen) - } - vals := make([]*structpb.Value, 0, len(sigList)) - for _, rawSig := range sigList { - var val structpb.Value - if err := protojson.Unmarshal(rawSig, &val); err != nil { - return nil, fmt.Errorf("failed to parse signature for %s: %w", origVuln.GetId(), err) - } - vals = append(vals, &val) - } - if len(vals) > 0 { - out[idx] = vals - } - } - - return out, nil -} - -// HTTPSignatureGenerator is the orchestrator-side SignatureGenerator used by -// vanir_signatures when VANIR_SANDBOX_URL is configured. For each vulnerability it -// strips invalid Git repo URLs, POSTs the record to the Cloud Run vanir-sandbox -// service over Google OIDC-authenticated HTTP (roles/run.invoker), and parses the -// returned signatures back into OSV structpb.Value entries. +// HTTPSignatureGenerator invokes the remote Cloud Run vanir-sandbox service over +// Google OIDC-authenticated HTTPS (roles/run.invoker). // // TODO: Integrate with gitter's /commit-pack endpoint to relay cached shallow commit // packs instead of having vanir-sandbox fetch directly from upstream Git hosts. @@ -172,7 +67,7 @@ type HTTPSignatureGenerator struct { var _ SignatureGenerator = (*HTTPSignatureGenerator)(nil) // NewHTTPSignatureGenerator creates an HTTPSignatureGenerator authenticated with Google OIDC -// identity tokens targeting sandboxURL (for Cloud Run IAM roles/run.invoker). +// identity tokens targeting sandboxURL. func NewHTTPSignatureGenerator(ctx context.Context, sandboxURL string) (*HTTPSignatureGenerator, error) { sandboxURL = strings.TrimRight(strings.TrimSpace(sandboxURL), "/") u, err := url.Parse(sandboxURL) @@ -212,25 +107,14 @@ func (g *HTTPSignatureGenerator) GenerateBatch(ctx context.Context, vulns []*osv return result, nil } -func (g *HTTPSignatureGenerator) generateSingle(ctx context.Context, origVuln *osvschema.Vulnerability) (map[int][]*structpb.Value, error) { - sanitized, hasWork := prepareVulnForSandbox(origVuln) - if !hasWork { - return map[int][]*structpb.Value{}, nil - } - - vulnBytes, err := protojson.MarshalOptions{UseProtoNames: true}.Marshal(sanitized) +func (g *HTTPSignatureGenerator) generateSingle(ctx context.Context, vuln *osvschema.Vulnerability) (map[int][]*structpb.Value, error) { + vulnBytes, err := protojson.MarshalOptions{UseProtoNames: true}.Marshal(vuln) if err != nil { - return nil, fmt.Errorf("failed to marshal sanitized vulnerability %s: %w", origVuln.GetId(), err) + return nil, fmt.Errorf("failed to marshal vulnerability %s: %w", vuln.GetId(), err) } - reqPayload, err := json.Marshal(sandboxGenerateRequest{ - Vulnerability: json.RawMessage(vulnBytes), - }) + reqPayload, err := json.Marshal(sandboxGenerateRequest{Vulnerability: json.RawMessage(vulnBytes)}) if err != nil { - return nil, fmt.Errorf("failed to marshal sandbox request for %s: %w", origVuln.GetId(), err) - } - if len(reqPayload) > maxSandboxRequestBytes { - logger.WarnContext(ctx, "Skipping vulnerability exceeding sandbox request size", slog.String("id", origVuln.GetId()), slog.Int("bytes", len(reqPayload))) - return map[int][]*structpb.Value{}, nil + return nil, fmt.Errorf("failed to marshal sandbox request for %s: %w", vuln.GetId(), err) } timeout := g.Timeout @@ -242,7 +126,7 @@ func (g *HTTPSignatureGenerator) generateSingle(ctx context.Context, origVuln *o httpReq, err := http.NewRequestWithContext(reqCtx, http.MethodPost, strings.TrimRight(g.SandboxURL, "/")+"/v1/generate", bytes.NewReader(reqPayload)) if err != nil { - return nil, fmt.Errorf("failed to create sandbox request for %s: %w", origVuln.GetId(), err) + return nil, fmt.Errorf("failed to create sandbox request for %s: %w", vuln.GetId(), err) } httpReq.GetBody = nil httpReq.Header.Set("Content-Type", "application/json") @@ -253,16 +137,16 @@ func (g *HTTPSignatureGenerator) generateSingle(ctx context.Context, origVuln *o } resp, err := httpClient.Do(httpReq) if err != nil { - return nil, fmt.Errorf("sandbox HTTP request failed for %s: %w", origVuln.GetId(), err) + return nil, fmt.Errorf("sandbox HTTP request failed for %s: %w", vuln.GetId(), err) } defer resp.Body.Close() respBytes, err := io.ReadAll(io.LimitReader(resp.Body, maxSandboxResponseBytes+1)) if err != nil { - return nil, fmt.Errorf("failed to read sandbox response for %s: %w", origVuln.GetId(), err) + return nil, fmt.Errorf("failed to read sandbox response for %s: %w", vuln.GetId(), err) } if len(respBytes) > maxSandboxResponseBytes { - return nil, fmt.Errorf("sandbox response for %s exceeds maximum size (%d bytes)", origVuln.GetId(), maxSandboxResponseBytes) + return nil, fmt.Errorf("sandbox response for %s exceeds maximum size (%d bytes)", vuln.GetId(), maxSandboxResponseBytes) } if resp.StatusCode != http.StatusOK { errBody := strings.TrimSpace(string(respBytes)) @@ -270,19 +154,36 @@ func (g *HTTPSignatureGenerator) generateSingle(ctx context.Context, origVuln *o errBody = strings.ToValidUTF8(errBody[:maxSandboxErrBodyBytes], "") + "... [truncated]" } - return nil, fmt.Errorf("sandbox returned status %d for %s: %s", resp.StatusCode, origVuln.GetId(), errBody) + return nil, fmt.Errorf("sandbox returned status %d for %s: %s", resp.StatusCode, vuln.GetId(), errBody) } var genResp sandboxGenerateResponse if err := json.Unmarshal(respBytes, &genResp); err != nil { - return nil, fmt.Errorf("failed to unmarshal sandbox response for %s: %w", origVuln.GetId(), err) + return nil, fmt.Errorf("failed to unmarshal sandbox response for %s: %w", vuln.GetId(), err) } - parsed, err := parseSandboxSignatures(origVuln, genResp.Signatures) - if err != nil { - logger.ErrorContext(ctx, "Skipping vulnerability due to invalid sandbox signatures", slog.String("id", origVuln.GetId()), slog.Any("error", err)) - return map[int][]*structpb.Value{}, nil + affectedLen := len(vuln.GetAffected()) + out := make(map[int][]*structpb.Value, len(genResp.Signatures)) + for idxStr, sigList := range genResp.Signatures { + idx, err := strconv.Atoi(idxStr) + if err != nil || idx < 0 || idx >= affectedLen { + logger.ErrorContext(ctx, "Skipping vulnerability due to invalid affected index from sandbox", + slog.String("id", vuln.GetId()), slog.String("index", idxStr)) + + return map[int][]*structpb.Value{}, nil + } + vals := make([]*structpb.Value, 0, len(sigList)) + for _, rawSig := range sigList { + var val structpb.Value + if err := protojson.Unmarshal(rawSig, &val); err != nil { + return nil, fmt.Errorf("failed to parse signature for %s: %w", vuln.GetId(), err) + } + vals = append(vals, &val) + } + if len(vals) > 0 { + out[idx] = vals + } } - return parsed, nil + return out, nil } diff --git a/go/internal/vanir/http_generator_test.go b/go/internal/vanir/http_generator_test.go index 861fbd89c02..120d08dd389 100644 --- a/go/internal/vanir/http_generator_test.go +++ b/go/internal/vanir/http_generator_test.go @@ -25,75 +25,23 @@ import ( "testing" "github.com/ossf/osv-schema/bindings/go/osvschema" - "google.golang.org/protobuf/types/known/structpb" ) -const ( - validCommit1 = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - validCommit2 = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" -) - -func gitVuln(id, repo string) *osvschema.Vulnerability { +func testVuln(id string) *osvschema.Vulnerability { return &osvschema.Vulnerability{ Id: id, Affected: []*osvschema.Affected{{ Ranges: []*osvschema.Range{{ Type: osvschema.Range_GIT, - Repo: repo, - Events: []*osvschema.Event{{Fixed: validCommit1}}, + Repo: "https://github.com/example/repo", + Events: []*osvschema.Event{{Fixed: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}}, }}, }}, } } -func TestPrepareVulnForSandbox(t *testing.T) { - badRepos := []string{"--upload-pack=sh -c id", "ssh://git@github.com/a/b", "file:///etc/passwd", "not-a-url"} - ranges := make([]*osvschema.Range, 0, len(badRepos)+2) - for _, repo := range badRepos { - ranges = append(ranges, &osvschema.Range{ - Type: osvschema.Range_GIT, - Repo: repo, - Events: []*osvschema.Event{{Fixed: validCommit1}}, - }) - } - ranges = append(ranges, - &osvschema.Range{ - Type: osvschema.Range_GIT, - Repo: "https://github.com/example/good?q=1#frag", - Events: []*osvschema.Event{{Introduced: "0"}, {Fixed: "--upload-pack=x"}, {Fixed: strings.ToUpper(validCommit2)}}, - }, - &osvschema.Range{ - Type: osvschema.Range_GIT, - Repo: "git://github.com/example/git-scheme", - Events: []*osvschema.Event{{Fixed: validCommit1}}, - }, - ) - - sanitized, hasWork := prepareVulnForSandbox(&osvschema.Vulnerability{ - Id: "OSV-2026-100", - Affected: []*osvschema.Affected{{Ranges: ranges}}, - }) - gotRanges := sanitized.GetAffected()[0].GetRanges() - if !hasWork || len(gotRanges) != 2 || - gotRanges[0].GetRepo() != "https://github.com/example/good" || - gotRanges[0].GetEvents()[0].GetFixed() != validCommit2 || - gotRanges[1].GetRepo() != "https://github.com/example/git-scheme" { - t.Errorf("unexpected sanitized ranges: hasWork=%v ranges=%v", hasWork, gotRanges) - } - - ecoSpec, _ := structpb.NewStruct(map[string]any{"fixes": []any{"https://android.googlesource.com/platform/art/+/deadbeef"}}) - if _, ok := prepareVulnForSandbox(&osvschema.Vulnerability{ - Id: "ASB-A-1", - Affected: []*osvschema.Affected{{EcosystemSpecific: ecoSpec}}, - }); !ok { - t.Error("expected hasWork=true when ecosystem_specific.fixes is set") - } -} - func TestHTTPSignatureGenerator(t *testing.T) { - var sandboxCalls atomic.Int32 sandbox := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - sandboxCalls.Add(1) var req sandboxGenerateRequest _ = json.NewDecoder(r.Body).Decode(&req) var v struct { @@ -110,18 +58,15 @@ func TestHTTPSignatureGenerator(t *testing.T) { t.Cleanup(sandbox.Close) gen := &HTTPSignatureGenerator{SandboxURL: sandbox.URL, HTTPClient: sandbox.Client()} - vulns := []*osvschema.Vulnerability{ - gitVuln("GHSA-aaaa-bbbb-cccc", "https://github.com/example/repo"), - gitVuln("OSV-BAD-IDX", "https://github.com/example/repo"), - gitVuln("OSV-NO-WORK", "not-a-url"), - } - - got, err := gen.GenerateBatch(context.Background(), vulns, "") + got, err := gen.GenerateBatch(context.Background(), []*osvschema.Vulnerability{ + testVuln("GHSA-aaaa-bbbb-cccc"), + testVuln("OSV-BAD-IDX"), + }, "") if err != nil { t.Fatalf("GenerateBatch: %v", err) } - if len(got["GHSA-aaaa-bbbb-cccc"][0]) != 1 || len(got["OSV-BAD-IDX"]) != 0 || sandboxCalls.Load() != 2 { - t.Errorf("got=%+v sandboxCalls=%d", got, sandboxCalls.Load()) + if len(got["GHSA-aaaa-bbbb-cccc"][0]) != 1 || len(got["OSV-BAD-IDX"]) != 0 { + t.Errorf("unexpected signatures: %+v", got) } } @@ -141,7 +86,7 @@ func TestHTTPSignatureGenerator_Errors(t *testing.T) { })) t.Cleanup(redir.Close) - v := gitVuln("OSV-2026-1", "https://github.com/example/repo") + v := testVuln("OSV-2026-1") if _, err := (&HTTPSignatureGenerator{SandboxURL: redir.URL}).GenerateBatch(context.Background(), []*osvschema.Vulnerability{v}, ""); err == nil || redirectHit.Load() { t.Fatalf("redirect should be refused (err=%v hit=%v)", err, redirectHit.Load()) } From 04ee8c0e741108ee44c7f825f334dec577a673b5 Mon Sep 17 00:00:00 2001 From: Rex P Date: Thu, 26 Nov 2026 17:25:00 +1100 Subject: [PATCH 3/7] fix(vanir): address PR #6403 review findings --- Makefile | 2 +- go/cmd/vanir_sandbox/main.go | 201 ++++++++++++++--------- go/cmd/vanir_sandbox/main_test.go | 169 +++++++++++++++---- go/cmd/vanir_signatures/main.go | 12 ++ go/internal/vanir/http_generator.go | 107 ++++++++---- go/internal/vanir/http_generator_test.go | 128 +++++++++++---- 6 files changed, 443 insertions(+), 176 deletions(-) diff --git a/Makefile b/Makefile index fe023b760e0..aed5c612678 100644 --- a/Makefile +++ b/Makefile @@ -19,7 +19,7 @@ lib-tests: ## Run core Python library tests ./run_tests.sh vanir-signatures-tests: ## Run Vanir signatures tests - cd go && go test ./internal/vanir/... ./cmd/vanir_signatures/... + cd go && go test ./internal/vanir/... ./cmd/vanir_signatures/... ./cmd/vanir_sandbox/... vulnfeed-tests: ## Run Go vulnfeeds tests cd vulnfeeds && ./run_tests.sh diff --git a/go/cmd/vanir_sandbox/main.go b/go/cmd/vanir_sandbox/main.go index ba41c220564..b5485cd2645 100644 --- a/go/cmd/vanir_sandbox/main.go +++ b/go/cmd/vanir_sandbox/main.go @@ -1,3 +1,5 @@ +//go:build linux + // Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); @@ -50,7 +52,7 @@ import ( const ( maxRequestBytes = 4 << 20 // 4 MiB max HTTP request payload maxOutputBytes = 4 << 20 // 4 MiB max output.json read from child - maxChildLogBytes = 64 << 10 // 64 KiB max child output logged on failure + maxChildLogBytes = 64 << 10 // 64 KiB max child output buffered in memory defaultTimeout = 25 * time.Minute shutdownTimeout = 8 * time.Second // Fits within Cloud Run's 10s SIGTERM grace period uidBase = 10000 @@ -58,6 +60,38 @@ const ( probeUID = 65534 // nobody ) +// cappedBuffer buffers up to limit bytes and silently discards excess writes so a +// noisy child cannot OOM the supervisor or stall on a full stdout/stderr pipe. +// Safe without a mutex when shared by cmd.Stdout and cmd.Stderr (os/exec uses one pipe). +type cappedBuffer struct { + buf bytes.Buffer + limit int + truncated bool +} + +func (b *cappedBuffer) Write(p []byte) (int, error) { + if rem := b.limit - b.buf.Len(); rem > 0 { + if len(p) > rem { + _, _ = b.buf.Write(p[:rem]) + b.truncated = true + } else { + _, _ = b.buf.Write(p) + } + } else { + b.truncated = true + } + + return len(p), nil +} + +func (b *cappedBuffer) String() string { + if b.truncated { + return strings.ToValidUTF8(b.buf.String(), "") + "... [truncated]" + } + + return b.buf.String() +} + // GenerateRequest is the JSON request body for POST /v1/generate. type GenerateRequest struct { Vulnerability json.RawMessage `json:"vulnerability"` // Single OSV JSON object @@ -78,14 +112,18 @@ type sandboxServer struct { selfExe string onShutdown func() - execMu sync.Mutex - seq atomic.Int64 - shutdownOnce sync.Once + execMu sync.Mutex + seq atomic.Int64 + tainted atomic.Bool } func (s *sandboxServer) routes() http.Handler { mux := http.NewServeMux() mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) { + if s.tainted.Load() { + http.Error(w, "sandbox tainted", http.StatusServiceUnavailable) + return + } w.WriteHeader(http.StatusOK) _, _ = w.Write([]byte("ok\n")) }) @@ -97,6 +135,11 @@ func (s *sandboxServer) routes() http.Handler { func (s *sandboxServer) handleGenerate(w http.ResponseWriter, r *http.Request) { ctx := r.Context() + if s.tainted.Load() { + http.Error(w, "sandbox tainted", http.StatusServiceUnavailable) + return + } + // Reject concurrent requests immediately so an in-flight child cannot queue // follow-up requests against loopback while running. if !s.execMu.TryLock() { @@ -105,6 +148,11 @@ func (s *sandboxServer) handleGenerate(w http.ResponseWriter, r *http.Request) { } defer s.execMu.Unlock() + if s.tainted.Load() { + http.Error(w, "sandbox tainted", http.StatusServiceUnavailable) + return + } + r.Body = http.MaxBytesReader(w, r.Body, maxRequestBytes) defer r.Body.Close() @@ -131,14 +179,13 @@ func (s *sandboxServer) handleGenerate(w http.ResponseWriter, r *http.Request) { //nolint:gosec // G115: uidBase + (n % uidSpan) is always in [10000, 59999]. uid := uint32(uidBase + (n % uidSpan)) - sigs, statusCode, err := s.executeRequest(ctx, n, uid, meta.ID, &req) + sigs, err := s.executeRequest(ctx, n, uid, meta.ID, &req) if err != nil { logger.ErrorContext(ctx, "Sandbox execution failed", slog.String("vuln_id", meta.ID), slog.Int64("seq", n), - slog.Int("status", statusCode), slog.Any("error", err)) - http.Error(w, err.Error(), statusCode) + http.Error(w, err.Error(), http.StatusInternalServerError) return } @@ -154,76 +201,51 @@ func (s *sandboxServer) handleGenerate(w http.ResponseWriter, r *http.Request) { _, _ = w.Write(respBytes) } -func (s *sandboxServer) executeRequest(ctx context.Context, seq int64, uid uint32, vulnID string, req *GenerateRequest) (json.RawMessage, int, error) { +func (s *sandboxServer) executeRequest(ctx context.Context, seq int64, uid uint32, vulnID string, req *GenerateRequest) (json.RawMessage, error) { jobDir := filepath.Join(s.baseWorkDir, fmt.Sprintf("vanir-job-%d", seq)) - ipcDir := filepath.Join(jobDir, "ipc") workDir := filepath.Join(jobDir, "work") gitWorkDir := filepath.Join(workDir, "git-work") + defer os.RemoveAll(jobDir) - var childPGID int - var reaped bool - var reapErr error - reapAll := func() error { - if reaped { - return reapErr - } - reaped = true - if childPGID > 0 { - _ = syscall.Kill(-childPGID, syscall.SIGKILL) - } - if s.useSetuid { - reapErr = s.reapUID(context.WithoutCancel(ctx), uid) - } - - return reapErr - } - - defer func() { - _ = reapAll() - _ = os.RemoveAll(jobDir) - }() - + // Root-owned 0711 jobDir prevents child from unlinking or listing IPC files while + // allowing traversal into child-owned 0700 workDir and gitWorkDir. for _, d := range []struct { path string mode os.FileMode }{ {jobDir, 0711}, - {ipcDir, 0755}, {workDir, 0700}, {gitWorkDir, 0700}, } { if err := os.Mkdir(d.path, d.mode); err != nil { - return nil, http.StatusInternalServerError, fmt.Errorf("failed to create %s: %w", filepath.Base(d.path), err) - } - if err := os.Chmod(d.path, d.mode); err != nil { - return nil, http.StatusInternalServerError, fmt.Errorf("failed to chmod %s: %w", filepath.Base(d.path), err) + return nil, fmt.Errorf("failed to create %s: %w", filepath.Base(d.path), err) } } - inputPath := filepath.Join(ipcDir, "input.json") - outputPath := filepath.Join(ipcDir, "output.json") + inputPath := filepath.Join(jobDir, "input.json") + outputPath := filepath.Join(jobDir, "output.json") batchPayload, err := json.Marshal([]json.RawMessage{req.Vulnerability}) if err != nil { - return nil, http.StatusInternalServerError, fmt.Errorf("failed to marshal input batch: %w", err) + return nil, fmt.Errorf("failed to marshal input batch: %w", err) } if err := os.WriteFile(inputPath, batchPayload, 0600); err != nil { - return nil, http.StatusInternalServerError, fmt.Errorf("failed to write input.json: %w", err) + return nil, fmt.Errorf("failed to write input.json: %w", err) } if err := os.WriteFile(outputPath, nil, 0600); err != nil { - return nil, http.StatusInternalServerError, fmt.Errorf("failed to pre-create output.json: %w", err) + return nil, fmt.Errorf("failed to pre-create output.json: %w", err) } if s.useSetuid { if err := os.Chown(inputPath, 0, int(uid)); err != nil { - return nil, http.StatusInternalServerError, fmt.Errorf("failed to chown input.json: %w", err) + return nil, fmt.Errorf("failed to chown input.json: %w", err) } if err := os.Chmod(inputPath, 0640); err != nil { - return nil, http.StatusInternalServerError, fmt.Errorf("failed to chmod input.json: %w", err) + return nil, fmt.Errorf("failed to chmod input.json: %w", err) } for _, p := range []string{workDir, gitWorkDir, outputPath} { if err := os.Chown(p, int(uid), int(uid)); err != nil { - return nil, http.StatusInternalServerError, fmt.Errorf("failed to chown %s: %w", p, err) + return nil, fmt.Errorf("failed to chown %s: %w", p, err) } } } @@ -264,65 +286,61 @@ func (s *sandboxServer) executeRequest(ctx context.Context, seq int64, uid uint3 } cmd.SysProcAttr = sysProcAttr cmd.Cancel = func() error { - if cmd.Process == nil { - return nil - } - return syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL) } cmd.WaitDelay = 5 * time.Second - var outBuf bytes.Buffer - cmd.Stdout = &outBuf - cmd.Stderr = &outBuf + outBuf := &cappedBuffer{limit: maxChildLogBytes} + cmd.Stdout = outBuf + cmd.Stderr = outBuf if err := cmd.Start(); err != nil { - return nil, http.StatusInternalServerError, fmt.Errorf("failed to start sandbox child: %w", err) + return nil, fmt.Errorf("failed to start sandbox child: %w", err) } - childPGID = cmd.Process.Pid waitErr := cmd.Wait() - if err := reapAll(); err != nil { - logger.ErrorContext(ctx, "UID process reaping failed; triggering shutdown", - slog.String("vuln_id", vulnID), - slog.Uint64("uid", uint64(uid)), - slog.Any("error", err)) - if s.onShutdown != nil { - s.shutdownOnce.Do(func() { go s.onShutdown() }) - } + _ = syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL) + if s.useSetuid { + if err := s.reapUID(context.WithoutCancel(ctx), uid); err != nil { + logger.ErrorContext(ctx, "UID process reaping failed; marking instance tainted and shutting down", + slog.String("vuln_id", vulnID), + slog.Uint64("uid", uint64(uid)), + slog.Any("error", err)) + s.tainted.Store(true) + if s.onShutdown != nil { + s.onShutdown() + } - return nil, http.StatusInternalServerError, fmt.Errorf("sandbox process reaping failed: %w", err) + return nil, fmt.Errorf("sandbox process reaping failed: %w", err) + } + sweepUIDTempFiles(uid) } if waitErr != nil { - outStr := outBuf.String() - if len(outStr) > maxChildLogBytes { - outStr = strings.ToValidUTF8(outStr[:maxChildLogBytes], "") + "... [truncated]" - } logger.WarnContext(ctx, "Vanir sandbox child failed", slog.String("vuln_id", vulnID), slog.Any("error", waitErr), - slog.String("output", outStr)) + slog.String("output", outBuf.String())) - return nil, http.StatusInternalServerError, fmt.Errorf("vanir sandbox execution failed: %w", waitErr) + return nil, fmt.Errorf("vanir sandbox execution failed: %w", waitErr) } outFile, err := os.Open(outputPath) if err != nil { - return nil, http.StatusInternalServerError, fmt.Errorf("failed to open output.json: %w", err) + return nil, fmt.Errorf("failed to open output.json: %w", err) } defer outFile.Close() outputBytes, err := io.ReadAll(io.LimitReader(outFile, maxOutputBytes+1)) if err != nil { - return nil, http.StatusInternalServerError, fmt.Errorf("failed to read output.json: %w", err) + return nil, fmt.Errorf("failed to read output.json: %w", err) } if len(outputBytes) > maxOutputBytes { - return nil, http.StatusInternalServerError, fmt.Errorf("output.json exceeds max size (%d bytes)", maxOutputBytes) + return nil, fmt.Errorf("output.json exceeds max size (%d bytes)", maxOutputBytes) } var rawOutput map[string]json.RawMessage if err := json.Unmarshal(outputBytes, &rawOutput); err != nil { - return nil, http.StatusInternalServerError, fmt.Errorf("failed to unmarshal output.json: %w", err) + return nil, fmt.Errorf("failed to unmarshal output.json: %w", err) } sigs := bytes.TrimSpace(rawOutput[vulnID]) @@ -330,7 +348,28 @@ func (s *sandboxServer) executeRequest(ctx context.Context, seq int64, uid uint3 sigs = json.RawMessage("{}") } - return sigs, http.StatusOK, nil + return sigs, nil +} + +// sweepUIDTempFiles removes any top-level entries owned by uid left behind in shared +// world-writable tmpfs directories across warm container requests. +func sweepUIDTempFiles(uid uint32) { + for _, dir := range []string{"/tmp", "/var/tmp", "/dev/shm", "/run/lock"} { + entries, err := os.ReadDir(dir) + if err != nil { + continue + } + for _, entry := range entries { + fullPath := filepath.Join(dir, entry.Name()) + fi, err := os.Lstat(fullPath) + if err != nil { + continue + } + if st, ok := fi.Sys().(*syscall.Stat_t); ok && st.Uid == uid { + _ = os.RemoveAll(fullPath) + } + } + } } // reapUID spawns a short-lived helper running as the given non-root UID that calls @@ -392,7 +431,9 @@ func main() { if os.Getuid() == 0 || os.Geteuid() == 0 { os.Exit(2) } - _ = syscall.Kill(-1, syscall.SIGKILL) + if err := syscall.Kill(-1, syscall.SIGKILL); err != nil && !errors.Is(err, syscall.ESRCH) { + os.Exit(3) + } return } @@ -434,13 +475,11 @@ func main() { if err != nil { logger.FatalContext(ctx, "Failed to create private sandbox base directory", slog.Any("error", err)) } - baseMode := os.FileMode(0700) if useSetuid { - baseMode = 0711 - } - if err := os.Chmod(baseWorkDir, baseMode); err != nil { - _ = os.RemoveAll(baseWorkDir) - logger.FatalContext(ctx, "Failed to chmod private sandbox base directory", slog.Any("error", err)) + if err := os.Chmod(baseWorkDir, 0711); err != nil { + _ = os.RemoveAll(baseWorkDir) + logger.FatalContext(ctx, "Failed to chmod private sandbox base directory", slog.Any("error", err)) + } } defer os.RemoveAll(baseWorkDir) diff --git a/go/cmd/vanir_sandbox/main_test.go b/go/cmd/vanir_sandbox/main_test.go index f54b93593d1..de95bf563d1 100644 --- a/go/cmd/vanir_sandbox/main_test.go +++ b/go/cmd/vanir_sandbox/main_test.go @@ -1,3 +1,5 @@ +//go:build linux + // Copyright 2026 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); @@ -28,36 +30,42 @@ import ( "time" ) +func writeMockScript(t *testing.T, body string) string { + t.Helper() + scriptPath := filepath.Join(t.TempDir(), "mock_vanir.py") + src := "#!/usr/bin/env python3\nimport argparse, json, os, subprocess, sys, time\n" + + "p = argparse.ArgumentParser()\n" + + "for a in ('--input', '--output', '--git-working-dir'): p.add_argument(a, required=True)\n" + + "args = p.parse_args()\n" + body + if err := os.WriteFile(scriptPath, []byte(src), 0600); err != nil { + t.Fatalf("write script: %v", err) + } + + return scriptPath +} + func TestSandboxEndToEnd(t *testing.T) { t.Setenv("SANDBOX_CANARY_SECRET", "must-not-leak") workRoot := t.TempDir() pidFile := filepath.Join(t.TempDir(), "bg.pid") - scriptPath := filepath.Join(t.TempDir(), "mock_vanir.py") - script := `#!/usr/bin/env python3 -import argparse, json, os, subprocess -p = argparse.ArgumentParser() -p.add_argument('--input', required=True) -p.add_argument('--output', required=True) -p.add_argument('--git-working-dir', required=True) -args = p.parse_args() - + scriptPath := writeMockScript(t, ` assert 'SANDBOX_CANARY_SECRET' not in os.environ assert os.environ.get('GIT_ALLOW_PROTOCOL') == 'https:http' -v = json.load(open(args.input, encoding='utf-8'))[0] +with open(args.input, encoding='utf-8') as f: + v = json.load(f)[0] bg = subprocess.Popen(['sleep', '60'], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) -open(` + strconv.Quote(pidFile) + `, 'w', encoding='utf-8').write(str(bg.pid)) - -json.dump({ - v['id']: {'0': [{'id': v['id'] + '-deadbeef', 'signature_type': 'Function', 'signature_version': 'v1'}]}, - 'CVE-SPOOFED': {'0': [{'id': 'CVE-SPOOFED-11111111'}]}, -}, open(args.output, 'w', encoding='utf-8')) -` - if err := os.WriteFile(scriptPath, []byte(script), 0600); err != nil { - t.Fatalf("write script: %v", err) - } +with open(`+strconv.Quote(pidFile)+`, 'w', encoding='utf-8') as f: + f.write(str(bg.pid)) + +with open(args.output, 'w', encoding='utf-8') as f: + json.dump({ + v['id']: {'0': [{'id': v['id'] + '-deadbeef', 'signature_type': 'Function', 'signature_version': 'v1'}]}, + 'CVE-SPOOFED': {'0': [{'id': 'CVE-SPOOFED-11111111'}]}, + }, f) +`) sb := &sandboxServer{ pythonBin: "python3", @@ -68,10 +76,13 @@ json.dump({ ts := httptest.NewServer(sb.routes()) t.Cleanup(ts.Close) - if resp, err := http.Get(ts.URL + "/healthz"); err != nil || resp.StatusCode != http.StatusOK { - t.Fatalf("GET /healthz failed: %v", err) - } else { - resp.Body.Close() + healthResp, err := http.Get(ts.URL + "/healthz") + if err != nil { + t.Fatalf("GET /healthz: %v", err) + } + healthResp.Body.Close() + if healthResp.StatusCode != http.StatusOK { + t.Fatalf("GET /healthz status = %d, want 200", healthResp.StatusCode) } reqBody, err := json.Marshal(GenerateRequest{ @@ -105,8 +116,14 @@ json.dump({ } // Verify background process was reaped and temp directories cleaned up. - pidBytes, _ := os.ReadFile(pidFile) - bgPID, _ := strconv.Atoi(strings.TrimSpace(string(pidBytes))) + pidBytes, err := os.ReadFile(pidFile) + if err != nil { + t.Fatalf("read pidFile: %v", err) + } + bgPID, err := strconv.Atoi(strings.TrimSpace(string(pidBytes))) + if err != nil || bgPID <= 0 { + t.Fatalf("invalid bgPID %q: %v", string(pidBytes), err) + } isDead := func(pid int) bool { if syscall.Kill(pid, 0) != nil { return true @@ -127,15 +144,97 @@ json.dump({ } } -func TestSandboxBusyReturns503(t *testing.T) { - sb := &sandboxServer{baseWorkDir: t.TempDir()} - sb.execMu.Lock() - defer sb.execMu.Unlock() +func TestSandboxHTTPGuardsAndErrors(t *testing.T) { + t.Run("busy and tainted return 503", func(t *testing.T) { + sb := &sandboxServer{baseWorkDir: t.TempDir()} + sb.execMu.Lock() + rr := httptest.NewRecorder() + sb.routes().ServeHTTP(rr, httptest.NewRequest(http.MethodPost, "/v1/generate", strings.NewReader(`{"vulnerability":{"id":"OSV-1"}}`))) + sb.execMu.Unlock() + if rr.Code != http.StatusServiceUnavailable { + t.Errorf("busy: got %d, want 503", rr.Code) + } + + sb.tainted.Store(true) + for _, tc := range []struct{ method, path string }{ + {http.MethodGet, "/healthz"}, + {http.MethodPost, "/v1/generate"}, + } { + rr := httptest.NewRecorder() + sb.routes().ServeHTTP(rr, httptest.NewRequest(tc.method, tc.path, strings.NewReader(`{"vulnerability":{"id":"OSV-1"}}`))) + if rr.Code != http.StatusServiceUnavailable { + t.Errorf("tainted %s %s: got %d, want 503", tc.method, tc.path, rr.Code) + } + } + }) - rr := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPost, "/v1/generate", strings.NewReader(`{"vulnerability":{"id":"OSV-BUSY"}}`)) - sb.routes().ServeHTTP(rr, req) - if rr.Code != http.StatusServiceUnavailable { - t.Errorf("got %d, want 503", rr.Code) + t.Run("request validation 400 and 413", func(t *testing.T) { + sb := &sandboxServer{baseWorkDir: t.TempDir()} + for _, tc := range []struct { + name string + body string + want int + }{ + {"invalid json", "{bad", http.StatusBadRequest}, + {"missing vuln id", `{"vulnerability":{}}`, http.StatusBadRequest}, + {"oversized body", `{"vulnerability":{"id":"` + strings.Repeat("a", maxRequestBytes) + `"}}`, http.StatusRequestEntityTooLarge}, + } { + rr := httptest.NewRecorder() + sb.routes().ServeHTTP(rr, httptest.NewRequest(http.MethodPost, "/v1/generate", strings.NewReader(tc.body))) + if rr.Code != tc.want { + t.Errorf("%s: got %d, want %d", tc.name, rr.Code, tc.want) + } + } + }) + + t.Run("child failure, timeout, empty output, and oversized output", func(t *testing.T) { + for _, tc := range []struct { + name string + script string + timeout time.Duration + wantCode int + wantBody string + }{ + {"non-zero exit", "sys.stderr.write('boom')\nsys.exit(1)\n", 10 * time.Second, http.StatusInternalServerError, ""}, + {"timeout kills child", "time.sleep(10)\n", 200 * time.Millisecond, http.StatusInternalServerError, ""}, + {"null output falls back to empty object", "open(args.output, 'w').write('{\"OSV-1\": null}')\n", 10 * time.Second, http.StatusOK, `{"signatures":{}}`}, + {"malformed output.json", "open(args.output, 'w').write('{bad')\n", 10 * time.Second, http.StatusInternalServerError, ""}, + {"oversized output.json", "open(args.output, 'w').write('x' * (5 * 1024 * 1024))\n", 10 * time.Second, http.StatusInternalServerError, ""}, + } { + t.Run(tc.name, func(t *testing.T) { + workRoot := t.TempDir() + sb := &sandboxServer{ + pythonBin: "python3", + scriptPath: writeMockScript(t, tc.script), + baseWorkDir: workRoot, + timeout: tc.timeout, + } + rr := httptest.NewRecorder() + sb.routes().ServeHTTP(rr, httptest.NewRequest(http.MethodPost, "/v1/generate", strings.NewReader(`{"vulnerability":{"id":"OSV-1"}}`))) + if rr.Code != tc.wantCode { + t.Errorf("got %d, want %d (body=%q)", rr.Code, tc.wantCode, rr.Body.String()) + } + if tc.wantBody != "" && strings.TrimSpace(rr.Body.String()) != tc.wantBody { + t.Errorf("body = %q, want %q", rr.Body.String(), tc.wantBody) + } + if entries, err := os.ReadDir(workRoot); err != nil || len(entries) != 0 { + t.Errorf("workRoot not cleaned up: %v (%d entries)", err, len(entries)) + } + }) + } + }) +} + +func TestCappedBuffer(t *testing.T) { + b := &cappedBuffer{limit: 5} + n, err := b.Write([]byte("abcdef")) + if err != nil || n != 6 { + t.Fatalf("Write() = (%d, %v), want (6, nil)", n, err) + } + if _, err := b.Write([]byte("more")); err != nil { + t.Fatalf("second Write: %v", err) + } + if got := b.String(); got != "abcde... [truncated]" { + t.Errorf("String() = %q, want %q", got, "abcde... [truncated]") } } diff --git a/go/cmd/vanir_signatures/main.go b/go/cmd/vanir_signatures/main.go index 6929981dbd5..feb5d1cad05 100644 --- a/go/cmd/vanir_signatures/main.go +++ b/go/cmd/vanir_signatures/main.go @@ -51,6 +51,18 @@ func main() { 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.Parse() + batchSizeSet := false + flag.Visit(func(f *flag.Flag) { + if f.Name == "batch-size" { + batchSizeSet = true + } + }) + // Cloud Run vanir-sandbox processes one vulnerability per request (concurrency=1); + // default to batch-size=1 so Runner fans out across instances and isolates retries. + if sandboxURL != "" && !batchSizeSet { + batchSize = 1 + } + logger.InitGlobalLogger() defer logger.Close() diff --git a/go/internal/vanir/http_generator.go b/go/internal/vanir/http_generator.go index db0d9377537..9238bb7af5e 100644 --- a/go/internal/vanir/http_generator.go +++ b/go/internal/vanir/http_generator.go @@ -37,6 +37,8 @@ import ( const ( maxSandboxResponseBytes = 4 << 20 // 4 MiB max HTTP response from vanir-sandbox maxSandboxErrBodyBytes = 1024 // Truncate error bodies before logging + maxSandboxAttempts = 3 + defaultRetryBackoff = 500 * time.Millisecond ) func refuseRedirects(*http.Request, []*http.Request) error { @@ -59,31 +61,33 @@ type sandboxGenerateResponse struct { // TODO: Integrate with gitter's /commit-pack endpoint to relay cached shallow commit // packs instead of having vanir-sandbox fetch directly from upstream Git hosts. type HTTPSignatureGenerator struct { - SandboxURL string - HTTPClient *http.Client - Timeout time.Duration + SandboxURL string + HTTPClient *http.Client + Timeout time.Duration + retryBackoff time.Duration } var _ SignatureGenerator = (*HTTPSignatureGenerator)(nil) // NewHTTPSignatureGenerator creates an HTTPSignatureGenerator authenticated with Google OIDC -// identity tokens targeting sandboxURL. +// identity tokens targeting sandboxURL (origin only, e.g. https://vanir-sandbox-xyz.run.app). func NewHTTPSignatureGenerator(ctx context.Context, sandboxURL string) (*HTTPSignatureGenerator, error) { sandboxURL = strings.TrimRight(strings.TrimSpace(sandboxURL), "/") u, err := url.Parse(sandboxURL) - if sandboxURL == "" || err != nil || !strings.EqualFold(u.Scheme, "https") || u.Host == "" || u.User != nil { - return nil, fmt.Errorf("sandboxURL must be a valid https URL without userinfo: %q", sandboxURL) + if sandboxURL == "" || err != nil || !strings.EqualFold(u.Scheme, "https") || u.Host == "" || u.User != nil || + u.Path != "" || u.RawQuery != "" || u.Fragment != "" { + return nil, fmt.Errorf("sandboxURL must be a valid https origin URL without path/query/userinfo: %q", sandboxURL) } + origin := "https://" + u.Host - httpClient, err := idtoken.NewClient(ctx, sandboxURL) + httpClient, err := idtoken.NewClient(ctx, origin) if err != nil { - return nil, fmt.Errorf("failed to create OIDC HTTP client for %s: %w", sandboxURL, err) + return nil, fmt.Errorf("failed to create OIDC HTTP client for %s: %w", origin, err) } - httpClient.Timeout = defaultBatchTimeout httpClient.CheckRedirect = refuseRedirects return &HTTPSignatureGenerator{ - SandboxURL: sandboxURL, + SandboxURL: origin, HTTPClient: httpClient, Timeout: defaultBatchTimeout, }, nil @@ -107,6 +111,27 @@ func (g *HTTPSignatureGenerator) GenerateBatch(ctx context.Context, vulns []*osv return result, nil } +func isRetryableSandboxStatus(code int) bool { + return code == http.StatusTooManyRequests || + code == http.StatusBadGateway || + code == http.StatusServiceUnavailable || + code == http.StatusGatewayTimeout +} + +func isValidSignatureValue(val *structpb.Value) bool { + fields := val.GetStructValue().GetFields() + if fields == nil { + return false + } + for _, key := range []string{"id", "signature_type", "signature_version"} { + if fields[key].GetStringValue() == "" { + return false + } + } + + return true +} + func (g *HTTPSignatureGenerator) generateSingle(ctx context.Context, vuln *osvschema.Vulnerability) (map[int][]*structpb.Value, error) { vulnBytes, err := protojson.MarshalOptions{UseProtoNames: true}.Marshal(vuln) if err != nil { @@ -124,37 +149,58 @@ func (g *HTTPSignatureGenerator) generateSingle(ctx context.Context, vuln *osvsc reqCtx, cancel := context.WithTimeout(ctx, timeout) defer cancel() - httpReq, err := http.NewRequestWithContext(reqCtx, http.MethodPost, strings.TrimRight(g.SandboxURL, "/")+"/v1/generate", bytes.NewReader(reqPayload)) - if err != nil { - return nil, fmt.Errorf("failed to create sandbox request for %s: %w", vuln.GetId(), err) - } - httpReq.GetBody = nil - httpReq.Header.Set("Content-Type", "application/json") - httpClient := g.HTTPClient if httpClient == nil { httpClient = noRedirectHTTPClient } - resp, err := httpClient.Do(httpReq) - if err != nil { - return nil, fmt.Errorf("sandbox HTTP request failed for %s: %w", vuln.GetId(), err) + backoff := g.retryBackoff + if backoff <= 0 { + backoff = defaultRetryBackoff } - defer resp.Body.Close() - respBytes, err := io.ReadAll(io.LimitReader(resp.Body, maxSandboxResponseBytes+1)) - if err != nil { - return nil, fmt.Errorf("failed to read sandbox response for %s: %w", vuln.GetId(), err) + endpoint := strings.TrimRight(g.SandboxURL, "/") + "/v1/generate" + var respBytes []byte + var statusCode int + for attempt := 1; attempt <= maxSandboxAttempts; attempt++ { + httpReq, err := http.NewRequestWithContext(reqCtx, http.MethodPost, endpoint, bytes.NewReader(reqPayload)) + if err != nil { + return nil, fmt.Errorf("failed to create sandbox request for %s: %w", vuln.GetId(), err) + } + httpReq.Header.Set("Content-Type", "application/json") + + resp, err := httpClient.Do(httpReq) + if err != nil { + return nil, fmt.Errorf("sandbox HTTP request failed for %s: %w", vuln.GetId(), err) + } + statusCode = resp.StatusCode + respBytes, err = io.ReadAll(io.LimitReader(resp.Body, maxSandboxResponseBytes+1)) + resp.Body.Close() + if err != nil { + return nil, fmt.Errorf("failed to read sandbox response for %s: %w", vuln.GetId(), err) + } + if statusCode == http.StatusOK || !isRetryableSandboxStatus(statusCode) || attempt == maxSandboxAttempts { + break + } + + timer := time.NewTimer(backoff * time.Duration(attempt)) + select { + case <-reqCtx.Done(): + timer.Stop() + return nil, reqCtx.Err() + case <-timer.C: + } } + if len(respBytes) > maxSandboxResponseBytes { return nil, fmt.Errorf("sandbox response for %s exceeds maximum size (%d bytes)", vuln.GetId(), maxSandboxResponseBytes) } - if resp.StatusCode != http.StatusOK { + if statusCode != http.StatusOK { errBody := strings.TrimSpace(string(respBytes)) if len(errBody) > maxSandboxErrBodyBytes { errBody = strings.ToValidUTF8(errBody[:maxSandboxErrBodyBytes], "") + "... [truncated]" } - return nil, fmt.Errorf("sandbox returned status %d for %s: %s", resp.StatusCode, vuln.GetId(), errBody) + return nil, fmt.Errorf("sandbox returned status %d for %s: %s", statusCode, vuln.GetId(), errBody) } var genResp sandboxGenerateResponse @@ -166,7 +212,7 @@ func (g *HTTPSignatureGenerator) generateSingle(ctx context.Context, vuln *osvsc out := make(map[int][]*structpb.Value, len(genResp.Signatures)) for idxStr, sigList := range genResp.Signatures { idx, err := strconv.Atoi(idxStr) - if err != nil || idx < 0 || idx >= affectedLen { + if err != nil || idx < 0 || idx >= affectedLen || strconv.Itoa(idx) != idxStr { logger.ErrorContext(ctx, "Skipping vulnerability due to invalid affected index from sandbox", slog.String("id", vuln.GetId()), slog.String("index", idxStr)) @@ -175,8 +221,11 @@ func (g *HTTPSignatureGenerator) generateSingle(ctx context.Context, vuln *osvsc vals := make([]*structpb.Value, 0, len(sigList)) for _, rawSig := range sigList { var val structpb.Value - if err := protojson.Unmarshal(rawSig, &val); err != nil { - return nil, fmt.Errorf("failed to parse signature for %s: %w", vuln.GetId(), err) + if err := protojson.Unmarshal(rawSig, &val); err != nil || !isValidSignatureValue(&val) { + logger.ErrorContext(ctx, "Skipping vulnerability due to malformed signature from sandbox", + slog.String("id", vuln.GetId()), slog.Int("index", idx)) + + return map[int][]*structpb.Value{}, nil } vals = append(vals, &val) } diff --git a/go/internal/vanir/http_generator_test.go b/go/internal/vanir/http_generator_test.go index 120d08dd389..f39a5d0860f 100644 --- a/go/internal/vanir/http_generator_test.go +++ b/go/internal/vanir/http_generator_test.go @@ -23,6 +23,7 @@ import ( "strings" "sync/atomic" "testing" + "time" "github.com/ossf/osv-schema/bindings/go/osvschema" ) @@ -42,18 +43,32 @@ func testVuln(id string) *osvschema.Vulnerability { func TestHTTPSignatureGenerator(t *testing.T) { sandbox := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost || r.URL.Path != "/v1/generate" { + t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path) + } var req sandboxGenerateRequest - _ = json.NewDecoder(r.Body).Decode(&req) + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + t.Errorf("decode request: %v", err) + } var v struct { ID string `json:"id"` } - _ = json.Unmarshal(req.Vulnerability, &v) + if err := json.Unmarshal(req.Vulnerability, &v); err != nil { + t.Errorf("unmarshal vulnerability: %v", err) + } w.Header().Set("Content-Type", "application/json") - if v.ID == "OSV-BAD-IDX" { - _, _ = w.Write([]byte(`{"signatures":{"99":[{"id":"OSV-BAD-IDX-1"}]}}`)) - return + switch v.ID { + case "OSV-BAD-IDX": + _, _ = w.Write([]byte(`{"signatures":{"99":[{"id":"OSV-BAD-IDX-1","signature_type":"Function","signature_version":"v1"}]}}`)) + case "OSV-NONCANON-IDX": + _, _ = w.Write([]byte(`{"signatures":{"00":[{"id":"OSV-NONCANON-IDX-1","signature_type":"Function","signature_version":"v1"}]}}`)) + case "OSV-BAD-SIG": + _, _ = w.Write([]byte(`{"signatures":{"0":[{"id":"OSV-BAD-SIG-1"}]}}`)) + case "OSV-EMPTY": + _, _ = w.Write([]byte(`{"signatures":{}}`)) + default: + _, _ = fmt.Fprintf(w, `{"signatures":{"0":[{"id":"%s-11223344","signature_type":"Function","signature_version":"v1"}]}}`, v.ID) } - _, _ = fmt.Fprintf(w, `{"signatures":{"0":[{"id":"%s-11223344","signature_type":"Function","signature_version":"v1"}]}}`, v.ID) })) t.Cleanup(sandbox.Close) @@ -61,42 +76,95 @@ func TestHTTPSignatureGenerator(t *testing.T) { got, err := gen.GenerateBatch(context.Background(), []*osvschema.Vulnerability{ testVuln("GHSA-aaaa-bbbb-cccc"), testVuln("OSV-BAD-IDX"), + testVuln("OSV-NONCANON-IDX"), + testVuln("OSV-BAD-SIG"), + testVuln("OSV-EMPTY"), }, "") if err != nil { t.Fatalf("GenerateBatch: %v", err) } - if len(got["GHSA-aaaa-bbbb-cccc"][0]) != 1 || len(got["OSV-BAD-IDX"]) != 0 { - t.Errorf("unexpected signatures: %+v", got) + sigs := got["GHSA-aaaa-bbbb-cccc"][0] + if len(sigs) != 1 || sigs[0].GetStructValue().GetFields()["id"].GetStringValue() != "GHSA-aaaa-bbbb-cccc-11223344" { + t.Errorf("unexpected valid signature: %+v", sigs) + } + for _, skipped := range []string{"OSV-BAD-IDX", "OSV-NONCANON-IDX", "OSV-BAD-SIG", "OSV-EMPTY"} { + if _, ok := got[skipped]; ok { + t.Errorf("expected %s to be omitted from results", skipped) + } } } -func TestHTTPSignatureGenerator_Errors(t *testing.T) { - if _, err := NewHTTPSignatureGenerator(context.Background(), "http://insecure.example.com"); err == nil { - t.Error("expected error for non-https sandboxURL") +func TestHTTPSignatureGenerator_RetriesAndErrors(t *testing.T) { + for _, badURL := range []string{ + "", + "http://insecure.example.com", + "https://user:pass@example.com", + "https://example.com/v1/generate", + "https://example.com?foo=bar", + "https://example.com#frag", + } { + if _, err := NewHTTPSignatureGenerator(context.Background(), badURL); err == nil { + t.Errorf("expected error for invalid sandboxURL %q", badURL) + } } - var redirectHit atomic.Bool - target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - redirectHit.Store(true) - w.WriteHeader(http.StatusOK) - })) - t.Cleanup(target.Close) - redir := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - http.Redirect(w, r, target.URL, http.StatusTemporaryRedirect) + // Retries transient 503 and succeeds. + var attempts atomic.Int32 + flaky := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + if attempts.Add(1) < 3 { + w.WriteHeader(http.StatusServiceUnavailable) + _, _ = w.Write([]byte("sandbox busy")) + + return + } + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"signatures":{"0":[{"id":"OSV-RETRY-1","signature_type":"Function","signature_version":"v1"}]}}`)) })) - t.Cleanup(redir.Close) + 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")}, "") + 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()) + } - v := testVuln("OSV-2026-1") - if _, err := (&HTTPSignatureGenerator{SandboxURL: redir.URL}).GenerateBatch(context.Background(), []*osvschema.Vulnerability{v}, ""); err == nil || redirectHit.Load() { - t.Fatalf("redirect should be refused (err=%v hit=%v)", err, redirectHit.Load()) + // Refuses both 302 (POST->GET) and 307 redirects via CheckRedirect: refuseRedirects. + for _, code := range []int{http.StatusFound, http.StatusTemporaryRedirect} { + var redirectHit atomic.Bool + target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + redirectHit.Store(true) + w.WriteHeader(http.StatusOK) + })) + t.Cleanup(target.Close) + redir := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, target.URL, code) + })) + t.Cleanup(redir.Close) + + _, 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()) + } } - errSrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - w.WriteHeader(http.StatusInternalServerError) - _, _ = w.Write([]byte(strings.Repeat("X", 4096))) - })) - t.Cleanup(errSrv.Close) - if _, err := (&HTTPSignatureGenerator{SandboxURL: errSrv.URL}).GenerateBatch(context.Background(), []*osvschema.Vulnerability{v}, ""); err == nil || !strings.Contains(err.Error(), "... [truncated]") { - t.Errorf("expected truncated 500 error, got %v", err) + // Truncates large 500 error responses, rejects malformed JSON and >4 MiB responses. + for _, tc := range []struct { + name string + status int + body string + wantSub string + }{ + {"truncated 500", http.StatusInternalServerError, strings.Repeat("X", 4096), "... [truncated]"}, + {"malformed JSON", http.StatusOK, "{not-json", "unmarshal sandbox response"}, + {"oversized 200", http.StatusOK, strings.Repeat("A", maxSandboxResponseBytes+10), "exceeds maximum size"}, + } { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(tc.status) + _, _ = w.Write([]byte(tc.body)) + })) + t.Cleanup(srv.Close) + _, 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) + } } } From 33481142964dd5b168ae466e5b93a65b2c1f51a5 Mon Sep 17 00:00:00 2001 From: Rex P Date: Fri, 27 Nov 2026 10:09:01 +1100 Subject: [PATCH 4/7] fix(vanir): address GitHub review comments on PR #6403 --- AGENTS.md | 2 +- .../terraform/modules/osv/vanir_sandbox.tf | 4 +- go/Dockerfile | 4 +- go/cmd/vanir_sandbox/main.go | 63 +++++++++---------- go/cmd/vanir_sandbox/main_test.go | 2 +- go/internal/vanir/http_generator.go | 6 +- go/internal/vanir/http_generator_test.go | 13 ++++ 7 files changed, 53 insertions(+), 41 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 3cce1b1f637..3a5209270e6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -334,7 +334,7 @@ All Go microservices are compiled using a single, unified multi-target Dockerfil - 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. 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, IPC/UTS namespaces, and fail-closed post-request `kill(-1, SIGKILL)` UID reaping, running with a zero-IAM-role service account and no VPC access. + - 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. 15. **`ubuntubinarymapper`**: - Run as a cron job (`go/cmd/ubuntubinarymapper/`). diff --git a/deployment/terraform/modules/osv/vanir_sandbox.tf b/deployment/terraform/modules/osv/vanir_sandbox.tf index 434b3953520..3ebfe78b822 100644 --- a/deployment/terraform/modules/osv/vanir_sandbox.tf +++ b/deployment/terraform/modules/osv/vanir_sandbox.tf @@ -19,7 +19,9 @@ resource "google_service_account_iam_member" "vanir_sandbox_deployer_act_as" { } # Untrusted Cloud Run Gen2 microVM sandbox for running Vanir signature generation. -# Intentionally has NO vpc_access block (physically air-gapped from internal VPC / GKE / Redis / Cloud SQL). +# Note: template is in lifecycle.ignore_changes, so Terraform only bootstraps the initial +# revision; deployment/clouddeploy/vanir-sandbox/run-{staging,prod}.yaml are the source of +# truth for runtime settings (zero-IAM SA, Gen2, concurrency=1, and no VPC access). resource "google_cloud_run_v2_service" "vanir_sandbox" { project = var.project_id name = "vanir-sandbox" diff --git a/go/Dockerfile b/go/Dockerfile index 1cdbb842708..37f992ec202 100644 --- a/go/Dockerfile +++ b/go/Dockerfile @@ -263,7 +263,7 @@ RUN --mount=type=cache,target=/go/pkg/mod \ 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 && \ +RUN apt-get update && apt-get install -y --no-install-recommends git ca-certificates tini && \ rm -rf /var/lib/apt/lists/* && \ find / -xdev -perm /6000 -exec chmod a-s {} + COPY --from=vanir-python-deps /app/.venv /app/.venv @@ -271,7 +271,7 @@ ENV PATH="/app/.venv/bin:$PATH" COPY --from=vanir-sandbox-build /app/vanir_sandbox /usr/local/bin/vanir_sandbox COPY cmd/vanir_signatures/generate_signatures.py /usr/local/bin/generate_signatures.py RUN chmod 755 /usr/local/bin/vanir_sandbox /usr/local/bin/generate_signatures.py -ENTRYPOINT ["/usr/local/bin/vanir_sandbox"] +ENTRYPOINT ["/usr/bin/tini", "--", "/usr/local/bin/vanir_sandbox"] # ======================================================== # Target: Ubuntu Binary Mapper diff --git a/go/cmd/vanir_sandbox/main.go b/go/cmd/vanir_sandbox/main.go index b5485cd2645..6a732f9c75e 100644 --- a/go/cmd/vanir_sandbox/main.go +++ b/go/cmd/vanir_sandbox/main.go @@ -16,9 +16,8 @@ // Package main implements the untrusted Vanir sandbox HTTP server for Cloud Run Gen2. // Each request processes a single vulnerability record under a unique non-root Linux UID, -// isolated work directory, stripped environment, IPC/UTS namespaces, and fail-closed -// post-request UID process reaping. Authentication is enforced by Cloud Run IAM -// (roles/run.invoker). +// isolated work directory, stripped environment, and fail-closed post-request UID process +// reaping. Authentication is enforced by Cloud Run IAM (roles/run.invoker). // // TODO: Integrate with gitter's /commit-pack endpoint (--git-instead-ofs) so Git-only // requests can run offline inside an empty CLONE_NEWNET network namespace. @@ -60,6 +59,8 @@ const ( probeUID = 65534 // nobody ) +var errChildTimeout = errors.New("vanir sandbox execution timed out") + // cappedBuffer buffers up to limit bytes and silently discards excess writes so a // noisy child cannot OOM the supervisor or stall on a full stdout/stderr pipe. // Safe without a mutex when shared by cmd.Stdout and cmd.Stderr (os/exec uses one pipe). @@ -103,14 +104,13 @@ type GenerateResponse struct { } type sandboxServer struct { - pythonBin string - scriptPath string - baseWorkDir string - timeout time.Duration - useSetuid bool - supportsIPCUTSNS bool - selfExe string - onShutdown func() + pythonBin string + scriptPath string + baseWorkDir string + timeout time.Duration + useSetuid bool + selfExe string + onShutdown func() execMu sync.Mutex seq atomic.Int64 @@ -185,7 +185,11 @@ func (s *sandboxServer) handleGenerate(w http.ResponseWriter, r *http.Request) { slog.String("vuln_id", meta.ID), slog.Int64("seq", n), slog.Any("error", err)) - http.Error(w, err.Error(), http.StatusInternalServerError) + status := http.StatusInternalServerError + if errors.Is(err, errChildTimeout) { + status = http.StatusGatewayTimeout + } + http.Error(w, err.Error(), status) return } @@ -281,9 +285,6 @@ func (s *sandboxServer) executeRequest(ctx context.Context, seq int64, uid uint3 if s.useSetuid { sysProcAttr.Credential = &syscall.Credential{Uid: uid, Gid: uid, Groups: []uint32{}} } - if s.supportsIPCUTSNS { - sysProcAttr.Cloneflags |= syscall.CLONE_NEWIPC | syscall.CLONE_NEWUTS - } cmd.SysProcAttr = sysProcAttr cmd.Cancel = func() error { return syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL) @@ -321,6 +322,9 @@ func (s *sandboxServer) executeRequest(ctx context.Context, seq int64, uid uint3 slog.String("vuln_id", vulnID), slog.Any("error", waitErr), slog.String("output", outBuf.String())) + if errors.Is(cmdCtx.Err(), context.DeadlineExceeded) && ctx.Err() == nil { + return nil, fmt.Errorf("%w: %w", errChildTimeout, waitErr) + } return nil, fmt.Errorf("vanir sandbox execution failed: %w", waitErr) } @@ -394,7 +398,7 @@ func (s *sandboxServer) reapUID(parentCtx context.Context, uid uint32) error { return nil } -func probeCapability(selfExe string, cloneFlags uintptr) error { +func probeSetuid(selfExe string) error { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() @@ -402,7 +406,6 @@ func probeCapability(selfExe string, cloneFlags uintptr) error { cmd.Env = []string{} cmd.SysProcAttr = &syscall.SysProcAttr{ Credential: &syscall.Credential{Uid: probeUID, Gid: probeUID, Groups: []uint32{}}, - Cloneflags: cloneFlags, } return cmd.Run() @@ -458,17 +461,11 @@ func main() { } useSetuid := isRoot - supportsIPCUTSNS := false if useSetuid { syscall.Umask(0022) - if err := probeCapability(selfExe, 0); err != nil { + if err := probeSetuid(selfExe); err != nil { logger.FatalContext(ctx, "CAP_SETUID/CAP_SETGID probe failed (Cloud Run Gen2 is required for UID isolation)", slog.Any("error", err)) } - if err := probeCapability(selfExe, syscall.CLONE_NEWIPC|syscall.CLONE_NEWUTS); err != nil { - logger.WarnContext(ctx, "CLONE_NEWIPC/CLONE_NEWUTS probe failed; continuing without IPC/UTS namespace isolation", slog.Any("error", err)) - } else { - supportsIPCUTSNS = true - } } baseWorkDir, err := os.MkdirTemp("", "vanir-sandbox-root-*") @@ -487,14 +484,13 @@ func main() { defer srvCancel() sb := &sandboxServer{ - pythonBin: *pythonBin, - scriptPath: *scriptPath, - baseWorkDir: baseWorkDir, - timeout: *timeout, - useSetuid: useSetuid, - supportsIPCUTSNS: supportsIPCUTSNS, - selfExe: selfExe, - onShutdown: srvCancel, + pythonBin: *pythonBin, + scriptPath: *scriptPath, + baseWorkDir: baseWorkDir, + timeout: *timeout, + useSetuid: useSetuid, + selfExe: selfExe, + onShutdown: srvCancel, } httpServer := &http.Server{ @@ -507,8 +503,7 @@ func main() { logger.InfoContext(ctx, "Starting vanir_sandbox server", slog.Int("port", *port), - slog.Bool("use_setuid", useSetuid), - slog.Bool("supports_ipc_uts_ns", supportsIPCUTSNS)) + slog.Bool("use_setuid", useSetuid)) go func() { if err := httpServer.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { diff --git a/go/cmd/vanir_sandbox/main_test.go b/go/cmd/vanir_sandbox/main_test.go index de95bf563d1..55d8670241c 100644 --- a/go/cmd/vanir_sandbox/main_test.go +++ b/go/cmd/vanir_sandbox/main_test.go @@ -196,7 +196,7 @@ func TestSandboxHTTPGuardsAndErrors(t *testing.T) { wantBody string }{ {"non-zero exit", "sys.stderr.write('boom')\nsys.exit(1)\n", 10 * time.Second, http.StatusInternalServerError, ""}, - {"timeout kills child", "time.sleep(10)\n", 200 * time.Millisecond, http.StatusInternalServerError, ""}, + {"timeout kills child", "time.sleep(10)\n", 200 * time.Millisecond, http.StatusGatewayTimeout, ""}, {"null output falls back to empty object", "open(args.output, 'w').write('{\"OSV-1\": null}')\n", 10 * time.Second, http.StatusOK, `{"signatures":{}}`}, {"malformed output.json", "open(args.output, 'w').write('{bad')\n", 10 * time.Second, http.StatusInternalServerError, ""}, {"oversized output.json", "open(args.output, 'w').write('x' * (5 * 1024 * 1024))\n", 10 * time.Second, http.StatusInternalServerError, ""}, diff --git a/go/internal/vanir/http_generator.go b/go/internal/vanir/http_generator.go index 9238bb7af5e..93d901c3928 100644 --- a/go/internal/vanir/http_generator.go +++ b/go/internal/vanir/http_generator.go @@ -111,11 +111,13 @@ func (g *HTTPSignatureGenerator) GenerateBatch(ctx context.Context, vulns []*osv return result, nil } +// isRetryableSandboxStatus returns true for transient ingress/capacity errors. +// 504 is intentionally excluded because vanir_sandbox returns 504 when a child +// exceeds its per-request timeout (25m) and should not be immediately retried. func isRetryableSandboxStatus(code int) bool { return code == http.StatusTooManyRequests || code == http.StatusBadGateway || - code == http.StatusServiceUnavailable || - code == http.StatusGatewayTimeout + code == http.StatusServiceUnavailable } func isValidSignatureValue(val *structpb.Value) bool { diff --git a/go/internal/vanir/http_generator_test.go b/go/internal/vanir/http_generator_test.go index f39a5d0860f..18d9d1aac63 100644 --- a/go/internal/vanir/http_generator_test.go +++ b/go/internal/vanir/http_generator_test.go @@ -127,6 +127,19 @@ func TestHTTPSignatureGenerator_RetriesAndErrors(t *testing.T) { t.Fatalf("retry failed: got=%+v err=%v attempts=%d", got, err, attempts.Load()) } + // Does not retry 504 child timeout. + var timeoutAttempts atomic.Int32 + timedOut := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + timeoutAttempts.Add(1) + http.Error(w, "vanir sandbox execution timed out", http.StatusGatewayTimeout) + })) + t.Cleanup(timedOut.Close) + _, err = (&HTTPSignatureGenerator{SandboxURL: timedOut.URL, HTTPClient: timedOut.Client(), retryBackoff: time.Millisecond}). + 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()) + } + // Refuses both 302 (POST->GET) and 307 redirects via CheckRedirect: refuseRedirects. for _, code := range []int{http.StatusFound, http.StatusTemporaryRedirect} { var redirectHit atomic.Bool From ddb9b0702346e28c30eeac92b74b787edc737294 Mon Sep 17 00:00:00 2001 From: Rex P Date: Fri, 27 Nov 2026 10:25:39 +1100 Subject: [PATCH 5/7] fix(vanir): restrict /tmp and move sandbox root to /run/vanir-sandbox --- go/cmd/vanir_sandbox/main.go | 26 +++++++++++++++++++------- 1 file changed, 19 insertions(+), 7 deletions(-) diff --git a/go/cmd/vanir_sandbox/main.go b/go/cmd/vanir_sandbox/main.go index 6a732f9c75e..0fccc524041 100644 --- a/go/cmd/vanir_sandbox/main.go +++ b/go/cmd/vanir_sandbox/main.go @@ -461,22 +461,34 @@ func main() { } useSetuid := isRoot + var baseWorkDir string if useSetuid { syscall.Umask(0022) if err := probeSetuid(selfExe); err != nil { logger.FatalContext(ctx, "CAP_SETUID/CAP_SETGID probe failed (Cloud Run Gen2 is required for UID isolation)", slog.Any("error", err)) } - } - - baseWorkDir, err := os.MkdirTemp("", "vanir-sandbox-root-*") - if err != nil { - logger.FatalContext(ctx, "Failed to create private sandbox base directory", slog.Any("error", err)) - } - if useSetuid { + // Prevent untrusted children from writing to shared world-writable temp dirs. + // /dev/shm stays writable for Python forkserver POSIX semaphores and is swept per-UID. + for _, dir := range []string{"/tmp", "/var/tmp", "/run/lock"} { + if err := os.Chmod(dir, 0755); err != nil && !errors.Is(err, os.ErrNotExist) { + logger.WarnContext(ctx, "Failed to restrict shared temp directory permissions", + slog.String("dir", dir), slog.Any("error", err)) + } + } + baseWorkDir = "/run/vanir-sandbox" + if err := os.MkdirAll(baseWorkDir, 0711); err != nil { + logger.FatalContext(ctx, "Failed to create private sandbox base directory", slog.Any("error", err)) + } if err := os.Chmod(baseWorkDir, 0711); err != nil { _ = os.RemoveAll(baseWorkDir) logger.FatalContext(ctx, "Failed to chmod private sandbox base directory", slog.Any("error", err)) } + } else { + var err error + baseWorkDir, err = os.MkdirTemp("", "vanir-sandbox-root-*") + if err != nil { + logger.FatalContext(ctx, "Failed to create private sandbox base directory", slog.Any("error", err)) + } } defer os.RemoveAll(baseWorkDir) From 55e89de85e56fcf8485d76a63525670b633c84a8 Mon Sep 17 00:00:00 2001 From: Rex P Date: Fri, 27 Nov 2026 10:45:16 +1100 Subject: [PATCH 6/7] chore(vanir): default max-workers to 15 in sandbox mode --- go/cmd/vanir_signatures/main.go | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/go/cmd/vanir_signatures/main.go b/go/cmd/vanir_signatures/main.go index feb5d1cad05..89dedfea3b9 100644 --- a/go/cmd/vanir_signatures/main.go +++ b/go/cmd/vanir_signatures/main.go @@ -52,15 +52,25 @@ func main() { flag.Parse() batchSizeSet := false + maxWorkersSet := false flag.Visit(func(f *flag.Flag) { - if f.Name == "batch-size" { + 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 so Runner fans out across instances and isolates retries. - if sandboxURL != "" && !batchSizeSet { - batchSize = 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() From e58ed3b7a262380238bb7479bfb5c0a9aaab3226 Mon Sep 17 00:00:00 2001 From: Rex P Date: Tue, 1 Dec 2026 11:40:32 +1100 Subject: [PATCH 7/7] fix(vanir): drop stale TODOs and add jittered backoff + transport retries --- go/cmd/vanir_sandbox/main.go | 3 - go/internal/vanir/http_generator.go | 86 +++++++++++++++++++----- go/internal/vanir/http_generator_test.go | 42 ++++++++++++ 3 files changed, 110 insertions(+), 21 deletions(-) diff --git a/go/cmd/vanir_sandbox/main.go b/go/cmd/vanir_sandbox/main.go index 0fccc524041..fe59f3c7424 100644 --- a/go/cmd/vanir_sandbox/main.go +++ b/go/cmd/vanir_sandbox/main.go @@ -18,9 +18,6 @@ // Each request processes a single vulnerability record under a unique non-root Linux UID, // isolated work directory, stripped environment, and fail-closed post-request UID process // reaping. Authentication is enforced by Cloud Run IAM (roles/run.invoker). -// -// TODO: Integrate with gitter's /commit-pack endpoint (--git-instead-ofs) so Git-only -// requests can run offline inside an empty CLONE_NEWNET network namespace. package main import ( diff --git a/go/internal/vanir/http_generator.go b/go/internal/vanir/http_generator.go index 93d901c3928..5b1c9c01301 100644 --- a/go/internal/vanir/http_generator.go +++ b/go/internal/vanir/http_generator.go @@ -17,10 +17,13 @@ package vanir import ( "bytes" "context" + "crypto/x509" "encoding/json" + "errors" "fmt" "io" "log/slog" + "math/rand/v2" "net/http" "net/url" "strconv" @@ -37,8 +40,9 @@ import ( const ( maxSandboxResponseBytes = 4 << 20 // 4 MiB max HTTP response from vanir-sandbox maxSandboxErrBodyBytes = 1024 // Truncate error bodies before logging - maxSandboxAttempts = 3 - defaultRetryBackoff = 500 * time.Millisecond + maxSandboxAttempts = 5 + defaultRetryBackoff = 2 * time.Second + maxRetryBackoff = 30 * time.Second ) func refuseRedirects(*http.Request, []*http.Request) error { @@ -57,9 +61,6 @@ type sandboxGenerateResponse struct { // HTTPSignatureGenerator invokes the remote Cloud Run vanir-sandbox service over // Google OIDC-authenticated HTTPS (roles/run.invoker). -// -// TODO: Integrate with gitter's /commit-pack endpoint to relay cached shallow commit -// packs instead of having vanir-sandbox fetch directly from upstream Git hosts. type HTTPSignatureGenerator struct { SandboxURL string HTTPClient *http.Client @@ -120,6 +121,40 @@ func isRetryableSandboxStatus(code int) bool { code == http.StatusServiceUnavailable } +func isRetryableTransportError(ctx context.Context, err error) bool { + if err == nil || ctx.Err() != nil || errors.Is(err, context.Canceled) { + return false + } + if _, ok := errors.AsType[x509.UnknownAuthorityError](err); ok { + return false + } + if _, ok := errors.AsType[x509.CertificateInvalidError](err); ok { + return false + } + if _, ok := errors.AsType[x509.HostnameError](err); ok { + return false + } + if strings.Contains(err.Error(), "unsupported protocol scheme") { + return false + } + + return true +} + +func retryDelay(base time.Duration, attempt int) time.Duration { + delay := base + for i := 1; i < attempt && delay < maxRetryBackoff; i++ { + delay = min(delay*2, maxRetryBackoff) + } + half := delay / 2 + if half <= 0 { + return delay + } + // Equal jitter in [delay/2, delay] to spread retries across workers. + //nolint:gosec // G404: retry jitter does not require cryptographic randomness. + return half + rand.N(delay-half+1) +} + func isValidSignatureValue(val *structpb.Value) bool { fields := val.GetStructValue().GetFields() if fields == nil { @@ -161,8 +196,11 @@ func (g *HTTPSignatureGenerator) generateSingle(ctx context.Context, vuln *osvsc } endpoint := strings.TrimRight(g.SandboxURL, "/") + "/v1/generate" - var respBytes []byte - var statusCode int + var ( + respBytes []byte + statusCode int + lastErr error + ) for attempt := 1; attempt <= maxSandboxAttempts; attempt++ { httpReq, err := http.NewRequestWithContext(reqCtx, http.MethodPost, endpoint, bytes.NewReader(reqPayload)) if err != nil { @@ -172,19 +210,28 @@ func (g *HTTPSignatureGenerator) generateSingle(ctx context.Context, vuln *osvsc resp, err := httpClient.Do(httpReq) if err != nil { - return nil, fmt.Errorf("sandbox HTTP request failed for %s: %w", vuln.GetId(), err) - } - statusCode = resp.StatusCode - respBytes, err = io.ReadAll(io.LimitReader(resp.Body, maxSandboxResponseBytes+1)) - resp.Body.Close() - if err != nil { - return nil, fmt.Errorf("failed to read sandbox response for %s: %w", vuln.GetId(), err) - } - if statusCode == http.StatusOK || !isRetryableSandboxStatus(statusCode) || attempt == maxSandboxAttempts { - break + lastErr = fmt.Errorf("sandbox HTTP request failed for %s: %w", vuln.GetId(), err) + if !isRetryableTransportError(reqCtx, err) || attempt == maxSandboxAttempts { + return nil, lastErr + } + } else { + statusCode = resp.StatusCode + respBytes, err = io.ReadAll(io.LimitReader(resp.Body, maxSandboxResponseBytes+1)) + resp.Body.Close() + if err != nil { + lastErr = fmt.Errorf("failed to read sandbox response for %s: %w", vuln.GetId(), err) + if !isRetryableTransportError(reqCtx, err) || attempt == maxSandboxAttempts { + return nil, lastErr + } + } else { + lastErr = nil + if statusCode == http.StatusOK || !isRetryableSandboxStatus(statusCode) || attempt == maxSandboxAttempts { + break + } + } } - timer := time.NewTimer(backoff * time.Duration(attempt)) + timer := time.NewTimer(retryDelay(backoff, attempt)) select { case <-reqCtx.Done(): timer.Stop() @@ -192,6 +239,9 @@ func (g *HTTPSignatureGenerator) generateSingle(ctx context.Context, vuln *osvsc case <-timer.C: } } + if lastErr != nil { + return nil, lastErr + } if len(respBytes) > maxSandboxResponseBytes { return nil, fmt.Errorf("sandbox response for %s exceeds maximum size (%d bytes)", vuln.GetId(), maxSandboxResponseBytes) diff --git a/go/internal/vanir/http_generator_test.go b/go/internal/vanir/http_generator_test.go index 18d9d1aac63..8e07e67601a 100644 --- a/go/internal/vanir/http_generator_test.go +++ b/go/internal/vanir/http_generator_test.go @@ -127,6 +127,27 @@ func TestHTTPSignatureGenerator_RetriesAndErrors(t *testing.T) { t.Fatalf("retry failed: got=%+v err=%v attempts=%d", got, err, attempts.Load()) } + // Retries transient transport errors (e.g. abrupt connection drop) and succeeds. + var transportAttempts atomic.Int32 + dropper := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + if transportAttempts.Add(1) < 3 { + if hj, ok := w.(http.Hijacker); ok { + if conn, _, err := hj.Hijack(); err == nil { + _ = conn.Close() + return + } + } + } + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"signatures":{"0":[{"id":"OSV-DROP-1","signature_type":"Function","signature_version":"v1"}]}}`)) + })) + 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")}, "") + 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()) + } + // Does not retry 504 child timeout. var timeoutAttempts atomic.Int32 timedOut := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { @@ -181,3 +202,24 @@ func TestHTTPSignatureGenerator_RetriesAndErrors(t *testing.T) { } } } + +func TestRetryDelay(t *testing.T) { + for _, tc := range []struct { + attempt int + minWant time.Duration + maxWant time.Duration + }{ + {1, 1 * time.Second, 2 * time.Second}, + {2, 2 * time.Second, 4 * time.Second}, + {3, 4 * time.Second, 8 * time.Second}, + {4, 8 * time.Second, 16 * time.Second}, + {10, maxRetryBackoff / 2, maxRetryBackoff}, + } { + for range 20 { + d := retryDelay(2*time.Second, tc.attempt) + if d < tc.minWant || d > tc.maxWant { + t.Fatalf("retryDelay(2s, %d) = %v, want in [%v, %v]", tc.attempt, d, tc.minWant, tc.maxWant) + } + } + } +}