Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -331,7 +331,7 @@ All Go microservices are compiled using a single, unified multi-target Dockerfil
- Long-running metrics collector daemon (`go/cmd/custommetrics/`) that periodically reads batch/dataset state from Datastore (`JobData`, `SourceRepository`, `ImportFindings`) and GCS (`all.zip`, `modified_id.csv`) and exposes dataset, drift, reconciler, deleter, and linter state metrics on `:9090/metrics` for GMP/Grafana.

13. **`vanir_signatures`**:
- Cron job orchestrated in Go (`go/cmd/vanir_signatures/` and `go/internal/vanir/`) that queries modified vulnerabilities, generates Vanir signatures, and writes them back to the database. Supports both remote Cloud Run `vanir-sandbox` execution (via `VANIR_SANDBOX_URL`) and local `generate_signatures.py` fallback.
- Distroless Go cron job (`go/cmd/vanir_signatures/` and `go/internal/vanir/`) that queries modified vulnerabilities, delegates signature generation to the remote Cloud Run `vanir-sandbox` service (required `VANIR_SANDBOX_URL`), and writes results back to the database. Local non-sandbox execution is disabled.

14. **`vanir_sandbox`**:
- Untrusted Cloud Run Gen2 HTTP service (`go/cmd/vanir_sandbox/`) that executes `generate_signatures.py` for a single vulnerability record per request under a unique non-root Linux UID, isolated `0700` work directory, and fail-closed post-request `kill(-1, SIGKILL)` UID reaping, running with a zero-IAM-role service account and no VPC access.
Expand Down
2 changes: 1 addition & 1 deletion deployment/build-and-stage.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -287,7 +287,7 @@ steps:

# Build/push vanir-signatures images to gcr.io/oss-vdb.
- name: gcr.io/cloud-builders/docker
args: ['buildx', 'build', '--load', '-t', 'gcr.io/oss-vdb/vanir-signatures:latest', '-t', 'gcr.io/oss-vdb/vanir-signatures:$COMMIT_SHA', '--target', 'vanir-signatures', '--build-context', 'bindings=../bindings', '--build-context', 'poetry=../docker/poetry', '-f', 'Dockerfile', '--pull', '.']
args: ['buildx', 'build', '--load', '-t', 'gcr.io/oss-vdb/vanir-signatures:latest', '-t', 'gcr.io/oss-vdb/vanir-signatures:$COMMIT_SHA', '--target', 'vanir-signatures', '--build-context', 'bindings=../bindings', '-f', 'Dockerfile', '--pull', '.']
dir: 'go'
id: 'build-vanir-signatures'
waitFor: ['build-importer']
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,11 @@ spec:
imagePullPolicy: Always
resources:
requests:
cpu: "12"
memory: "100Gi"
cpu: "1"
memory: "2Gi"
limits:
cpu: "28"
memory: "220Gi"
cpu: "2"
memory: "4Gi"
env:
- name: POSTGRES_PORT
value: "6432"
Expand All @@ -37,10 +37,4 @@ spec:
secretKeyRef:
name: osv-db-worker-password
key: password
nodeSelector:
cloud.google.com/gke-nodepool: highend
tolerations:
- key: workloadType
operator: Equal
value: highend
restartPolicy: Never
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,6 @@ spec:
value: osv-test-vulnerabilities
- name: POSTGRES_HOST
value: "172.24.1.3"
# Deterministic Cloud Run URL: https://<service>-<project-number>.<region>.run.app
- name: VANIR_SANDBOX_URL
value: "https://vanir-sandbox-175272184261.us-west2.run.app"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

could we make project-number a variable instead of hard-coded here?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hmm I think it's a bit annoying to actually add to the format it into the variable. I'll have a look.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

asked the AI to implement something, but I don't like the replacement stuff, so sticking with the hard coded id for now.

Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,6 @@ spec:
value: osv-vulnerabilities
- name: POSTGRES_HOST
value: "10.25.1.3"
# Deterministic Cloud Run URL: https://<service>-<project-number>.<region>.run.app
- name: VANIR_SANDBOX_URL
value: "https://vanir-sandbox-651737493649.us-west2.run.app"
29 changes: 12 additions & 17 deletions go/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,18 @@ RUN --mount=type=cache,target=/go/pkg/mod \
--mount=type=cache,target=/root/.cache/go-build \
CGO_ENABLED=0 go build -o /app/vanir_signatures ./cmd/vanir_signatures/

FROM gcr.io/distroless/static-debian12@sha256:d75cdd72874d4790092fcb1b058493ecf6bb5bf2b2b897045b00ff01d91843f2 AS vanir-signatures
COPY --from=vanir-signatures-build /app/vanir_signatures /
ENTRYPOINT ["/vanir_signatures"]

# ========================================================
# Target: Vanir Sandbox
# ========================================================
FROM builder AS vanir-sandbox-build
RUN --mount=type=cache,target=/go/pkg/mod \
--mount=type=cache,target=/root/.cache/go-build \
CGO_ENABLED=0 go build -o /app/vanir_sandbox ./cmd/vanir_sandbox/

FROM python:3.13-slim@sha256:8d9d0b8bcf6506481eae4907c18f5e3e7902e629f5f6d684f9e7c32e85e3ddf0 AS vanir-python-deps
ENV POETRY_HOME="/opt/poetry"
COPY --from=poetry requirements.txt ./poetry-requirements.txt
Expand All @@ -245,23 +257,6 @@ COPY cmd/vanir_signatures/pyproject.toml cmd/vanir_signatures/poetry.lock ./
COPY cmd/vanir_signatures/osv/pyproject.toml cmd/vanir_signatures/osv/README.md cmd/vanir_signatures/osv/vulnerability_pb2.py ./osv/
RUN POETRY_VIRTUALENVS_IN_PROJECT=true poetry install --only main --no-interaction --no-ansi

FROM python:3.13-slim@sha256:8d9d0b8bcf6506481eae4907c18f5e3e7902e629f5f6d684f9e7c32e85e3ddf0 AS vanir-signatures
RUN apt-get update && apt-get install -y --no-install-recommends git ca-certificates && rm -rf /var/lib/apt/lists/*
COPY --from=vanir-python-deps /app/.venv /app/.venv
ENV PATH="/app/.venv/bin:$PATH"
COPY --from=vanir-signatures-build /app/vanir_signatures /usr/local/bin/vanir_signatures
COPY cmd/vanir_signatures/generate_signatures.py /usr/local/bin/generate_signatures.py
RUN chmod 755 /usr/local/bin/generate_signatures.py
ENTRYPOINT ["/usr/local/bin/vanir_signatures"]

# ========================================================
# Target: Vanir Sandbox
# ========================================================
FROM builder AS vanir-sandbox-build
RUN --mount=type=cache,target=/go/pkg/mod \
--mount=type=cache,target=/root/.cache/go-build \
CGO_ENABLED=0 go build -o /app/vanir_sandbox ./cmd/vanir_sandbox/

FROM python:3.13-slim@sha256:8d9d0b8bcf6506481eae4907c18f5e3e7902e629f5f6d684f9e7c32e85e3ddf0 AS vanir-sandbox
RUN apt-get update && apt-get install -y --no-install-recommends git ca-certificates tini && \
rm -rf /var/lib/apt/lists/* && \
Expand Down
50 changes: 11 additions & 39 deletions go/cmd/vanir_signatures/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,47 +40,25 @@ func main() {
maxWorkers int
dryRun bool
hours int
pythonBin string
scriptPath string
sandboxURL string
)

flag.IntVar(&batchSize, "batch-size", 100, "Number of vulnerabilities to process in each batch.")
flag.IntVar(&maxWorkers, "max-workers", 10, "Maximum number of parallel batch workers.")
flag.IntVar(&batchSize, "batch-size", 1, "Number of vulnerabilities to process serially per worker batch.")
flag.IntVar(&maxWorkers, "max-workers", 15, "Maximum number of parallel workers calling vanir-sandbox.")
flag.BoolVar(&dryRun, "dry-run", false, "Perform a dry run without modifying GCS or Datastore.")
flag.IntVar(&hours, "hours", 0, "Number of hours back to process modified records.")
flag.StringVar(&pythonBin, "python-bin", "python3", "Python interpreter binary to use.")
flag.StringVar(&scriptPath, "script-path", "/usr/local/bin/generate_signatures.py", "Path to the Python Vanir signature generation script.")
flag.StringVar(&sandboxURL, "sandbox-url", os.Getenv("VANIR_SANDBOX_URL"), "URL of the remote Cloud Run vanir-sandbox service (defaults to VANIR_SANDBOX_URL). If empty, runs generate_signatures.py locally.")
flag.StringVar(&sandboxURL, "sandbox-url", os.Getenv("VANIR_SANDBOX_URL"), "Required URL of the remote Cloud Run vanir-sandbox service (defaults to VANIR_SANDBOX_URL).")
flag.Parse()

batchSizeSet := false
maxWorkersSet := false
flag.Visit(func(f *flag.Flag) {
switch f.Name {
case "batch-size":
batchSizeSet = true
case "max-workers":
maxWorkersSet = true
}
})
// Cloud Run vanir-sandbox processes one vulnerability per request (concurrency=1);
// default to batch-size=1 and max-workers=15 so Runner fans out across instances
// and isolates retries.
if sandboxURL != "" {
if !batchSizeSet {
batchSize = 1
}
if !maxWorkersSet {
maxWorkers = 15
}
}

logger.InitGlobalLogger()
defer logger.Close()

ctx := context.Background()

if strings.TrimSpace(sandboxURL) == "" {
logger.FatalContext(ctx, "VANIR_SANDBOX_URL environment variable or -sandbox-url flag must be set (local non-sandbox execution is disabled)")
}

projectID := os.Getenv("GOOGLE_CLOUD_PROJECT")
if projectID == "" {
logger.FatalContext(ctx, "GOOGLE_CLOUD_PROJECT environment variable not set")
Expand Down Expand Up @@ -124,17 +102,11 @@ func main() {
}
jobStore := osvdatastore.NewJobDataStore(dsClient)

var generator vanir.SignatureGenerator
if sandboxURL != "" {
httpGen, err := vanir.NewHTTPSignatureGenerator(ctx, sandboxURL)
if err != nil {
logger.FatalContext(ctx, "Failed to create HTTP Vanir sandbox generator", slog.Any("error", err))
}
generator = httpGen
logger.InfoContext(ctx, "Using remote Vanir sandbox generator", slog.String("sandbox_url", sandboxURL))
} else {
generator = vanir.NewPythonGenerator(pythonBin, scriptPath)
generator, err := vanir.NewHTTPSignatureGenerator(ctx, sandboxURL)
if err != nil {
logger.FatalContext(ctx, "Failed to create HTTP Vanir sandbox generator", slog.Any("error", err))
}
logger.InfoContext(ctx, "Using remote Vanir sandbox generator", slog.String("sandbox_url", generator.SandboxURL))

runner := &vanir.Runner{
VulnStore: vulnStore,
Expand Down
160 changes: 1 addition & 159 deletions go/internal/vanir/generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,21 +15,10 @@
package vanir

import (
"bytes"
"context"
"encoding/json"
"fmt"
"log/slog"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"time"

"github.com/google/osv.dev/go/logger"
"github.com/ossf/osv-schema/bindings/go/osvschema"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/types/known/structpb"
)

Expand All @@ -40,152 +29,5 @@ type SignatureMap map[string]map[int][]*structpb.Value

// SignatureGenerator abstracts the Vanir signature generation engine.
type SignatureGenerator interface {
GenerateBatch(ctx context.Context, vulns []*osvschema.Vulnerability, gitWorkingDir string) (SignatureMap, error)
}

// PythonGenerator shells out to the Python Vanir helper script to generate signatures for a batch.
type PythonGenerator struct {
PythonBin string
ScriptPath string
Timeout time.Duration
}

var _ SignatureGenerator = (*PythonGenerator)(nil)

func NewPythonGenerator(pythonBin, scriptPath string) *PythonGenerator {
if pythonBin == "" {
pythonBin = "python3"
}
if scriptPath == "" {
scriptPath = "/usr/local/bin/generate_signatures.py"
}

return &PythonGenerator{
PythonBin: pythonBin,
ScriptPath: scriptPath,
Timeout: defaultBatchTimeout,
}
}

func (g *PythonGenerator) GenerateBatch(ctx context.Context, vulns []*osvschema.Vulnerability, workingDir string) (SignatureMap, error) {
if len(vulns) == 0 {
return SignatureMap{}, nil
}

ipcDir, err := os.MkdirTemp(workingDir, "vanir-ipc-*")
if err != nil {
return nil, fmt.Errorf("failed to create IPC temp dir: %w", err)
}
defer os.RemoveAll(ipcDir)
gitDir, err := os.MkdirTemp(workingDir, "vanir-git-*")
if err != nil {
return nil, fmt.Errorf("failed to create git temp dir: %w", err)
}
defer os.RemoveAll(gitDir)

inputPath := filepath.Join(ipcDir, "input.json")
outputPath := filepath.Join(ipcDir, "output.json")

marshaler := protojson.MarshalOptions{UseProtoNames: true}
rawMessages := make([]json.RawMessage, 0, len(vulns))
for _, v := range vulns {
b, err := marshaler.Marshal(v)
if err != nil {
return nil, fmt.Errorf("failed to marshal vulnerability %s to JSON: %w", v.GetId(), err)
}
rawMessages = append(rawMessages, json.RawMessage(b))
}

inputData, err := json.Marshal(rawMessages)
if err != nil {
return nil, fmt.Errorf("failed to marshal batch JSON array: %w", err)
}

if err := os.WriteFile(inputPath, inputData, 0600); err != nil {
return nil, fmt.Errorf("failed to write input JSON file: %w", err)
}

timeout := g.Timeout
if timeout <= 0 {
timeout = defaultBatchTimeout
}
cmdCtx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()

//nolint:gosec // G204: PythonBin and ScriptPath are trusted service configuration paths.
cmd := exec.CommandContext(
cmdCtx,
g.PythonBin,
g.ScriptPath,
"--input", inputPath,
"--output", outputPath,
"--git-working-dir", gitDir,
)
cmd.Env = filteredEnv(os.Environ())
cmd.WaitDelay = 10 * time.Second
var stderr bytes.Buffer
cmd.Stdout = &stderr
cmd.Stderr = &stderr

if err := cmd.Run(); err != nil {
logger.ErrorContext(ctx, "Python Vanir signature generation failed",
slog.Any("error", err),
slog.String("output", stderr.String()))

return nil, fmt.Errorf("vanir python runner failed: %w", err)
}

if stderr.Len() > 0 {
logger.DebugContext(ctx, "Python Vanir runner output", slog.String("output", stderr.String()))
}

outputData, err := os.ReadFile(outputPath)
if err != nil {
return nil, fmt.Errorf("failed to read output JSON file: %w", err)
}

var rawOutput map[string]map[string][]any
if err := json.Unmarshal(outputData, &rawOutput); err != nil {
return nil, fmt.Errorf("failed to unmarshal output JSON: %w", err)
}

result := make(SignatureMap, len(rawOutput))
for vulnID, affectedMap := range rawOutput {
idxMap := make(map[int][]*structpb.Value, len(affectedMap))
for idxStr, sigList := range affectedMap {
idx, err := strconv.Atoi(idxStr)
if err != nil {
return nil, fmt.Errorf("invalid affected index %q for %s: %w", idxStr, vulnID, err)
}
vals := make([]*structpb.Value, 0, len(sigList))
for _, rawSig := range sigList {
val, err := structpb.NewValue(rawSig)
if err != nil {
return nil, fmt.Errorf("failed to convert signature to structpb.Value for %s: %w", vulnID, err)
}
vals = append(vals, val)
}
if len(vals) > 0 {
idxMap[idx] = vals
}
}
if len(idxMap) > 0 {
result[vulnID] = idxMap
}
}

return result, nil
}

// filteredEnv strips PostgreSQL connection variables (including POSTGRES_PASSWORD)
// so database credentials are not exposed to the Python Vanir subprocess.
func filteredEnv(env []string) []string {
out := make([]string, 0, len(env))
for _, entry := range env {
if !strings.HasPrefix(entry, "POSTGRES_") {
out = append(out, entry)
}
}

return out
GenerateBatch(ctx context.Context, vulns []*osvschema.Vulnerability) (SignatureMap, error)
}
2 changes: 1 addition & 1 deletion go/internal/vanir/http_generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ func NewHTTPSignatureGenerator(ctx context.Context, sandboxURL string) (*HTTPSig
}, nil
}

func (g *HTTPSignatureGenerator) GenerateBatch(ctx context.Context, vulns []*osvschema.Vulnerability, _ string) (SignatureMap, error) {
func (g *HTTPSignatureGenerator) GenerateBatch(ctx context.Context, vulns []*osvschema.Vulnerability) (SignatureMap, error) {
result := make(SignatureMap, len(vulns))
for _, v := range vulns {
if v == nil {
Expand Down
Loading
Loading