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
71 changes: 49 additions & 22 deletions vulnfeeds/cmd/ids/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ package main
import (
"crypto/rand"
"encoding/hex"
"encoding/json"
"flag"
"fmt"
"io"
Expand All @@ -17,9 +16,10 @@ import (
"strings"
"time"

"github.com/google/osv-scanner/pkg/models"
"github.com/goccy/go-yaml"
"github.com/google/osv/vulnfeeds/utility/logger"
"gopkg.in/yaml.v2"
"github.com/ossf/osv-schema/bindings/go/osvschema"
"google.golang.org/protobuf/encoding/protojson"
)

const (
Expand Down Expand Up @@ -112,16 +112,16 @@ func assignID(prefix, path string, format fileFormat, yearCounters map[int]int,
// If the vulnerability has a published date, use the year from that.
// Otherwise, just default to the current year.
year := defaultYear
if !vuln.Published.IsZero() {
year = vuln.Published.Year()
if vuln.GetPublished() != nil {
year = vuln.GetPublished().AsTime().Year()
}

// Allocate a new ID and write the new file.
id := yearCounters[year] + 1
yearCounters[year] = id

vuln.ID = fmt.Sprintf("%s-%d-%d", prefix, year, id)
newPath := filepath.Join(filepath.Dir(path), vuln.ID+formatToExtension[format])
vuln.Id = fmt.Sprintf("%s-%d-%d", prefix, year, id)
newPath := filepath.Join(filepath.Dir(path), vuln.GetId()+formatToExtension[format])

writef, err := os.Create(newPath)
if err != nil {
Expand Down Expand Up @@ -193,37 +193,64 @@ func assignIDs(prefix, dir string, format fileFormat) error {
return os.WriteFile(filepath.Join(dir, conflictFile), []byte(hex.EncodeToString(b)), 0600)
}

func readVulnWithFormat(r io.Reader, format fileFormat) (*models.Vulnerability, error) {
var v models.Vulnerability
func readVulnWithFormat(r io.Reader, format fileFormat) (*osvschema.Vulnerability, error) {
data, err := io.ReadAll(r)
if err != nil {
return nil, err
}

var jsonBytes []byte
switch format {
case fileFormatJSON:
dec := json.NewDecoder(r)
if err := dec.Decode(&v); err != nil {
return nil, err
}
jsonBytes = data
case fileFormatYAML:
dec := yaml.NewDecoder(r)
if err := dec.Decode(&v); err != nil {
jsonBytes, err = yaml.YAMLToJSON(data)
if err != nil {
return nil, err
}
default:
return nil, fmt.Errorf("unknown file format: %v", format)
}

var v osvschema.Vulnerability
if err := protojson.Unmarshal(jsonBytes, &v); err != nil {
return nil, err
}

return &v, nil
Comment thread
cuixq marked this conversation as resolved.
Resolved
}

func writeVulnWithFormat(v *models.Vulnerability, w io.Writer, format fileFormat) error {
func writeVulnWithFormat(v *osvschema.Vulnerability, w io.Writer, format fileFormat) error {
marshaler := protojson.MarshalOptions{
Multiline: true,
Indent: " ",
}

jsonBytes, err := marshaler.Marshal(v)
if err != nil {
return err
}

var data []byte
switch format {
case fileFormatJSON:
enc := json.NewEncoder(w)
enc.SetIndent("", " ")

return enc.Encode(v)
data = jsonBytes
case fileFormatYAML:
enc := yaml.NewEncoder(w)
return enc.Encode(v)
data, err = yaml.JSONToYAML(jsonBytes)
if err != nil {
return err
}
default:
return fmt.Errorf("unknown file format: %v", format)
}
Comment thread
cuixq marked this conversation as resolved.
Resolved

// Ensure the output has a trailing newline to match the behavior of
// json.Encoder, which was previously used.
if len(data) > 0 && data[len(data)-1] != '\n' {
data = append(data, '\n')
}

_, err = w.Write(data)

return err
}
103 changes: 103 additions & 0 deletions vulnfeeds/cmd/ids/main_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
package main

import (
"bytes"
"os"
"path/filepath"
"testing"
)

func TestAssignIDs(t *testing.T) {
tests := []struct {
name string
prefix string
format fileFormat
templateName string
existingName string
expectedID string
}{
{
name: "OSV YAML",
prefix: "OSV",
format: fileFormatYAML,
templateName: "OSV-0000-abc.yaml",
existingName: "OSV-2026-10.yaml",
expectedID: "OSV-2026-11",
},
{
name: "TEST JSON",
prefix: "TEST",
format: fileFormatJSON,
templateName: "TEST-0000-def.json",
existingName: "TEST-2026-20.json",
expectedID: "TEST-2026-21",
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tmpDir := t.TempDir()

// 1. Copy existing assigned vulnerability from testdata to set counter.
existingPath := filepath.Join("testdata", tt.existingName)
existingData, err := os.ReadFile(existingPath)
if err != nil {
t.Fatalf("failed to read existing ID: %v", err)
}
err = os.WriteFile(filepath.Join(tmpDir, tt.existingName), existingData, 0600)
if err != nil {
t.Fatalf("failed to copy existing ID: %v", err)
}

// 2. Setup unassigned vulnerability using template.
templatePath := filepath.Join("testdata", tt.templateName)
templateData, err := os.ReadFile(templatePath)
if err != nil {
t.Fatalf("failed to read template %s: %v", templatePath, err)
}
destPath := filepath.Join(tmpDir, tt.templateName)
if err := os.WriteFile(destPath, templateData, 0600); err != nil {
t.Fatalf("failed to setup unassigned vuln: %v", err)
}

// 3. Run assignIDs.
if err := assignIDs(tt.prefix, tmpDir, tt.format); err != nil {
t.Fatalf("assignIDs failed: %v", err)
}

// 4. Verify results.
ext := formatToExtension[tt.format]
expectedFilename := tt.expectedID + ext
gotPath := filepath.Join(tmpDir, expectedFilename)
if _, err := os.Stat(gotPath); os.IsNotExist(err) {
t.Errorf("Expected %s to exist", gotPath)
return
}

if _, err := os.Stat(destPath); !os.IsNotExist(err) {
t.Errorf("Expected old file %s to be removed", tt.templateName)
}

gotData, err := os.ReadFile(gotPath)
if err != nil {
t.Fatalf("failed to read assigned vuln %s: %v", gotPath, err)
}

wantData, err := os.ReadFile(filepath.Join("testdata", expectedFilename))
if err != nil {
t.Fatalf("failed to read expected vuln: %v", err)
}

// Trim space to be robust against minor formatting differences,
// for example trailing newlines.
if !bytes.Equal(bytes.TrimSpace(gotData), bytes.TrimSpace(wantData)) {
t.Errorf("Data fidelity mismatch for %s:\nGot:\n%s\nWant:\n%s", tt.expectedID, string(gotData), string(wantData))
}

// Verify .id-allocator was created.
if _, err := os.Stat(filepath.Join(tmpDir, ".id-allocator")); os.IsNotExist(err) {
t.Errorf("Expected .id-allocator to exist")
}
})
}
}
31 changes: 31 additions & 0 deletions vulnfeeds/cmd/ids/testdata/OSV-0000-abc.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
id:
published: "2026-01-02T00:00:00Z"
modified: "2026-01-02T00:00:00Z"
summary: A vulnerability
details: |
Blah blah blah
Blah
affected:
- package:
name: blah.com/package
ecosystem: Go
ranges:
- type: GIT
repo: https://osv-test/repo/url
events:
- introduced: eefe8ec3f1f90d0e684890e810f3f21e8500a4cd
- fixed: 8d8242f545e9cec3e6d0d2e3f5bde8be1c659735
versions:
- branch-v0.1.1
references:
- type: WEB
url: https://ref.com/ref
database_specific:
specific: 1337
severity:
- type: CVSS_V3
score: CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:L/A:L
credits:
- name: Foo bar
contact:
- mailto:foo@bar.com
2 changes: 2 additions & 0 deletions vulnfeeds/cmd/ids/testdata/OSV-2026-10.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
id: OSV-2026-10
modified: '2026-01-01T00:00:00Z'
31 changes: 31 additions & 0 deletions vulnfeeds/cmd/ids/testdata/OSV-2026-11.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
id: OSV-2026-11
published: "2026-01-02T00:00:00Z"
modified: "2026-01-02T00:00:00Z"
summary: A vulnerability
details: |
Blah blah blah
Blah
affected:
- package:
name: blah.com/package
ecosystem: Go
ranges:
- type: GIT
repo: https://osv-test/repo/url
events:
- introduced: eefe8ec3f1f90d0e684890e810f3f21e8500a4cd
- fixed: 8d8242f545e9cec3e6d0d2e3f5bde8be1c659735
versions:
- branch-v0.1.1
references:
- type: WEB
url: https://ref.com/ref
database_specific:
specific: 1337
severity:
- type: CVSS_V3
score: CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:L/A:L
credits:
- name: Foo bar
contact:
- mailto:foo@bar.com
55 changes: 55 additions & 0 deletions vulnfeeds/cmd/ids/testdata/TEST-0000-def.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
{
"id": "",
"published": "2026-01-02T00:00:00Z",
"modified": "2026-01-02T00:00:00Z",
"summary": "A vulnerability",
"details": "Blah blah blah\nBlah\n",
"affected": [
{
"package": {
"name": "blah.com/package",
"ecosystem": "Go"
},
"ranges": [
{
"type": "GIT",
"repo": "https://osv-test/repo/url",
"events": [
{
"introduced": "eefe8ec3f1f90d0e684890e810f3f21e8500a4cd"
},
{
"fixed": "8d8242f545e9cec3e6d0d2e3f5bde8be1c659735"
}
]
}
],
"versions": [
"branch-v0.1.1"
]
}
],
"references": [
{
"type": "WEB",
"url": "https://ref.com/ref"
}
],
"database_specific": {
"specific": 1337
},
"severity": [
{
"type": "CVSS_V3",
"score": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:L/A:L"
}
],
"credits": [
{
"name": "Foo bar",
"contact": [
"mailto:foo@bar.com"
]
}
]
}
4 changes: 4 additions & 0 deletions vulnfeeds/cmd/ids/testdata/TEST-2026-20.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"id": "TEST-2026-20",
"modified": "2026-01-01T00:00:00Z"
}
Loading
Loading