diff --git a/go/internal/database/datastore/vulnerability.go b/go/internal/database/datastore/vulnerability.go index 2915ac1c4bd..fc726436786 100644 --- a/go/internal/database/datastore/vulnerability.go +++ b/go/internal/database/datastore/vulnerability.go @@ -472,9 +472,16 @@ func (s *VulnerabilityStore) writeBaseEntities(ctx context.Context, req models.W dsVulnKey := datastore.NameKey("Vulnerability", req.ID, nil) dsVuln := new(Vulnerability) - if err := tx.Get(dsVulnKey, dsVuln); err != nil && !errors.Is(err, datastore.ErrNoSuchEntity) { + err = tx.Get(dsVulnKey, dsVuln) + if err != nil && !errors.Is(err, datastore.ErrNoSuchEntity) { return fmt.Errorf("failed to get old Vulnerability: %w", err) } + if err == nil && dsVuln.SourceID != "" { + existingSource, _, _ := strings.Cut(dsVuln.SourceID, ":") + if existingSource != "" && existingSource != req.Source { + return fmt.Errorf("%w: %s is owned by %q, cannot overwrite from %q", models.ErrSourceMismatch, req.ID, existingSource, req.Source) + } + } dsVuln.SourceID = req.Source + ":" + req.Path dsVuln.Modified = req.Enriched.GetModified().AsTime() diff --git a/go/internal/database/datastore/vulnerability_test.go b/go/internal/database/datastore/vulnerability_test.go index 409e7067fdd..4b361f4c58f 100644 --- a/go/internal/database/datastore/vulnerability_test.go +++ b/go/internal/database/datastore/vulnerability_test.go @@ -681,3 +681,32 @@ func TestJobDataStore(t *testing.T) { t.Errorf("GetJobData[[]string] mismatch (-want +got):\n%s", diff) } } + +func TestVulnerabilityStore_Write_SourceOwnership(t *testing.T) { + ctx := t.Context() + store := NewVulnerabilityStore(VulnStoreConfig{ + Client: testutils.MustNewDatastoreClientForTesting(t), + GCS: testutils.NewMockStorage(), + }) + + v := &osvschema.Vulnerability{Id: "GHSA-ownr-test-0001", Summary: "Original"} + write := func(source, path string, vuln *osvschema.Vulnerability) error { + return store.Write(ctx, models.WriteRequest{ + ID: vuln.GetId(), Source: source, Path: path, Raw: vuln, Enriched: vuln, + AffectedCommits: models.AffectedCommitsResult{Skip: true}, + }) + } + + if err := write("ghsa", "advisories/GHSA-ownr-test-0001.json", v); err != nil { + t.Fatalf("initial Write() failed: %v", err) + } + if err := write("ghsa", "advisories/moved/GHSA-ownr-test-0001.json", v); err != nil { + t.Fatalf("same-source Write() failed: %v", err) + } + if err := write("other", "GHSA-ownr-test-0001.json", &osvschema.Vulnerability{Id: v.GetId(), Summary: "Hijacked"}); !errors.Is(err, models.ErrSourceMismatch) { + t.Fatalf("cross-source Write() error = %v, want ErrSourceMismatch", err) + } + if gotV, gotRef, err := store.GetWithMetadata(ctx, v.GetId()); err != nil || gotRef.Source != "ghsa" || gotV.GetSummary() != "Original" { + t.Errorf("record modified after ErrSourceMismatch: ref=%+v vuln=%+v err=%v", gotRef, gotV, err) + } +} diff --git a/go/internal/database/postgres/queries/vulnerability.sql b/go/internal/database/postgres/queries/vulnerability.sql index 55eb6625466..ee6b769fc76 100644 --- a/go/internal/database/postgres/queries/vulnerability.sql +++ b/go/internal/database/postgres/queries/vulnerability.sql @@ -13,6 +13,13 @@ SELECT id, source_id, source_path, source_modified, proto FROM vulnerabilities WHERE id = @id; +-- name: GetVulnerabilitySourceForUpdate :one +SELECT source_id +FROM vulnerabilities +WHERE id = @id +-- Lock the existing row for the duration of the transaction. +FOR UPDATE; + -- name: VulnerabilityExists :one SELECT EXISTS(SELECT 1 FROM vulnerabilities WHERE id = @id); diff --git a/go/internal/database/postgres/vulnerability.go b/go/internal/database/postgres/vulnerability.go index ebd8d9a8748..8414e522e5a 100644 --- a/go/internal/database/postgres/vulnerability.go +++ b/go/internal/database/postgres/vulnerability.go @@ -445,6 +445,14 @@ func (s *VulnerabilityStore) Write(ctx context.Context, req models.WriteRequest) } return s.withTx(ctx, id, func(q *Queries) error { + existingSource, err := q.GetVulnerabilitySourceForUpdate(ctx, id) + if err != nil && !errors.Is(err, pgx.ErrNoRows) { + return fmt.Errorf("failed to check existing source for %s: %w", id, err) + } + if err == nil && existingSource != "" && existingSource != req.Source { + return fmt.Errorf("%w: %s is owned by %q, cannot overwrite from %q", models.ErrSourceMismatch, id, existingSource, req.Source) + } + params := UpsertVulnerabilityParams{ ID: id, SourceID: req.Source, diff --git a/go/internal/database/postgres/vulnerability.sql.go b/go/internal/database/postgres/vulnerability.sql.go index f9208366cd6..df3bbbfecd0 100644 --- a/go/internal/database/postgres/vulnerability.sql.go +++ b/go/internal/database/postgres/vulnerability.sql.go @@ -130,6 +130,21 @@ func (q *Queries) GetVulnerabilityProtos(ctx context.Context, ids []string) ([]G return items, nil } +const getVulnerabilitySourceForUpdate = `-- name: GetVulnerabilitySourceForUpdate :one +SELECT source_id +FROM vulnerabilities +WHERE id = $1 +FOR UPDATE +` + +// Lock the existing row for the duration of the transaction. +func (q *Queries) GetVulnerabilitySourceForUpdate(ctx context.Context, id string) (string, error) { + row := q.db.QueryRow(ctx, getVulnerabilitySourceForUpdate, id) + var source_id string + err := row.Scan(&source_id) + return source_id, err +} + const getVulnerabilitySourceModified = `-- name: GetVulnerabilitySourceModified :one SELECT source_modified FROM vulnerabilities diff --git a/go/internal/database/postgres/vulnerability_test.go b/go/internal/database/postgres/vulnerability_test.go index 475bc993475..e6990f18038 100644 --- a/go/internal/database/postgres/vulnerability_test.go +++ b/go/internal/database/postgres/vulnerability_test.go @@ -242,6 +242,15 @@ func (f *fakeWriteDB) QueryRow(_ context.Context, sql string, args ...any) pgx.R return &fakeWriteRow{vals: []any{rec.revision}} + case strings.Contains(sql, "GetVulnerabilitySourceForUpdate"): + id := args[0].(string) + rec, ok := f.vulns[id] + if !ok { + return &fakeWriteRow{err: pgx.ErrNoRows} + } + + return &fakeWriteRow{vals: []any{rec.source}} + case strings.Contains(sql, "GetVulnerabilityWithMetadata"): id := args[0].(string) rec, ok := f.vulns[id] @@ -577,3 +586,31 @@ func TestVulnerabilityStore_MutateWithOptimisticConcurrencyRetry(t *testing.T) { t.Errorf("Mutate() exhausted error = %v, want 'exhausted retries mutating vulnerability OSV-2026-200'", err) } } + +func TestVulnerabilityStore_Write_SourceOwnership(t *testing.T) { + ctx := t.Context() + db := newFakeWriteDB() + store := NewVulnerabilityStore(VulnStoreConfig{DB: db}) + + v := &osvschema.Vulnerability{Id: "PYSEC-2026-42"} + write := func(source, path string) error { + return store.Write(ctx, models.WriteRequest{ + ID: v.GetId(), Source: source, Path: path, Raw: v, Enriched: v, + AffectedCommits: models.AffectedCommitsResult{Skip: true}, + }) + } + + if err := write("python", "vulns/PYSEC-2026-42.yaml"); err != nil { + t.Fatalf("initial Write() failed: %v", err) + } + if err := write("python", "vulns/moved/PYSEC-2026-42.yaml"); err != nil { + t.Fatalf("same-source Write() failed: %v", err) + } + db.rolledBack = false + if err := write("malicious-packages", "osv/PYSEC-2026-42.json"); !errors.Is(err, models.ErrSourceMismatch) { + t.Fatalf("cross-source Write() error = %v, want ErrSourceMismatch", err) + } + if !db.rolledBack || db.vulns[v.GetId()].source != "python" { + t.Errorf("expected rollback with source=python, got rolledBack=%v source=%q", db.rolledBack, db.vulns[v.GetId()].source) + } +} diff --git a/go/internal/importer/helper.go b/go/internal/importer/helper.go index a2034ee773e..293bfdffa16 100644 --- a/go/internal/importer/helper.go +++ b/go/internal/importer/helper.go @@ -7,34 +7,20 @@ import ( "strings" "github.com/google/osv.dev/go/internal/models" + "github.com/google/osv.dev/go/internal/osvutil/schema" "github.com/google/osv.dev/go/logger" ) -var validIDRegex = regexp.MustCompile(`^[a-zA-Z0-9:_.-]+$`) - -// isValidID reports whether id uses only characters permitted by the OSV schema -// (^[a-zA-Z0-9:_.-]+$) and is not a relative path segment ("." or ".."). +// isValidID reports whether id uses only characters permitted by the OSV schema, +// is within the maximum ID length, and is not a relative path segment ("." or ".."). func isValidID(id string) bool { - if id == "." || id == ".." { - return false - } - - return validIDRegex.MatchString(id) + return schema.IsValidID(id) } // hasValidPrefix reports whether name starts with any of the configured ID prefixes // (or returns true when no prefixes are configured). func hasValidPrefix(name string, idPrefixes []string) bool { - if len(idPrefixes) == 0 { - return true - } - for _, prefix := range idPrefixes { - if strings.HasPrefix(name, prefix) { - return true - } - } - - return false + return schema.HasValidPrefix(name, idPrefixes) } func compileIgnorePatterns(sourceRepo *models.SourceRepository) []*regexp.Regexp { diff --git a/go/internal/models/models.go b/go/internal/models/models.go index abfa24ae877..556e717f882 100644 --- a/go/internal/models/models.go +++ b/go/internal/models/models.go @@ -8,3 +8,6 @@ var ErrNotFound = errors.New("not found") // ErrInvalidArgument indicates that an argument provided to a function or method is invalid. var ErrInvalidArgument = errors.New("invalid argument") + +// ErrSourceMismatch indicates that a vulnerability is owned by a different source repository. +var ErrSourceMismatch = errors.New("vulnerability owned by a different source") diff --git a/go/internal/osvutil/schema/schema.go b/go/internal/osvutil/schema/schema.go index b236f0f0a69..ef6570fd4d1 100644 --- a/go/internal/osvutil/schema/schema.go +++ b/go/internal/osvutil/schema/schema.go @@ -7,6 +7,7 @@ import ( _ "embed" "encoding/json" "fmt" + "regexp" "strings" "unicode/utf8" @@ -50,6 +51,37 @@ func IsKnownEcosystem(ecosystem string) bool { return ok } +// MaxIDLength caps the length of a vulnerability ID so derived Datastore keys +// (e.g. "-" on AffectedCommits) stay well within Datastore's 1500-byte key limit. +const MaxIDLength = 256 + +var validIDRegex = regexp.MustCompile(`^[a-zA-Z0-9:_.-]+$`) + +// IsValidID reports whether id uses only characters permitted by the OSV schema +// (^[a-zA-Z0-9:_.-]+$), does not exceed MaxIDLength, and is not "." or "..". +func IsValidID(id string) bool { + if id == "" || id == "." || id == ".." || len(id) > MaxIDLength { + return false + } + + return validIDRegex.MatchString(id) +} + +// HasValidPrefix reports whether name starts with any of the configured ID prefixes +// (or returns true when no prefixes are configured). +func HasValidPrefix(name string, idPrefixes []string) bool { + if len(idPrefixes) == 0 { + return true + } + for _, prefix := range idPrefixes { + if strings.HasPrefix(name, prefix) { + return true + } + } + + return false +} + // Validate checks the given data against the OSV JSON schema. func Validate(data []byte) error { schemaLoader := gojsonschema.NewBytesLoader(schemaBytes) diff --git a/go/internal/osvutil/schema/schema_test.go b/go/internal/osvutil/schema/schema_test.go index c2d8e7956ef..eb7ad4191cc 100644 --- a/go/internal/osvutil/schema/schema_test.go +++ b/go/internal/osvutil/schema/schema_test.go @@ -15,6 +15,7 @@ package schema import ( + "strings" "testing" "k8s.io/apimachinery/pkg/util/yaml" @@ -144,3 +145,43 @@ func TestSanitizeJSON(t *testing.T) { }) } } + +func TestIsValidID(t *testing.T) { + tests := []struct { + name string + id string + want bool + }{ + {name: "standard OSV ID", id: "OSV-2026-1234", want: true}, + {name: "ID with colon underscore dot", id: "openSUSE-SU-2024:0123-1_a.b", want: true}, + {name: "max length ID", id: "OSV-" + strings.Repeat("a", MaxIDLength-4), want: true}, + {name: "exceeds max length", id: "OSV-" + strings.Repeat("a", MaxIDLength-3), want: false}, + {name: "empty ID", id: "", want: false}, + {name: "single dot", id: ".", want: false}, + {name: "double dot", id: "..", want: false}, + {name: "forward slash traversal", id: "OSV-../../etc/passwd", want: false}, + {name: "backslash traversal", id: `OSV-..\..\etc\passwd`, want: false}, + {name: "space in ID", id: "SUSE-SU-403 Forbidden", want: false}, + {name: "query injection", id: "PYSEC-2026-1?foo=bar", want: false}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := IsValidID(tt.id); got != tt.want { + t.Errorf("IsValidID(%q) = %v, want %v", tt.id, got, tt.want) + } + }) + } +} + +func TestHasValidPrefix(t *testing.T) { + if !HasValidPrefix("ANY-1", nil) { + t.Errorf("HasValidPrefix with empty prefixes = false, want true") + } + if !HasValidPrefix("RHSA-2026:0001", []string{"RHBA-", "RHSA-"}) { + t.Errorf("HasValidPrefix matching prefix = false, want true") + } + if HasValidPrefix("GHSA-xxxx-yyyy-zzzz", []string{"PYSEC-"}) { + t.Errorf("HasValidPrefix mismatched prefix = true, want false") + } +} diff --git a/go/internal/recoverer/recoverer.go b/go/internal/recoverer/recoverer.go index bad7e088c6c..17df794dc37 100644 --- a/go/internal/recoverer/recoverer.go +++ b/go/internal/recoverer/recoverer.go @@ -234,6 +234,14 @@ func (r *Recoverer) HandleGCSMissing(ctx context.Context, m *pubsub.Message) err return err } + if downloaded.ID != vulnID { + logger.ErrorContext(ctx, "gcs_missing: recovered vulnerability ID does not match requested ID", + slog.String("expected_id", vulnID), + slog.String("actual_id", downloaded.ID), + slog.String("source_id", vuln.SourceID)) + + return nil + } msg := taskmsg.NewUpdateMessage(ctx, taskmsg.UpdateParams{ Source: source, @@ -257,6 +265,7 @@ func (r *Recoverer) HandleGCSMissing(ctx context.Context, m *pubsub.Message) err // DownloadedVulnData holds the parsed JSON and source provenance of a recovered vulnerability. type DownloadedVulnData struct { + ID string JSON []byte OriginalSHA256 string GitCommit string @@ -357,12 +366,13 @@ func (r *Recoverer) DownloadVulnData(ctx context.Context, source, vulnPath strin sum := sha256.Sum256(rawData) originalSHA256 := hex.EncodeToString(sum[:]) - jsonData, err := parseVulnerabilityJSON(rawData, sourceRepo.Extension, vulnPath, sourceRepo.KeyPath) + jsonData, parsedID, err := parseVulnerabilityJSON(rawData, sourceRepo.Extension, vulnPath, sourceRepo.KeyPath) if err != nil { return nil, fmt.Errorf("failed to parse vulnerability data for %s:%s: %w", source, vulnPath, err) } return &DownloadedVulnData{ + ID: parsedID, JSON: jsonData, OriginalSHA256: originalSHA256, GitCommit: gitCommit, @@ -370,7 +380,7 @@ func (r *Recoverer) DownloadVulnData(ctx context.Context, source, vulnPath strin }, nil } -func parseVulnerabilityJSON(raw []byte, extension, vulnPath, keyPath string) ([]byte, error) { +func parseVulnerabilityJSON(raw []byte, extension, vulnPath, keyPath string) ([]byte, string, error) { data := bytes.ToValidUTF8(raw, []byte("\uFFFD")) if bytes.IndexByte(data, 0) >= 0 { data = bytes.ReplaceAll(data, []byte{0}, []byte("\uFFFD")) @@ -379,7 +389,7 @@ func parseVulnerabilityJSON(raw []byte, extension, vulnPath, keyPath string) ([] if ext == ".yaml" || ext == ".yml" || strings.HasSuffix(strings.ToLower(vulnPath), ".yaml") || strings.HasSuffix(strings.ToLower(vulnPath), ".yml") { jsonBytes, err := yaml.ToJSON(data) if err != nil { - return nil, fmt.Errorf("failed to convert YAML to JSON: %w", err) + return nil, "", fmt.Errorf("failed to convert YAML to JSON: %w", err) } data = jsonBytes } @@ -387,7 +397,7 @@ func parseVulnerabilityJSON(raw []byte, extension, vulnPath, keyPath string) ([] if keyPath != "" { res := gjson.GetBytes(data, keyPath) if !res.Exists() { - return nil, fmt.Errorf("key path %q not found in data", keyPath) + return nil, "", fmt.Errorf("key path %q not found in data", keyPath) } data = []byte(res.Raw) } @@ -396,10 +406,10 @@ func parseVulnerabilityJSON(raw []byte, extension, vulnPath, keyPath string) ([] var vulnProto osvschema.Vulnerability unmarshalOptions := protojson.UnmarshalOptions{DiscardUnknown: true} if err := unmarshalOptions.Unmarshal(data, &vulnProto); err != nil { - return nil, fmt.Errorf("failed to unmarshal OSV proto: %w", err) + return nil, "", fmt.Errorf("failed to unmarshal OSV proto: %w", err) } - return data, nil + return data, vulnProto.GetId(), nil } // HandleGCSGenMismatch handles a generation mismatch when attempting to update a part of a record. diff --git a/go/internal/recoverer/recoverer_test.go b/go/internal/recoverer/recoverer_test.go index 0eabd58e9a6..f1a32a106fc 100644 --- a/go/internal/recoverer/recoverer_test.go +++ b/go/internal/recoverer/recoverer_test.go @@ -316,6 +316,18 @@ summary: "Git test summary" if pubVuln.GetSummary() != "Git test summary" { t.Errorf("Expected summary 'Git test summary', got %s", pubVuln.GetSummary()) } + + // Mismatched ID at source path is ignored without publishing. + publisherMock.Messages = nil + gitterMock.fileContentFunc = func(_ context.Context, _ *gitterpb.FileContentRequest) (*gitterpb.FileContentResponse, error) { + return &gitterpb.FileContentResponse{Content: []byte("id: OTHER-ID\nmodified: \"2025-01-01T00:00:00Z\"\n")}, nil + } + if err := rec.HandleGCSMissing(ctx, msg); err != nil { + t.Fatalf("HandleGCSMissing on ID mismatch returned error: %v", err) + } + if len(publisherMock.Messages) != 0 { + t.Errorf("Expected 0 published messages on ID mismatch, got %d", len(publisherMock.Messages)) + } } func TestHandleGCSMissing_Bucket(t *testing.T) { diff --git a/go/internal/worker/engine.go b/go/internal/worker/engine.go index c061ea86dc0..762948af64b 100644 --- a/go/internal/worker/engine.go +++ b/go/internal/worker/engine.go @@ -15,6 +15,7 @@ import ( "github.com/google/osv.dev/go/internal/gitter" "github.com/google/osv.dev/go/internal/metrics" "github.com/google/osv.dev/go/internal/models" + "github.com/google/osv.dev/go/internal/osvutil/schema" "github.com/google/osv.dev/go/internal/worker/pipeline" "github.com/google/osv.dev/go/logger" "github.com/google/osv.dev/go/osv/ecosystem" @@ -70,7 +71,17 @@ func (e *Engine) handleUpdate(ctx context.Context, task Task) error { } if task.Vuln == nil { metrics.RecordWorkerFailedTask(metrics.WorkerErrorParse, false) - return errors.New("vuln not provided") + return fmt.Errorf("%w: vuln not provided", models.ErrInvalidArgument) + } + vulnID := task.Vuln.GetId() + if !schema.IsValidID(vulnID) { + metrics.RecordWorkerFailedTask(metrics.WorkerErrorParse, false) + return fmt.Errorf("%w: invalid vulnerability ID %q", models.ErrInvalidArgument, vulnID) + } + if !schema.HasValidPrefix(vulnID, params.SourceRepo.IDPrefixes) { + metrics.RecordWorkerFailedTask(metrics.WorkerErrorParse, false) + return fmt.Errorf("%w: vulnerability ID %q does not match allowed prefixes %v for source %q", + models.ErrInvalidArgument, vulnID, params.SourceRepo.IDPrefixes, task.SourceID) } // Get the current state of the vuln to check against @@ -137,7 +148,9 @@ func (e *Engine) handleUpdate(ctx context.Context, task Task) error { Enriched: enriched, AffectedCommits: commits, }); err != nil { - metrics.RecordWorkerFailedTask(metrics.WorkerErrorWrite, true) + retryable := !errors.Is(err, models.ErrSourceMismatch) && !errors.Is(err, models.ErrInvalidArgument) + metrics.RecordWorkerFailedTask(metrics.WorkerErrorWrite, retryable) + return err } @@ -210,10 +223,12 @@ func (e *Engine) handleDelete(ctx context.Context, task Task) error { return err } - // Safety Check: Does the record in the DB still belong to this path? - if ref.Path != task.PathInSource { - logger.WarnContext(ctx, "Skipping deletion: record moved", + // Safety Check: Does the record in the DB still belong to this source and path? + if ref.Source != task.SourceID || ref.Path != task.PathInSource { + logger.WarnContext(ctx, "Skipping deletion: record source or path mismatch", slog.String("id", id), + slog.String("current_source", ref.Source), + slog.String("requested_source", task.SourceID), slog.String("current_path", ref.Path), slog.String("requested_path", task.PathInSource)) @@ -241,7 +256,9 @@ func (e *Engine) handleDelete(ctx context.Context, task Task) error { // When deleting, we clear the commit index AffectedCommits: models.AffectedCommitsResult{Skip: false, Commits: nil}, }); err != nil { - metrics.RecordWorkerFailedTask(metrics.WorkerErrorDelete, true) + retryable := !errors.Is(err, models.ErrSourceMismatch) && !errors.Is(err, models.ErrInvalidArgument) + metrics.RecordWorkerFailedTask(metrics.WorkerErrorDelete, retryable) + return err } diff --git a/go/internal/worker/engine_test.go b/go/internal/worker/engine_test.go index 9846eda013e..e53733762b2 100644 --- a/go/internal/worker/engine_test.go +++ b/go/internal/worker/engine_test.go @@ -2,6 +2,7 @@ package worker import ( "context" + "errors" "net/http" "net/http/httptest" "os" @@ -52,8 +53,9 @@ func (m mockSourceRepoStore) Get(_ context.Context, _ string) (*models.SourceRep type mockVulnerabilityStore struct { models.VulnerabilityStore - existing *osvschema.Vulnerability - written *models.WriteRequest + existing *osvschema.Vulnerability + existingRef *models.VulnSourceRef + written *models.WriteRequest } func (m *mockVulnerabilityStore) GetFull(_ context.Context, _ string) (*osvschema.Vulnerability, error) { @@ -64,6 +66,14 @@ func (m *mockVulnerabilityStore) GetFull(_ context.Context, _ string) (*osvschem return m.existing, nil } +func (m *mockVulnerabilityStore) GetWithMetadata(_ context.Context, _ string) (*osvschema.Vulnerability, *models.VulnSourceRef, error) { + if m.existing == nil { + return nil, nil, models.ErrNotFound + } + + return m.existing, m.existingRef, nil +} + func (m *mockVulnerabilityStore) Write(_ context.Context, req models.WriteRequest) error { m.written = &req return nil @@ -360,3 +370,56 @@ func TestIsSemanticallyDifferent(t *testing.T) { }) } } + +func TestHandleUpdate_RejectsInvalidIDAndPrefix(t *testing.T) { + mockVulnStore := &mockVulnerabilityStore{} + engine := &Engine{ + Stores: Stores{ + SourceRepo: mockSourceRepoStore{ + repo: &models.SourceRepository{Name: "malicious-packages", IDPrefixes: []string{"MAL-"}}, + }, + Vulnerability: mockVulnStore, + }, + } + + for _, vuln := range []*osvschema.Vulnerability{ + nil, + {Id: "MAL-../../etc/passwd"}, + {Id: "PYSEC-2026-1"}, + } { + err := engine.handleUpdate(t.Context(), Task{ + Type: TaskUpdate, + SourceID: "malicious-packages", + PathInSource: "osv/MAL-2026-1.json", + Vuln: vuln, + }) + if !errors.Is(err, models.ErrInvalidArgument) || !isNonRetryableTaskError(err) { + t.Errorf("handleUpdate(%v) error = %v, want non-retryable ErrInvalidArgument", vuln, err) + } + } + if mockVulnStore.written != nil { + t.Errorf("expected no write on rejected updates, got %+v", mockVulnStore.written) + } +} + +func TestHandleDelete_RejectsCrossSource(t *testing.T) { + mockVulnStore := &mockVulnerabilityStore{ + existing: &osvschema.Vulnerability{Id: "PYSEC-2026-10"}, + existingRef: &models.VulnSourceRef{ID: "PYSEC-2026-10", Source: "python", Path: "vulns/PYSEC-2026-10.yaml"}, + } + engine := &Engine{Stores: Stores{Vulnerability: mockVulnStore}} + + if err := engine.handleDelete(t.Context(), Task{Type: TaskDelete, SourceID: "r", PathInSource: "vulns/PYSEC-2026-10.yaml"}); err != nil { + t.Fatalf("cross-source handleDelete() error: %v", err) + } + if mockVulnStore.written != nil { + t.Fatalf("expected cross-source delete to be skipped, got %+v", mockVulnStore.written) + } + + if err := engine.handleDelete(t.Context(), Task{Type: TaskDelete, SourceID: "python", PathInSource: "vulns/PYSEC-2026-10.yaml"}); err != nil { + t.Fatalf("same-source handleDelete() error: %v", err) + } + if mockVulnStore.written == nil || mockVulnStore.written.Enriched.GetWithdrawn() == nil { + t.Fatalf("expected same-source delete to withdraw record, got %+v", mockVulnStore.written) + } +} diff --git a/go/internal/worker/subscriber.go b/go/internal/worker/subscriber.go index c0872c9d128..0953ea5d9b7 100644 --- a/go/internal/worker/subscriber.go +++ b/go/internal/worker/subscriber.go @@ -3,6 +3,7 @@ package worker import ( "cmp" "context" + "errors" "fmt" "log/slog" "strconv" @@ -10,6 +11,7 @@ import ( "cloud.google.com/go/pubsub/v2" "github.com/google/osv.dev/go/internal/metrics" + "github.com/google/osv.dev/go/internal/models" "github.com/google/osv.dev/go/logger" "github.com/klauspost/compress/zstd" "github.com/ossf/osv-schema/bindings/go/osvschema" @@ -123,7 +125,11 @@ func (s *Subscriber) handleMessage(ctx context.Context, m *pubsub.Message) { if err := s.Engine.RunTask(taskCtx, task); err != nil { metrics.RecordWorkerTask(metrics.TaskStatusError, action, workPool) logger.ErrorContext(taskCtx, "Failed to process task", append(logInfo, slog.Any("error", err))...) - m.Nack() + if isNonRetryableTaskError(err) { + m.Ack() + } else { + m.Nack() + } } else { metrics.RecordWorkerTask(metrics.TaskStatusSuccess, action, workPool) if deleted { @@ -136,6 +142,10 @@ func (s *Subscriber) handleMessage(ctx context.Context, m *pubsub.Message) { } } +func isNonRetryableTaskError(err error) bool { + return errors.Is(err, models.ErrInvalidArgument) || errors.Is(err, models.ErrSourceMismatch) +} + func (s *Subscriber) parseVuln(m *pubsub.Message) (*osvschema.Vulnerability, []byte, error) { if len(m.Data) == 0 { return nil, nil, nil