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
9 changes: 8 additions & 1 deletion go/internal/database/datastore/vulnerability.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Trying to imagine a situation where we might want to intentionally do this, e.g. renaming a datasource (or consolidating e.g. the 3 almalinux ones into a single source, or if we accidentally let one datasource publish another's prefix before them).
Probably would get around this by manually editing the database.

}
}

dsVuln.SourceID = req.Source + ":" + req.Path
dsVuln.Modified = req.Enriched.GetModified().AsTime()
Expand Down
29 changes: 29 additions & 0 deletions go/internal/database/datastore/vulnerability_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
7 changes: 7 additions & 0 deletions go/internal/database/postgres/queries/vulnerability.sql
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand Down
8 changes: 8 additions & 0 deletions go/internal/database/postgres/vulnerability.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)

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.

We can probably avoid this extra SELECT, but it'll make the other SQL a bit more complicated, might not be worth it.

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,
Expand Down
15 changes: 15 additions & 0 deletions go/internal/database/postgres/vulnerability.sql.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

37 changes: 37 additions & 0 deletions go/internal/database/postgres/vulnerability_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down Expand Up @@ -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)
}
}
24 changes: 5 additions & 19 deletions go/internal/importer/helper.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
3 changes: 3 additions & 0 deletions go/internal/models/models.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
32 changes: 32 additions & 0 deletions go/internal/osvutil/schema/schema.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
_ "embed"
"encoding/json"
"fmt"
"regexp"
"strings"
"unicode/utf8"

Expand Down Expand Up @@ -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. "<id>-<page>" 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)
Expand Down
41 changes: 41 additions & 0 deletions go/internal/osvutil/schema/schema_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
package schema

import (
"strings"
"testing"

"k8s.io/apimachinery/pkg/util/yaml"
Expand Down Expand Up @@ -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")
}
}
22 changes: 16 additions & 6 deletions go/internal/recoverer/recoverer.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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
Expand Down Expand Up @@ -357,20 +366,21 @@ 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,
GCSGeneration: gcsGeneration,
}, 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"))
Expand All @@ -379,15 +389,15 @@ 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
}

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)
}
Expand All @@ -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.
Expand Down
12 changes: 12 additions & 0 deletions go/internal/recoverer/recoverer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
Loading
Loading