repo_id
stringclasses 927
values | file_path
stringlengths 99
214
| content
stringlengths 2
4.15M
|
|---|---|---|
symbols
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/internal/symbols/patched_functions_test.go
|
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package symbols
import (
"go/ast"
"go/parser"
"go/token"
"path/filepath"
"sort"
"testing"
"github.com/google/go-cmp/cmp"
)
func TestPatchedSymbols(t *testing.T) {
toMap := func(syms []symKey) map[symKey]bool {
m := make(map[symKey]bool)
for _, s := range syms {
m[s] = true
}
return m
}
for _, tc := range []struct {
module string
oldRepoRoot string
fixedRepoRoot string
want map[symKey]bool
}{
{"golang.org/module", "testdata/module", "testdata/fixed-module", map[symKey]bool{
{pkg: "golang.org/module", symbol: "Foo"}: true,
{pkg: "golang.org/module/internal", symbol: "Bar"}: true,
}},
{"golang.org/nestedmodule", "testdata/module", "testdata/fixed-module", map[symKey]bool{
{pkg: "golang.org/nestedmodule", file: "main_linux.go", symbol: "main"}: true,
}},
} {
oldSyms, err := moduleSymbols(tc.oldRepoRoot, tc.module)
if err != nil {
t.Error(err)
}
newSyms, err := moduleSymbols(tc.fixedRepoRoot, tc.module)
if err != nil {
t.Error(err)
}
patched, err := patchedSymbols(oldSyms, newSyms)
if err != nil {
t.Fatal(err)
}
got := toMap(patched)
if diff := cmp.Diff(got, tc.want); diff != "" {
t.Errorf("(-got, want+):\n%s", diff)
}
}
}
func TestModuleSymbols(t *testing.T) {
symKeys := func(syms map[symKey]*ast.FuncDecl) map[symKey]bool {
m := make(map[symKey]bool)
for sym := range syms {
m[sym] = true
}
return m
}
for _, tc := range []struct {
module string
repoRoot string
want map[symKey]bool
}{
{"golang.org/module", "testdata/module", map[symKey]bool{
{"golang.org/module", "", "Foo"}: true,
{"golang.org/module", "", "main"}: true,
{"golang.org/module/internal", "", "Bar"}: true,
}},
{"golang.org/nestedmodule", "testdata/module/submodule", map[symKey]bool{
{"golang.org/nestedmodule", "main_linux.go", "main"}: true,
{"golang.org/nestedmodule", "main_windows.go", "main"}: true,
}},
} {
syms, err := moduleSymbols(tc.repoRoot, tc.module)
if err != nil {
t.Error(err)
}
got := symKeys(syms)
if diff := cmp.Diff(got, tc.want); diff != "" {
t.Errorf("(-got, want+):\n%s", diff)
}
}
}
func TestModuleRootAndFiles(t *testing.T) {
dirName := func(path string) string {
if path == "" {
return ""
}
rel, err := filepath.Rel("testdata", path)
if err != nil {
t.Error(err)
}
return filepath.ToSlash(rel)
}
fileNames := func(filePaths []string) []string {
var fs []string
for _, p := range filePaths {
fs = append(fs, filepath.Base(p))
}
sort.Strings(fs)
return fs
}
for _, tc := range []struct {
module string
wantRoot string
wantFiles []string
}{
{"golang.org/module", "module", []string{"bar.go", "foo.go", "main.go"}},
{"golang.org/nestedmodule", "module/submodule", []string{"main_linux.go", "main_windows.go"}},
{"golang.org/testdata", "", nil},
{"golang.org/nonexistentmodule", "", nil},
} {
modRoot, fPaths, err := moduleRootAndFiles("testdata/module", tc.module)
if err != nil {
t.Error(err)
}
gotFiles := fileNames(fPaths)
if diff := cmp.Diff(tc.wantFiles, gotFiles); diff != "" {
t.Errorf("got %s; want %s", gotFiles, tc.wantFiles)
}
gotRoot := dirName(modRoot)
if gotRoot != tc.wantRoot {
t.Errorf("module root: got %s; want %s", gotRoot, tc.wantRoot)
}
}
}
func TestModuleRoots(t *testing.T) {
toSlash := func(modRoots map[string]string) map[string]string {
m := make(map[string]string)
for mod, root := range modRoots {
m[mod] = filepath.ToSlash(root)
}
return m
}
want := map[string]string{
"golang.org/module": "testdata/module",
"golang.org/nestedmodule": "testdata/module/submodule",
}
roots, err := moduleRoots("testdata/module")
if err != nil {
t.Fatal(err)
}
got := toSlash(roots)
if diff := cmp.Diff(want, got); diff != "" {
t.Errorf("(-got, want+):\n%s", diff)
}
}
func TestPackageImportPath(t *testing.T) {
const module = "golang.org/module"
for _, tc := range []struct {
root string
path string
want string
}{
// relative paths
{"modroot", "modroot/main.go", "golang.org/module"},
{"modroot", "modroot/", "golang.org/module"},
{"./modroot", "./modroot/main.go", "golang.org/module"},
{"modroot", "modroot/internal/internal.go", "golang.org/module/internal"},
{"modroot", "modroot/internal/", "golang.org/module/internal"},
{"modroot", "modroot/exp/foo/foo.go", "golang.org/module/exp/foo"},
// absolute paths
{"/modroot", "/modroot/exp/foo/foo.go", "golang.org/module/exp/foo"},
{"/", "/internal/internal.go", "golang.org/module/internal"},
{"/", "/internal/", "golang.org/module/internal"},
} {
got := packageImportPath(module, tc.root, tc.path)
if got != tc.want {
t.Errorf("got %s; want %s", got, tc.want)
}
}
}
func TestSymbolName(t *testing.T) {
src := `
package p
func Foo() {}
type A struct {}
func (a A) Do() {}
type B struct {}
func (b *B) Do() {}
type C[T any] struct {
t T
}
func (c C[T]) Do() {}
func (c *C[T]) Bar() {}
func Go[X any]() {}
`
fset := token.NewFileSet() // positions are relative to fset
f, err := parser.ParseFile(fset, "src.go", src, 0)
if err != nil {
t.Error(err)
}
var got []string
for _, decl := range f.Decls {
if fn, ok := decl.(*ast.FuncDecl); ok {
got = append(got, astSymbolName(fn))
}
}
sort.Strings(got)
want := []string{"A.Do", "B.Do", "C.Bar", "C.Do", "Foo", "Go"}
if diff := cmp.Diff(want, got); diff != "" {
t.Errorf("(-got, want+):\n%s", diff)
}
}
|
module
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/internal/symbols/testdata/module/foo_test.go
|
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import "testing"
func TestFoo(t *testing.T) {
if err := Foo(); err != nil {
t.Error(err)
}
}
|
module
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/internal/symbols/testdata/module/go.mod
|
module golang.org/module
go 1.22
|
module
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/internal/symbols/testdata/module/foo.go
|
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import "golang.org/module/internal"
func Foo() error {
internal.Bar()
return nil
}
|
module
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/internal/symbols/testdata/module/main.go
|
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
func main() {
Foo()
}
|
submodule
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/internal/symbols/testdata/module/submodule/main_linux.go
|
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build linux
package main
func main() {}
|
submodule
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/internal/symbols/testdata/module/submodule/go.mod
|
module golang.org/nestedmodule
go 1.22
|
submodule
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/internal/symbols/testdata/module/submodule/main_windows.go
|
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build windows
package main
func main() {}
|
testdata
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/internal/symbols/testdata/module/submodule/testdata/go.mod
|
module golang.org/testdata
go 1.22
|
testdata
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/internal/symbols/testdata/module/submodule/testdata/main.go
|
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
func main() {}
|
internal
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/internal/symbols/testdata/module/internal/bar.go
|
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package internal
func Bar() {}
|
fixed-module
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/internal/symbols/testdata/fixed-module/foo_test.go
|
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import "testing"
func TestFoo(t *testing.T) {
if err := Foo(); err != nil {
t.Error(err)
}
}
|
fixed-module
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/internal/symbols/testdata/fixed-module/go.mod
|
module golang.org/module
go 1.22
|
fixed-module
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/internal/symbols/testdata/fixed-module/foo.go
|
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
func Foo() error {
return nil
}
|
fixed-module
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/internal/symbols/testdata/fixed-module/main.go
|
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
func main() {
Foo()
}
|
submodule
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/internal/symbols/testdata/fixed-module/submodule/main_linux.go
|
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build linux
package main
func main() {
bar()
}
func bar() {}
|
submodule
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/internal/symbols/testdata/fixed-module/submodule/go.mod
|
module golang.org/nestedmodule
go 1.22
|
submodule
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/internal/symbols/testdata/fixed-module/submodule/main_windows.go
|
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build windows
package main
func main() {}
|
testdata
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/internal/symbols/testdata/fixed-module/submodule/testdata/go.mod
|
module golang.org/testdata
go 1.22
|
testdata
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/internal/symbols/testdata/fixed-module/submodule/testdata/main.go
|
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import "fmt"
func main() {
fmt.Println("hello world")
}
|
database
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/internal/database/json.go
|
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package database
import (
"encoding/json"
"os"
"golang.org/x/vulndb/internal/derrors"
)
func WriteJSON(filename string, value any, indent bool) (err error) {
defer derrors.Wrap(&err, "writeJSON(%s)", filename)
j, err := jsonMarshal(value, indent)
if err != nil {
return err
}
return os.WriteFile(filename, j, 0644)
}
func jsonMarshal(v any, indent bool) ([]byte, error) {
if indent {
return json.MarshalIndent(v, "", " ")
}
return json.Marshal(v)
}
|
database
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/internal/database/endpoints.go
|
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package database
var (
indexDir = "index"
idDir = "ID"
dbEndpoint = "db.json"
modulesEndpoint = "modules.json"
vulnsEndpoint = "vulns.json"
)
func IsIndexEndpoint(filename string) bool {
return filename == dbEndpoint ||
filename == modulesEndpoint ||
filename == vulnsEndpoint
}
|
database
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/internal/database/write.go
|
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package database
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
)
func (db *Database) Write(dir string) error {
gzip := true
if err := db.writeIndex(filepath.Join(dir, indexDir), gzip); err != nil {
return err
}
return db.writeEntries(filepath.Join(dir, idDir), gzip)
}
func (db *Database) writeIndex(dir string, gzip bool) error {
if err := os.MkdirAll(dir, 0755); err != nil {
return fmt.Errorf("failed to create directory %q: %s", dir, err)
}
if err := write(filepath.Join(dir, dbEndpoint), db.DB, gzip); err != nil {
return err
}
if err := write(filepath.Join(dir, modulesEndpoint), db.Modules, gzip); err != nil {
return err
}
return write(filepath.Join(dir, vulnsEndpoint), db.Vulns, gzip)
}
func (db *Database) writeEntries(dir string, gzip bool) error {
if err := os.MkdirAll(dir, 0755); err != nil {
return fmt.Errorf("failed to create directory %q: %s", dir, err)
}
for _, entry := range db.Entries {
if err := write(filepath.Join(dir, entry.ID+".json"), entry, gzip); err != nil {
return err
}
}
return nil
}
func write(filename string, v any, gzip bool) error {
b, err := json.Marshal(v)
if err != nil {
return err
}
// Write standard.
if err := os.WriteFile(filename, b, 0644); err != nil {
return err
}
if gzip {
return writeGzipped(filename+".gz", b)
}
return nil
}
|
database
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/internal/database/write_test.go
|
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package database
import (
"fmt"
"testing"
"golang.org/x/mod/sumdb/dirhash"
)
func TestWrite(t *testing.T) {
want := t.TempDir()
gzip := true
if err := txtarToDir(validTxtar, want, gzip); err != nil {
t.Fatal(err)
}
got := t.TempDir()
if err := valid.Write(got); err != nil {
t.Fatal(err)
}
if err := cmpDirHashes(want, got); err != nil {
t.Error(err)
}
}
func TestLoadWrite(t *testing.T) {
// Check that Load and Write are inverses.
want := t.TempDir()
gzip := true
if err := txtarToDir(validTxtar, want, gzip); err != nil {
t.Fatal(err)
}
loaded, err := Load(want)
if err != nil {
t.Fatal(err)
}
got := t.TempDir()
if err := loaded.Write(got); err != nil {
t.Fatal(err)
}
if err := cmpDirHashes(want, got); err != nil {
t.Error(err)
}
}
// cmpDirHashes compares the contents of two directories by comparing
// their hashes.
func cmpDirHashes(d1, d2 string) error {
h1, err := dirhash.HashDir(d1, "", dirhash.DefaultHash)
if err != nil {
return fmt.Errorf("could not hash dir %q: %v", d1, err)
}
h2, err := dirhash.HashDir(d2, "", dirhash.DefaultHash)
if err != nil {
return fmt.Errorf("could not hash dir %q: %v", d2, err)
}
if h1 != h2 {
return fmt.Errorf("hashes do not match:\n%s: %s\n%s: %s", d1, h1, d2, h2)
}
return nil
}
|
database
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/internal/database/all_test.go
|
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package database
import (
"context"
"flag"
"os"
"testing"
"github.com/google/go-cmp/cmp"
"golang.org/x/vulndb/internal/gitrepo"
)
var integration = flag.Bool("integration", false, "test with respect to current contents of vulndb")
func TestNewWriteLoadValidate(t *testing.T) {
newDB, err := New(testOSV1, testOSV2, testOSV3)
if err != nil {
t.Fatal(err)
}
tmpDir := t.TempDir()
if err = newDB.Write(tmpDir); err != nil {
t.Fatal(err)
}
loaded, err := Load(tmpDir)
if err != nil {
t.Fatal(err)
}
if diff := cmp.Diff(newDB, loaded); diff != "" {
t.Errorf("new/write/load mismatch (-new, +loaded):\n%s", diff)
}
if err := ValidateDeploy(tmpDir, tmpDir); err != nil {
t.Error(err)
}
}
func TestFromRepoWriteLoadValidate(t *testing.T) {
ctx := context.Background()
testRepo, err := gitrepo.ReadTxtarRepo(vulndbTxtar, jan2002.Time)
if err != nil {
t.Fatal(err)
}
fromRepo, err := FromRepo(ctx, testRepo)
if err != nil {
t.Fatal(err)
}
tmpDir := t.TempDir()
if err = fromRepo.Write(tmpDir); err != nil {
t.Fatal(err)
}
loaded, err := Load(tmpDir)
if err != nil {
t.Fatal(err)
}
if diff := cmp.Diff(fromRepo, loaded); diff != "" {
t.Errorf("fromRepo/write/load mismatch (-fromRepo, +loaded):\n%s", diff)
}
if err := ValidateDeploy(tmpDir, tmpDir); err != nil {
t.Error(err)
}
}
func TestIntegration(t *testing.T) {
if !*integration {
t.Skip("Skipping integration tests, use flag -integration to run")
}
moveToVulnDBRoot(t)
ctx := context.Background()
repo, err := gitrepo.Open(ctx, ".")
if err != nil {
t.Fatal(err)
}
dir := t.TempDir()
created, err := FromRepo(ctx, repo)
if err != nil {
t.Fatal(err)
}
if err := created.Write(dir); err != nil {
t.Fatal(err)
}
loaded, err := Load(dir)
if err != nil {
t.Fatal(err)
}
if diff := cmp.Diff(created, loaded); diff != "" {
t.Errorf("unexpected diff: (-created,+loaded):\n%s", diff)
}
if err := ValidateDeploy(dir, dir); err != nil {
t.Error(err)
}
}
func moveToVulnDBRoot(t *testing.T) {
// Store current working directory and move into vulndb/ folder.
wd, err := os.Getwd()
if err != nil {
t.Fatal(err)
}
if err := os.Chdir("../.."); err != nil {
t.Fatal(err)
}
// Restore state from before test.
t.Cleanup(func() {
if err = os.Chdir(wd); err != nil {
t.Log(err)
}
})
}
|
database
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/internal/database/database.go
|
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package database provides functionality for reading, writing, and
// validating Go vulnerability databases according to the v1 schema.
package database
import (
"encoding/json"
"fmt"
"golang.org/x/exp/maps"
"golang.org/x/exp/slices"
"golang.org/x/vulndb/internal/osv"
)
// Database represents a Go Vulnerability Database in the v1 schema.
type Database struct {
// DB represents the index/db.json endpoint.
DB DBMeta
// Modules represents the index/modules.json endpoint.
Modules ModulesIndex
// Vulns represents the index/vulns.json endpoint.
Vulns VulnsIndex
// Entries represents the ID/GO-YYYY-XXXX.json endpoints.
Entries []osv.Entry
}
// DBMeta contains metadata about the database itself.
type DBMeta struct {
// Modified is the time the database was last modified, calculated
// as the most recent time any single OSV entry was modified.
Modified osv.Time `json:"modified"`
}
// ModulesIndex is a map from module paths to module metadata.
// It marshals into and unmarshals from the format published in
// index/modules.json, which is a JSON array of objects.
type ModulesIndex map[string]*Module
func (m *ModulesIndex) UnmarshalJSON(data []byte) error {
var modules []*Module
if err := json.Unmarshal(data, &modules); err != nil {
return err
}
for _, module := range modules {
path := module.Path
if _, ok := (*m)[path]; ok {
return fmt.Errorf("module %q appears twice in modules.json", path)
}
(*m)[path] = module
}
return nil
}
func (m ModulesIndex) MarshalJSON() ([]byte, error) {
modules := maps.Values(m)
slices.SortStableFunc(modules, func(m1, m2 *Module) int {
switch {
case m1.Path < m2.Path:
return -1
case m1.Path > m2.Path:
return 1
default:
return 0
}
})
for _, module := range modules {
slices.SortStableFunc(module.Vulns, func(v1, v2 ModuleVuln) int {
switch {
case v1.ID < v2.ID:
return -1
case v1.ID > v2.ID:
return 1
default:
return 0
}
})
}
return json.Marshal(modules)
}
// Module contains metadata about a Go module that has one
// or more vulnerabilities in the database.
type Module struct {
// Path is the module path.
Path string `json:"path"`
// Vulns is a list of vulnerabilities that affect this module.
Vulns []ModuleVuln `json:"vulns"`
}
// ModuleVuln contains metadata about a vulnerability that affects
// a certain module (as used by the ModulesIndex).
type ModuleVuln struct {
// ID is a unique identifier for the vulnerability.
// The Go vulnerability database issues IDs of the form
// GO-<YEAR>-<ENTRYID>.
ID string `json:"id"`
// Modified is the time the vuln was last modified.
Modified osv.Time `json:"modified"`
// Fixed is the latest version that introduces a fix for the
// vulnerability, in SemVer 2.0.0 format, with no leading "v" prefix.
// (This is technically the earliest version V such that the
// vulnerability does not occur in any version later than V.)
//
// This field can be used to determine if a version is definitely
// not affected by a vulnerability (if the version is greater than
// or equal to the fixed version), but the full OSV entry must
// be downloaded to determine if a version less than the fixed
// version is affected.
//
// This field is optional, and should be empty if there is no
// known fixed version.
//
// Example:
// Suppose a vulnerability is present in all versions
// up to (not including) version 1.5.0, is re-introduced in version
// 2.0.0, and fixed again in version 2.4.0. The "Fixed" version
// would be 2.4.0.
// The fixed version tells us that any version greater than or equal
// to 2.4.0 is not affected, but we would need to look at the OSV
// entry to determine if any version less than 2.4.0 was affected.
Fixed string `json:"fixed,omitempty"`
}
// VulnsIndex is a map from vulnerability IDs to vulnerability metadata.
// It marshals into and unmarshals from the format published in
// index/vulns.json, which is a JSON array of objects.
type VulnsIndex map[string]*Vuln
func (v VulnsIndex) MarshalJSON() ([]byte, error) {
vulns := maps.Values(v)
slices.SortStableFunc(vulns, func(v1, v2 *Vuln) int {
switch {
case v1.ID < v2.ID:
return -1
case v1.ID > v2.ID:
return 1
default:
return 0
}
})
return json.Marshal(vulns)
}
func (v *VulnsIndex) UnmarshalJSON(data []byte) error {
var vulns []*Vuln
if err := json.Unmarshal(data, &vulns); err != nil {
return err
}
for _, vuln := range vulns {
id := vuln.ID
if _, ok := (*v)[id]; ok {
return fmt.Errorf("id %q appears twice in vulns.json", id)
}
(*v)[id] = vuln
}
return nil
}
// Vuln contains metadata about a vulnerability in the database,
// as used by the VulnsIndex.
type Vuln struct {
// ID is a unique identifier for the vulnerability.
// The Go vulnerability database issues IDs of the form
// GO-<YEAR>-<ENTRYID>.
ID string `json:"id"`
// Modified is the time the vulnerability was last modified.
Modified osv.Time `json:"modified"`
// Aliases is a list of IDs for the same vulnerability in other
// databases.
Aliases []string `json:"aliases,omitempty"`
}
|
database
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/internal/database/gzip_test.go
|
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package database
import (
"path/filepath"
"testing"
)
func TestWriteReadGzipped(t *testing.T) {
filename := filepath.Join(t.TempDir(), "test.json.gz")
want := []byte(`{"test":"Hello world!"}`)
if err := writeGzipped(filename, want); err != nil {
t.Fatal(err)
}
got, err := readGzipped(filename)
if err != nil {
t.Fatal(err)
}
if string(got) != string(want) {
t.Errorf("readGzipped: got %s, want %s", got, want)
}
}
|
database
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/internal/database/database_test.go
|
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package database
import (
"encoding/json"
"testing"
"golang.org/x/tools/txtar"
)
func TestMarshalUnmarshal(t *testing.T) {
ar, err := txtar.ParseFile(validTxtar)
if err != nil {
t.Fatal(err)
}
testMarshalUnmarshal := func(t *testing.T, filename string, v any) {
data, err := data(ar, filename)
if err != nil {
t.Fatal(err)
}
if err = json.Unmarshal(data, &v); err != nil {
t.Fatal(err)
}
marshaled, err := json.Marshal(v)
if err != nil {
t.Fatal(err)
}
if got, want := string(marshaled), string(data); got != want {
t.Errorf("json.Marshal: got \n%s\n, want \n%s", got, want)
}
}
t.Run("DBIndex", func(t *testing.T) {
var db DBMeta
testMarshalUnmarshal(t, "index/db.json", &db)
})
t.Run("ModulesIndex", func(t *testing.T) {
modules := make(ModulesIndex)
testMarshalUnmarshal(t, "index/modules.json", &modules)
})
t.Run("VulnsIndex", func(t *testing.T) {
vulns := make(VulnsIndex)
testMarshalUnmarshal(t, "index/vulns.json", &vulns)
})
}
|
database
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/internal/database/txtar_test.go
|
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package database
import (
"bytes"
"encoding/json"
"fmt"
"os"
"path/filepath"
"golang.org/x/tools/txtar"
)
// Helper functions for working with txtar files in tests.
const (
validTxtar = "testdata/db.txtar"
smallTxtar = "testdata/db-small.txtar"
invalidDBMetaTxtar = "testdata/invalid-db-meta.txtar"
invalidModulesTxtar = "testdata/invalid-modules.txtar"
invalidVulnsTxtar = "testdata/invalid-vulns.txtar"
invalidFilenameTxtar = "testdata/invalid-filename.txtar"
invalidEntriesTxtar = "testdata/invalid-entries.txtar"
vulndbTxtar = "testdata/vulndb-repo.txtar"
)
// data returns the raw JSON data contained in the pseudofile filename,
// with any whitespace removed.
//
// This a test helper function.
func data(ar *txtar.Archive, filename string) ([]byte, error) {
for _, f := range ar.Files {
if f.Name == filename {
return removeWhitespace(f.Data)
}
}
return nil, fmt.Errorf("file %s not found", filename)
}
// txtarToDir writes the contents of a txtar file into a directory dir,
// removing any whitespace from the contents.
// It assumes that all "files" in the txtar file contain json.
// If gzip is true, it adds a corresponding gzipped file for each file present.
//
// This a test helper function.
func txtarToDir(filename string, dir string, gzip bool) error {
ar, err := txtar.ParseFile(filename)
if err != nil {
return err
}
for _, f := range ar.Files {
if err := os.MkdirAll(filepath.Join(dir, filepath.Dir(f.Name)), 0755); err != nil {
return err
}
data, err := removeWhitespace(f.Data)
if err != nil {
return err
}
fname := filepath.Join(dir, f.Name)
if err := os.WriteFile(fname, data, 0644); err != nil {
return err
}
if gzip {
if err := writeGzipped(fname+".gz", data); err != nil {
return err
}
}
}
return nil
}
func removeWhitespace(data []byte) ([]byte, error) {
var b bytes.Buffer
if err := json.Compact(&b, data); err != nil {
return nil, err
}
return b.Bytes(), nil
}
|
database
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/internal/database/validate_test.go
|
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package database
import (
"strings"
"testing"
"golang.org/x/vulndb/internal/osv"
)
func TestValidate(t *testing.T) {
small, big, invalid := t.TempDir(), t.TempDir(), t.TempDir()
gzip := true
if err := txtarToDir(smallTxtar, small, gzip); err != nil {
t.Fatal(err)
}
if err := txtarToDir(validTxtar, big, gzip); err != nil {
t.Fatal(err)
}
if err := txtarToDir(invalidModulesTxtar, invalid, gzip); err != nil {
t.Fatal(err)
}
t.Run("valid", func(t *testing.T) {
// Adding more entries is OK.
if err := ValidateDeploy(big, small); err != nil {
t.Error(err)
}
})
failTests := []struct {
name string
old string
new string
}{
{
name: "deleted entry",
old: big,
new: small,
},
{
name: "invalid new db",
old: small,
new: invalid,
},
}
for _, test := range failTests {
t.Run(test.name, func(t *testing.T) {
if err := ValidateDeploy(test.new, test.old); err == nil {
t.Error("expected error, got nil")
}
})
}
}
func TestValidateInternal(t *testing.T) {
successTests := []struct {
name string
new []osv.Entry
old []osv.Entry
}{
{
name: "valid updates ok",
old: []osv.Entry{{
ID: "GO-1999-0001",
Published: jan1999,
Modified: jan1999,
}},
new: []osv.Entry{{
ID: "GO-1999-0001",
Published: jan1999,
Modified: jan2000,
}, {
ID: "GO-1999-0002",
Published: jan2000,
Modified: jan2000,
}},
},
{
name: "same db ok",
old: []osv.Entry{{
ID: "GO-1999-0001",
Published: jan1999,
Modified: jan1999,
}},
new: []osv.Entry{{
ID: "GO-1999-0001",
Published: jan1999,
Modified: jan1999,
}},
},
}
for _, test := range successTests {
t.Run(test.name, func(t *testing.T) {
new, err := New(test.new...)
if err != nil {
t.Fatal(err)
}
old, err := New(test.old...)
if err != nil {
t.Fatal(err)
}
if err := validate(new, old); err != nil {
t.Errorf("validate(): unexpected error %v", err)
}
})
}
failTests := []struct {
name string
new []osv.Entry
old []osv.Entry
wantErr string
}{
{
name: "published time changed",
old: []osv.Entry{
{
ID: "GO-1999-0001",
Published: jan1999,
Modified: jan1999,
}},
new: []osv.Entry{
{
ID: "GO-1999-0001",
Published: jan2000,
Modified: jan2000,
},
},
wantErr: "published time cannot change",
},
{
name: "deleted entry",
old: []osv.Entry{
{
ID: "GO-1999-0001",
Published: jan1999,
Modified: jan1999,
},
},
wantErr: "GO-1999-0001 is not present in new database",
},
{
name: "modified time decreased",
old: []osv.Entry{{
ID: "GO-1999-0001",
Modified: jan2000,
}},
new: []osv.Entry{{
ID: "GO-1999-0001",
Modified: jan1999,
}},
wantErr: "modified time cannot decrease",
},
}
for _, test := range failTests {
t.Run(test.name, func(t *testing.T) {
new, err := New(test.new...)
if err != nil {
t.Fatal(err)
}
old, err := New(test.old...)
if err != nil {
t.Fatal(err)
}
if err := validate(new, old); err == nil || !strings.Contains(err.Error(), test.wantErr) {
t.Errorf("validate(): want error containing %q, got %v", test.wantErr, err)
}
})
}
}
|
database
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/internal/database/write_zip_test.go
|
// Copyright 2024 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package database
import (
"path/filepath"
"testing"
)
func TestWriteZip(t *testing.T) {
tmp, want, got := t.TempDir(), t.TempDir(), t.TempDir()
if err := txtarToDir(validTxtar, want, false); err != nil {
t.Fatal(err)
}
zipped := filepath.Join(tmp, "all.zip")
if err := valid.WriteZip(zipped); err != nil {
t.Fatal("WriteZip:", err)
}
if err := Unzip(zipped, got); err != nil {
t.Fatal("Unzip:", err)
}
if err := cmpDirHashes(want, got); err != nil {
t.Error(err)
}
}
|
database
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/internal/database/from_repo.go
|
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package database
import (
"context"
"encoding/json"
"fmt"
"path"
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/plumbing/object"
"golang.org/x/vulndb/internal/derrors"
"golang.org/x/vulndb/internal/gitrepo"
"golang.org/x/vulndb/internal/osv"
"golang.org/x/vulndb/internal/report"
)
// FromRepo creates a new Database based on the contents of the "data/osv"
// folder in the given repo.
//
// It reads each OSV file, marshals it into a struct, updates the
// modified and published times based on the time of latest and first
// CL to modify the file, and stores the struct in the Database).
//
// The result is an in-memory vulnerability database
// that can be written to files via Database.Write.
//
// The repo must contain a "data/osv" folder with files in
// OSV JSON format with filenames of the form GO-YYYY-XXXX.json.
//
// Does not modify the repo.
func FromRepo(ctx context.Context, repo *git.Repository) (_ *Database, err error) {
defer derrors.Wrap(&err, "FromRepo()")
d, err := New()
if err != nil {
return nil, err
}
root, err := gitrepo.Root(repo)
if err != nil {
return nil, err
}
commitDates, err := gitrepo.AllCommitDates(repo, gitrepo.HeadReference, report.OSVDir)
if err != nil {
return nil, err
}
if err = root.Files().ForEach(func(f *object.File) error {
if path.Dir(f.Name) != report.OSVDir ||
path.Ext(f.Name) != ".json" {
return nil
}
// Read the entry.
contents, err := f.Contents()
if err != nil {
return fmt.Errorf("could not read contents of file %s: %v", f.Name, err)
}
var entry osv.Entry
err = json.Unmarshal([]byte(contents), &entry)
if err != nil {
return err
}
// Set the modified and published times.
dates, ok := commitDates[f.Name]
if !ok {
return fmt.Errorf("can't find git repo commit dates for %q", f.Name)
}
addTimestamps(&entry, dates)
return d.Add(entry)
}); err != nil {
return nil, err
}
return d, nil
}
func addTimestamps(entry *osv.Entry, dates gitrepo.Dates) {
// If a report contains a published field, consider it
// the authoritative source of truth.
// Otherwise, use the time of the earliest commit in the git history.
if entry.Published.IsZero() {
entry.Published = osv.Time{Time: dates.Oldest}
}
// The modified time is the time of the latest commit for the file.
entry.Modified = osv.Time{Time: dates.Newest}
}
|
database
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/internal/database/new_test.go
|
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package database
import (
"testing"
"time"
"github.com/google/go-cmp/cmp"
"golang.org/x/vulndb/internal/osv"
"golang.org/x/vulndb/internal/report"
)
var (
jan1999 = osv.Time{Time: time.Date(1999, 1, 1, 0, 0, 0, 0, time.UTC)}
jan2000 = osv.Time{Time: time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC)}
jan2002 = osv.Time{Time: time.Date(2002, 1, 1, 0, 0, 0, 0, time.UTC)}
jan2003 = osv.Time{Time: time.Date(2003, 1, 1, 0, 0, 0, 0, time.UTC)}
testOSV1 = osv.Entry{
SchemaVersion: report.SchemaVersion,
ID: "GO-1999-0001",
Published: jan1999,
Modified: jan2000,
Aliases: []string{"CVE-1999-1111"},
Summary: "A summary",
Details: "Some details",
Affected: []osv.Affected{
{
Module: osv.Module{
Path: "stdlib",
Ecosystem: "Go",
},
Ranges: []osv.Range{
{
Type: "SEMVER",
Events: []osv.RangeEvent{
{Introduced: "0"}, {Fixed: "1.1.0"},
{Introduced: "1.2.0"},
{Fixed: "1.2.2"},
}}},
EcosystemSpecific: &osv.EcosystemSpecific{
Packages: []osv.Package{{Path: "package", Symbols: []string{"Symbol"}}}},
},
},
References: []osv.Reference{
{Type: "FIX", URL: "https://example.com/cl/123"},
}, DatabaseSpecific: &osv.DatabaseSpecific{
URL: "https://pkg.go.dev/vuln/GO-1999-0001"}}
testOSV2 = osv.Entry{
SchemaVersion: report.SchemaVersion,
ID: "GO-2000-0002",
Published: jan2000,
Modified: jan2002,
Aliases: []string{"CVE-1999-2222"},
Summary: "A summary",
Details: "Some details",
Affected: []osv.Affected{
{
Module: osv.Module{
Path: "example.com/module",
Ecosystem: "Go",
},
Ranges: []osv.Range{
{
Type: "SEMVER", Events: []osv.RangeEvent{{Introduced: "0"},
{Fixed: "1.2.0"},
}}},
EcosystemSpecific: &osv.EcosystemSpecific{
Packages: []osv.Package{{Path: "example.com/module/package",
Symbols: []string{"Symbol"},
}}}}},
References: []osv.Reference{
{Type: "FIX", URL: "https://example.com/cl/543"},
}, DatabaseSpecific: &osv.DatabaseSpecific{URL: "https://pkg.go.dev/vuln/GO-2000-0002"}}
testOSV3 = osv.Entry{
SchemaVersion: report.SchemaVersion,
ID: "GO-2000-0003",
Published: jan2000,
Modified: jan2003,
Aliases: []string{"CVE-1999-3333", "GHSA-xxxx-yyyy-zzzz"},
Summary: "A summary",
Details: "Some details",
Affected: []osv.Affected{
{
Module: osv.Module{
Path: "example.com/module",
Ecosystem: "Go",
},
Ranges: []osv.Range{
{
Type: "SEMVER",
Events: []osv.RangeEvent{
{Introduced: "0"}, {Fixed: "1.1.0"},
}}},
EcosystemSpecific: &osv.EcosystemSpecific{Packages: []osv.Package{
{
Path: "example.com/module/package",
Symbols: []string{"Symbol"},
}}}}},
References: []osv.Reference{
{Type: "FIX", URL: "https://example.com/cl/000"},
},
DatabaseSpecific: &osv.DatabaseSpecific{
URL: "https://pkg.go.dev/vuln/GO-2000-0003",
}}
valid = &Database{
DB: DBMeta{Modified: jan2003},
Modules: ModulesIndex{
"example.com/module": &Module{Path: "example.com/module", Vulns: []ModuleVuln{{ID: "GO-2000-0002", Modified: jan2002, Fixed: "1.2.0"}, {ID: "GO-2000-0003", Modified: jan2003, Fixed: "1.1.0"}}}, "stdlib": &Module{Path: "stdlib", Vulns: []ModuleVuln{{ID: "GO-1999-0001", Modified: jan2000, Fixed: "1.2.2"}}},
},
Vulns: VulnsIndex{
"GO-1999-0001": &Vuln{ID: "GO-1999-0001", Modified: jan2000, Aliases: []string{"CVE-1999-1111"}}, "GO-2000-0002": &Vuln{ID: "GO-2000-0002", Modified: jan2002, Aliases: []string{"CVE-1999-2222"}}, "GO-2000-0003": &Vuln{ID: "GO-2000-0003", Modified: jan2003, Aliases: []string{"CVE-1999-3333", "GHSA-xxxx-yyyy-zzzz"}},
},
Entries: []osv.Entry{testOSV1, testOSV2, testOSV3}}
)
func TestNew(t *testing.T) {
got, err := New(testOSV1, testOSV2, testOSV3)
if err != nil {
t.Fatal(err)
}
want := valid
if diff := cmp.Diff(want, got); diff != "" {
t.Errorf("New: unexpected diff (-want, +got):\n%v", diff)
}
}
func TestLatestFixedVersion(t *testing.T) {
tests := []struct {
name string
ranges []osv.Range
want string
}{
{
name: "empty",
ranges: []osv.Range{},
want: "",
},
{
name: "no fix",
ranges: []osv.Range{{
Type: osv.RangeTypeSemver,
Events: []osv.RangeEvent{
{
Introduced: "0",
},
},
}},
want: "",
},
{
name: "no latest fix",
ranges: []osv.Range{{
Type: osv.RangeTypeSemver,
Events: []osv.RangeEvent{
{Introduced: "0"},
{Fixed: "1.0.4"},
{Introduced: "1.1.2"},
},
}},
want: "",
},
{
name: "unsorted no latest fix",
ranges: []osv.Range{{
Type: osv.RangeTypeSemver,
Events: []osv.RangeEvent{
{Fixed: "1.0.4"},
{Introduced: "0"},
{Introduced: "1.1.2"},
{Introduced: "1.5.0"},
{Fixed: "1.1.4"},
},
}},
want: "",
},
{
name: "unsorted with fix",
ranges: []osv.Range{{
Type: osv.RangeTypeSemver,
Events: []osv.RangeEvent{
{
Fixed: "1.0.0",
},
{
Introduced: "0",
},
{
Fixed: "0.1.0",
},
{
Introduced: "0.5.0",
},
},
}},
want: "1.0.0",
},
{
name: "multiple ranges",
ranges: []osv.Range{{
Type: osv.RangeTypeSemver,
Events: []osv.RangeEvent{
{
Introduced: "0",
},
{
Fixed: "0.1.0",
},
},
},
{
Type: osv.RangeTypeSemver,
Events: []osv.RangeEvent{
{
Introduced: "0",
},
{
Fixed: "0.2.0",
},
},
}},
want: "0.2.0",
},
{
name: "pseudoversion",
ranges: []osv.Range{{
Type: osv.RangeTypeSemver,
Events: []osv.RangeEvent{
{
Introduced: "0",
},
{
Fixed: "0.0.0-20220824120805-abc",
},
{
Introduced: "0.0.0-20230824120805-efg",
},
{
Fixed: "0.0.0-20240824120805-hij",
},
},
}},
want: "0.0.0-20240824120805-hij",
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
got := latestFixedVersion(test.ranges)
if got != test.want {
t.Errorf("latestFixedVersion = %q, want %q", got, test.want)
}
})
}
}
|
database
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/internal/database/validate.go
|
// Copyright 2022 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package database
import (
"fmt"
"path/filepath"
"golang.org/x/vulndb/internal/derrors"
"golang.org/x/vulndb/internal/osv"
)
// ValidateDeploy checks that the database in newPath is a valid database,
// and that the database in newPath can be safely deployed on top of the
// database in oldPath.
func ValidateDeploy(newPath, oldPath string) (err error) {
derrors.Wrap(&err, "Validate(new=%s, old=%s)", newPath, oldPath)
new, err := Load(newPath)
if err != nil {
return err
}
old, err := RawLoad(filepath.Join(oldPath, idDir))
if err != nil {
return err
}
return validate(new, old)
}
// validate checks for deleted files and inconsistent timestamps.
func validate(new, old *Database) error {
newEntriesByID := make(map[string]osv.Entry, len(new.Entries))
for _, newEntry := range new.Entries {
newEntriesByID[newEntry.ID] = newEntry
}
for _, oldEntry := range old.Entries {
newEntry, ok := newEntriesByID[oldEntry.ID]
if !ok {
return fmt.Errorf("%s is not present in new database. Use the %q field to delete an entry", oldEntry.ID, "withdrawn")
}
if newEntry.Published != oldEntry.Published {
return fmt.Errorf("%s: published time cannot change (new %s, old %s)", oldEntry.ID, newEntry.Published, oldEntry.Published)
}
if newEntry.Modified.Before(oldEntry.Modified.Time) {
return fmt.Errorf("%s: modified time cannot decrease (new %s, old %s)", oldEntry.ID, newEntry.Modified, oldEntry.Modified)
}
}
return nil
}
|
database
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/internal/database/write_zip.go
|
// Copyright 2024 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package database
import (
"archive/zip"
"encoding/json"
"io"
"os"
"path/filepath"
)
// WriteZip writes the database to filename as a zip file.
func (db *Database) WriteZip(filename string) error {
if err := os.MkdirAll(filepath.Dir(filename), 0755); err != nil {
return err
}
f, err := os.Create(filename)
if err != nil {
return err
}
defer f.Close()
zw := zip.NewWriter(f)
defer zw.Close()
for endpoint, v := range map[string]any{dbEndpoint: db.DB, modulesEndpoint: db.Modules, vulnsEndpoint: db.Vulns} {
if err := writeZip(zw, filepath.Join(indexDir, endpoint), v); err != nil {
return err
}
}
for _, entry := range db.Entries {
if err := writeZip(zw, filepath.Join(idDir, entry.ID+".json"), entry); err != nil {
return err
}
}
return nil
}
// Unzip unzips the zip file in src and writes it to the directory dst.
func Unzip(src, dst string) error {
zr, err := zip.OpenReader(src)
if err != nil {
return err
}
defer zr.Close()
for _, f := range zr.File {
fpath := filepath.Join(dst, f.Name)
if f.FileInfo().IsDir() {
if err := os.MkdirAll(fpath, os.ModePerm); err != nil {
return err
}
continue
}
src, err := f.Open()
if err != nil {
return err
}
defer src.Close()
if err := os.MkdirAll(filepath.Dir(fpath), os.ModePerm); err != nil {
return err
}
dst, err := os.Create(fpath)
if err != nil {
return err
}
defer dst.Close()
if _, err := io.Copy(dst, src); err != nil {
return err
}
}
return nil
}
func writeZip(zw *zip.Writer, filename string, v any) error {
b, err := json.Marshal(v)
if err != nil {
return err
}
w, err := zw.Create(filename)
if err != nil {
return err
}
if _, err := w.Write(b); err != nil {
return err
}
return nil
}
|
database
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/internal/database/new.go
|
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package database
import (
"fmt"
"golang.org/x/vulndb/internal/osv"
"golang.org/x/vulndb/internal/version"
)
// New creates a new database from the given entries.
// Errors if there are multiple entries with the same ID.
func New(entries ...osv.Entry) (*Database, error) {
db := &Database{
DB: DBMeta{},
Modules: make(ModulesIndex),
Vulns: make(VulnsIndex),
Entries: make([]osv.Entry, 0, len(entries)),
}
for _, entry := range entries {
if err := db.Add(entry); err != nil {
return nil, err
}
}
return db, nil
}
// Add adds new entries to a database, erroring if any of the entries
// is already in the database.
func (db *Database) Add(entries ...osv.Entry) error {
for _, entry := range entries {
if err := db.Vulns.add(entry); err != nil {
return err
}
// Only add the entry once we are sure it won't
// cause an error.
db.Entries = append(db.Entries, entry)
db.Modules.add(entry)
db.DB.add(entry)
}
return nil
}
func (dbi *DBMeta) add(entry osv.Entry) {
if entry.Modified.After(dbi.Modified.Time) {
dbi.Modified = entry.Modified
}
}
func (m *ModulesIndex) add(entry osv.Entry) {
for _, affected := range entry.Affected {
modulePath := affected.Module.Path
if _, ok := (*m)[modulePath]; !ok {
(*m)[modulePath] = &Module{
Path: modulePath,
Vulns: []ModuleVuln{},
}
}
module := (*m)[modulePath]
module.Vulns = append(module.Vulns, ModuleVuln{
ID: entry.ID,
Modified: entry.Modified,
Fixed: latestFixedVersion(affected.Ranges),
})
}
}
func (v *VulnsIndex) add(entry osv.Entry) error {
if _, ok := (*v)[entry.ID]; ok {
return fmt.Errorf("id %q appears twice in database", entry.ID)
}
(*v)[entry.ID] = &Vuln{
ID: entry.ID,
Modified: entry.Modified,
Aliases: entry.Aliases,
}
return nil
}
func latestFixedVersion(ranges []osv.Range) string {
var latestFixed string
for _, r := range ranges {
if r.Type == osv.RangeTypeSemver {
for _, e := range r.Events {
if fixed := e.Fixed; fixed != "" && version.Before(latestFixed, fixed) {
latestFixed = fixed
}
}
// If the vulnerability was re-introduced after the latest fix
// we found, there is no latest fix for this range.
for _, e := range r.Events {
if introduced := e.Introduced; introduced != "" && introduced != "0" && version.Before(latestFixed, introduced) {
latestFixed = ""
break
}
}
}
}
return string(latestFixed)
}
|
database
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/internal/database/from_repo_test.go
|
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package database
import (
"context"
"testing"
"github.com/google/go-cmp/cmp"
"golang.org/x/vulndb/internal/gitrepo"
"golang.org/x/vulndb/internal/osv"
"golang.org/x/vulndb/internal/report"
)
var (
testOSV4 = osv.Entry{
SchemaVersion: report.SchemaVersion,
ID: "GO-1999-0001",
Published: jan2002, // overwritten because unset
Modified: jan2002, // overwritten
Aliases: []string{"CVE-1999-1111"},
Summary: "A summary",
Details: "Some details",
Affected: []osv.Affected{
{
Module: osv.Module{
Path: "stdlib",
Ecosystem: "Go",
},
Ranges: []osv.Range{
{
Type: "SEMVER",
Events: []osv.RangeEvent{
{Introduced: "0"}, {Fixed: "1.1.0"},
{Introduced: "1.2.0"},
{Fixed: "1.2.2"},
}}},
EcosystemSpecific: &osv.EcosystemSpecific{
Packages: []osv.Package{{Path: "package", Symbols: []string{"Symbol"}}}}},
},
References: []osv.Reference{
{Type: "FIX", URL: "https://example.com/cl/123"},
},
DatabaseSpecific: &osv.DatabaseSpecific{
URL: "https://pkg.go.dev/vuln/GO-1999-0001"},
}
testOSV5 = osv.Entry{
SchemaVersion: report.SchemaVersion,
ID: "GO-2000-0002",
Published: jan2000, // not overwritten
Modified: jan2002, // overwritten
Aliases: []string{"CVE-1999-2222"},
Summary: "A summary",
Details: "Some details",
Affected: []osv.Affected{
{
Module: osv.Module{
Path: "example.com/module",
Ecosystem: "Go",
},
Ranges: []osv.Range{
{
Type: "SEMVER", Events: []osv.RangeEvent{{Introduced: "0"},
{Fixed: "1.2.0"},
}}},
EcosystemSpecific: &osv.EcosystemSpecific{
Packages: []osv.Package{{Path: "example.com/module/package",
Symbols: []string{"Symbol"},
}}}}},
References: []osv.Reference{
{Type: "FIX", URL: "https://example.com/cl/543"},
},
DatabaseSpecific: &osv.DatabaseSpecific{URL: "https://pkg.go.dev/vuln/GO-2000-0002"}}
testOSV6 = osv.Entry{
SchemaVersion: report.SchemaVersion,
ID: "GO-2000-0003",
Published: jan2000, // not overwritten
Modified: jan2002, // overwritten
Aliases: []string{"CVE-1999-3333", "GHSA-xxxx-yyyy-zzzz"},
Summary: "A summary",
Details: "Some details",
Affected: []osv.Affected{
{
Module: osv.Module{
Path: "example.com/module",
Ecosystem: "Go",
},
Ranges: []osv.Range{
{
Type: "SEMVER",
Events: []osv.RangeEvent{
{Introduced: "0"}, {Fixed: "1.1.0"},
}}},
EcosystemSpecific: &osv.EcosystemSpecific{Packages: []osv.Package{
{
Path: "example.com/module/package",
Symbols: []string{"Symbol"},
}}}}},
References: []osv.Reference{
{Type: "FIX", URL: "https://example.com/cl/000"},
},
DatabaseSpecific: &osv.DatabaseSpecific{
URL: "https://pkg.go.dev/vuln/GO-2000-0003",
},
}
validFromRepo = &Database{
DB: DBMeta{Modified: jan2002},
Modules: ModulesIndex{"example.com/module": &Module{Path: "example.com/module", Vulns: []ModuleVuln{{ID: "GO-2000-0002", Modified: jan2002, Fixed: "1.2.0"}, {ID: "GO-2000-0003", Modified: jan2002, Fixed: "1.1.0"}}}, "stdlib": &Module{Path: "stdlib", Vulns: []ModuleVuln{{ID: "GO-1999-0001", Modified: jan2002, Fixed: "1.2.2"}}}},
Vulns: VulnsIndex{"GO-1999-0001": &Vuln{ID: "GO-1999-0001", Modified: jan2002, Aliases: []string{"CVE-1999-1111"}}, "GO-2000-0002": &Vuln{ID: "GO-2000-0002", Modified: jan2002, Aliases: []string{"CVE-1999-2222"}}, "GO-2000-0003": &Vuln{ID: "GO-2000-0003", Modified: jan2002, Aliases: []string{"CVE-1999-3333", "GHSA-xxxx-yyyy-zzzz"}}},
Entries: []osv.Entry{testOSV4, testOSV5, testOSV6}}
)
func TestFromRepo(t *testing.T) {
// Checks that modified and published times are set correctly
// when we read from a repo.
ctx := context.Background()
testRepo, err := gitrepo.ReadTxtarRepo(vulndbTxtar, jan2002.Time)
if err != nil {
t.Fatal(err)
}
got, err := FromRepo(ctx, testRepo)
if err != nil {
t.Fatal(err)
}
want := validFromRepo
if diff := cmp.Diff(want, got); diff != "" {
t.Errorf("FromRepo: unexpected diff (-want, +got):\n%s", diff)
}
}
|
database
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/internal/database/load.go
|
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package database
import (
"encoding/json"
"fmt"
"io/fs"
"os"
"path/filepath"
"golang.org/x/exp/slices"
"golang.org/x/vulndb/internal/derrors"
"golang.org/x/vulndb/internal/osv"
"golang.org/x/vulndb/internal/osvutils"
"golang.org/x/vulndb/internal/report"
)
// Load loads a database assuming that path contains a full, valid
// database following the v1 specification.
//
// It errors if:
// - any required files are missing or invalid
// - any unexpected files are found in the index/ or ID/ folders
// (with the exception that ID/index.json, from the legacy spec, is ignored)
//
// Any files present in the top level directory are ignored.
func Load(path string) (_ *Database, err error) {
defer derrors.Wrap(&err, "Load(%q)", path)
db, err := RawLoad(filepath.Join(path, idDir))
if err != nil {
return nil, err
}
requireGzip := true
if err := db.validateIndex(filepath.Join(path, indexDir), requireGzip); err != nil {
return nil, err
}
if err := db.validateEntries(filepath.Join(path, idDir), requireGzip); err != nil {
return nil, err
}
return db, nil
}
// RawLoad loads a database assuming that vulnsPath contains ".json" files
// representing OSV entries.
// It errors if any of the files cannot be unmarshaled into osv.Entry.
// It does not require any database indexes or gzipped files to be present,
// Directories and non-JSON files are ignored.
// Also, to accommodate the legacy spec, the file "index.json" is ignored
// if present.
func RawLoad(vulnsPath string) (_ *Database, err error) {
defer derrors.Wrap(&err, "RawLoad(%q)", vulnsPath)
db, err := New()
if err != nil {
return nil, err
}
if err := filepath.WalkDir(vulnsPath, func(path string, f fs.DirEntry, err error) error {
if err != nil {
return err
}
fname := f.Name()
if f.IsDir() ||
fname == "index.json" ||
filepath.Ext(fname) != ".json" {
return nil
}
var entry osv.Entry
if err = report.UnmarshalFromFile(path, &entry); err != nil {
return fmt.Errorf("could not unmarshal %q: %v", path, err)
}
return db.Add(entry)
}); err != nil {
return nil, err
}
return db, nil
}
func (db *Database) validateIndex(indexPath string, requireGzip bool) (err error) {
defer derrors.Wrap(&err, "validateIndex(%q)", indexPath)
// Check that the index files are present and have the correct
// contents.
dbPath := filepath.Join(indexPath, dbEndpoint)
if err := checkFiles(dbPath, db.DB, requireGzip); err != nil {
return err
}
modulesPath := filepath.Join(indexPath, modulesEndpoint)
if err := checkFiles(modulesPath, db.Modules, requireGzip); err != nil {
return err
}
vulnsPath := filepath.Join(indexPath, vulnsEndpoint)
if err := checkFiles(vulnsPath, db.Vulns, requireGzip); err != nil {
return err
}
// Check for unexpected files in the index folder.
expected := []string{
indexDir,
dbEndpoint, dbEndpoint + ".gz",
modulesEndpoint, modulesEndpoint + ".gz",
vulnsEndpoint, vulnsEndpoint + ".gz",
}
return checkNoUnexpectedFiles(indexPath, expected)
}
func (db *Database) validateEntries(idPath string, requireGzip bool) (err error) {
defer derrors.Wrap(&err, "validateEntries(%q)", idPath)
expected := []string{
idDir,
"index.json", // index.json is OK to accommodate legacy spec
}
for _, entry := range db.Entries {
if err = osvutils.Validate(&entry); err != nil {
return err
}
path := filepath.Join(idPath, entry.ID+".json")
if err = checkFiles(path, entry, requireGzip); err != nil {
return err
}
expected = append(expected, entry.ID+".json", entry.ID+".json.gz")
}
return checkNoUnexpectedFiles(idPath, expected)
}
func checkNoUnexpectedFiles(path string, expected []string) error {
if err := filepath.WalkDir(path, func(path string, f fs.DirEntry, err error) error {
if err != nil {
return err
}
if !slices.Contains(expected, f.Name()) {
return fmt.Errorf("unexpected file %s", f.Name())
}
return nil
}); err != nil {
return err
}
return nil
}
// checkFiles ensures that filepath and filepath+".gz" exist and
// have contents consistent with v.
// Returns an error if:
// - any expected files don't exist or v cannot be marshaled
// - the contents of filepath do not match the result
// of marshaling v
// - the uncompressed contents of filepath+".gz" do not match the
// contents of filepath
func checkFiles(filepath string, v any, requireGzip bool) (err error) {
defer derrors.Wrap(&err, "checkFiles(%q)", filepath)
contents, err := os.ReadFile(filepath)
if err != nil {
return err
}
marshaled, err := json.Marshal(v)
if err != nil {
return err
}
if c, m := string(contents), string(marshaled); c != m {
return fmt.Errorf("%s: contents do not match marshaled bytes of value:\ncontents:\n%s\nvalue (marshaled):\n%s", filepath, c, m)
}
if requireGzip {
gzipped, err := readGzipped(filepath + ".gz")
if err != nil {
return err
}
if c, g := string(contents), string(gzipped); c != g {
return fmt.Errorf("%[1]s: contents of uncompressed file do not match contents of compressed file:\ncontents of %[1]s:\n%[2]s\ncontents of %[1]s.gz:\n%[3]s", filepath, c, g)
}
}
return nil
}
|
database
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/internal/database/gzip.go
|
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package database
import (
"bytes"
"compress/gzip"
"io/ioutil"
"os"
)
// writeGzipped compresses the data in data and writes it
// to filename, creating the file if needed.
func writeGzipped(filename string, data []byte) error {
var b bytes.Buffer
w, err := gzip.NewWriterLevel(&b, 9)
if err != nil {
return err
}
defer w.Close()
if _, err := w.Write(data); err != nil {
return err
}
if err := w.Close(); err != nil {
return err
}
if err := os.WriteFile(filename, b.Bytes(), 0644); err != nil {
return err
}
return nil
}
// readGzipped returns the uncompressed bytes of gzipped file filename.
func readGzipped(filename string) ([]byte, error) {
b, err := os.ReadFile(filename)
if err != nil {
return nil, err
}
buf := bytes.NewBuffer(b)
r, err := gzip.NewReader(buf)
if err != nil {
return nil, err
}
defer r.Close()
return ioutil.ReadAll(r)
}
|
database
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/internal/database/load_test.go
|
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package database
import (
"path/filepath"
"regexp"
"testing"
"github.com/google/go-cmp/cmp"
)
func TestLoad(t *testing.T) {
tmp := t.TempDir()
gzip := true
if err := txtarToDir(validTxtar, tmp, gzip); err != nil {
t.Fatal(err)
}
got, err := Load(tmp)
if err != nil {
t.Fatal(err)
}
want := valid
if diff := cmp.Diff(want, got); diff != "" {
t.Errorf("Load: unexpected diff (-want, +got):\n%v", diff)
}
}
func TestLoadError(t *testing.T) {
tests := []struct {
name string
db string
gzip bool
wantErrRe string
}{
{
name: "invalid db.json",
db: invalidDBMetaTxtar,
gzip: true,
wantErrRe: `db\.json: contents do not match`,
},
{
name: "invalid modules.json",
db: invalidModulesTxtar,
gzip: true,
wantErrRe: `modules\.json: contents do not match`,
},
{
name: "invalid vulns.json",
db: invalidVulnsTxtar,
gzip: true,
wantErrRe: `vulns\.json: contents do not match`,
},
{
name: "invalid entry filename",
db: invalidFilenameTxtar,
gzip: true,
wantErrRe: `GO-1999-0001\.json:.*(cannot find|no such)`,
},
{
name: "unmarshalable entry contents",
db: invalidEntriesTxtar,
gzip: true,
wantErrRe: `cannot unmarshal`,
},
{
name: "no gzip",
db: validTxtar,
gzip: false,
wantErrRe: `\.gz:.*(cannot find|no such)`,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
tmp := t.TempDir()
if err := txtarToDir(test.db, tmp, test.gzip); err != nil {
t.Fatal(err)
}
errRe := regexp.MustCompile(test.wantErrRe)
if _, gotErr := Load(tmp); gotErr == nil ||
!errRe.MatchString(gotErr.Error()) {
t.Errorf("Load: got %s, want error containing %q", gotErr, test.wantErrRe)
}
})
}
}
func TestRawLoad(t *testing.T) {
tmp := t.TempDir()
gzip := false
if err := txtarToDir(validTxtar, tmp, gzip); err != nil {
t.Fatal(err)
}
got, err := RawLoad(filepath.Join(tmp, idDir))
if err != nil {
t.Fatal(err)
}
want := valid
if diff := cmp.Diff(want, got); diff != "" {
t.Errorf("Load: unexpected diff (-want, +got):\n%v", diff)
}
}
|
testdata
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/internal/database/testdata/db-small.txtar
|
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//
// Test database for the Go vulnerability database v1 schema with one
// entry.
-- index/db.json --
{
"modified": "2003-01-01T00:00:00Z"
}
-- index/vulns.json --
[
{
"id": "GO-2000-0003",
"modified": "2003-01-01T00:00:00Z",
"aliases": [
"CVE-1999-3333",
"GHSA-xxxx-yyyy-zzzz"
]
}
]
-- index/modules.json --
[
{
"path": "example.com/module",
"vulns": [
{
"id": "GO-2000-0003",
"modified": "2003-01-01T00:00:00Z",
"fixed": "1.1.0"
}
]
}
]
-- ID/GO-2000-0003.json --
{
"schema_version": "1.3.1",
"id": "GO-2000-0003",
"modified": "2003-01-01T00:00:00Z",
"published": "2000-01-01T00:00:00Z",
"aliases": [
"CVE-1999-3333",
"GHSA-xxxx-yyyy-zzzz"
],
"summary": "A summary",
"details": "Some details",
"affected": [
{
"package": {
"name": "example.com/module",
"ecosystem": "Go"
},
"ranges": [
{
"type": "SEMVER",
"events": [
{
"introduced": "0"
},
{
"fixed": "1.1.0"
}
]
}
],
"ecosystem_specific": {
"imports": [
{
"path": "example.com/module/package",
"symbols": [
"Symbol"
]
}
]
}
}
],
"references": [
{
"type": "FIX",
"url": "https://example.com/cl/000"
}
],
"database_specific": {
"url": "https://pkg.go.dev/vuln/GO-2000-0003"
}
}
|
testdata
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/internal/database/testdata/vulndb-repo.txtar
|
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//
// Test representation of the vulndb repo.
// Modified times will be overwritten with time of CL
// submission. Published times will be overwritten if unset (zero).
-- data/osv/GO-1999-0001.json --
{
"schema_version": "1.3.1",
"id": "GO-1999-0001",
"modified": "0001-01-01T00:00:00Z",
"published": "0001-01-01T00:00:00Z",
"aliases": [
"CVE-1999-1111"
],
"summary": "A summary",
"details": "Some details",
"affected": [
{
"package": {
"name": "stdlib",
"ecosystem": "Go"
},
"ranges": [
{
"type": "SEMVER",
"events": [
{
"introduced": "0"
},
{
"fixed": "1.1.0"
},
{
"introduced": "1.2.0"
},
{
"fixed": "1.2.2"
}
]
}
],
"ecosystem_specific": {
"imports": [
{
"path": "package",
"symbols": [
"Symbol"
]
}
]
}
}
],
"references": [
{
"type": "FIX",
"url": "https://example.com/cl/123"
}
],
"database_specific": {
"url": "https://pkg.go.dev/vuln/GO-1999-0001"
}
}
-- data/osv/GO-2000-0002.json --
{
"schema_version": "1.3.1",
"id": "GO-2000-0002",
"modified": "0001-01-01T00:00:00Z",
"published": "2000-01-01T00:00:00Z",
"aliases": [
"CVE-1999-2222"
],
"summary": "A summary",
"details": "Some details",
"affected": [
{
"package": {
"name": "example.com/module",
"ecosystem": "Go"
},
"ranges": [
{
"type": "SEMVER",
"events": [
{
"introduced": "0"
},
{
"fixed": "1.2.0"
}
]
}
],
"ecosystem_specific": {
"imports": [
{
"path": "example.com/module/package",
"symbols": [
"Symbol"
]
}
]
}
}
],
"references": [
{
"type": "FIX",
"url": "https://example.com/cl/543"
}
],
"database_specific": {
"url": "https://pkg.go.dev/vuln/GO-2000-0002"
}
}
-- data/osv/GO-2000-0003.json --
{
"schema_version": "1.3.1",
"id": "GO-2000-0003",
"modified": "0001-01-01T00:00:00Z",
"published": "2000-01-01T00:00:00Z",
"aliases": [
"CVE-1999-3333",
"GHSA-xxxx-yyyy-zzzz"
],
"summary": "A summary",
"details": "Some details",
"affected": [
{
"package": {
"name": "example.com/module",
"ecosystem": "Go"
},
"ranges": [
{
"type": "SEMVER",
"events": [
{
"introduced": "0"
},
{
"fixed": "1.1.0"
}
]
}
],
"ecosystem_specific": {
"imports": [
{
"path": "example.com/module/package",
"symbols": [
"Symbol"
]
}
]
}
}
],
"references": [
{
"type": "FIX",
"url": "https://example.com/cl/000"
}
],
"database_specific": {
"url": "https://pkg.go.dev/vuln/GO-2000-0003"
}
}
|
testdata
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/internal/database/testdata/invalid-modules.txtar
|
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//
// Test database for the Go vulnerability database v1 schema.
// This database is invalid because modules.json is missing
// an entry for "GO-1999-0001".
-- index/db.json --
{
"modified": "2000-01-01T00:00:00Z"
}
-- index/vulns.json --
[
{
"id": "GO-1999-0001",
"modified": "2000-01-01T00:00:00Z",
"aliases": [
"CVE-1999-1111"
]
}
]
-- index/modules.json --
[
{
"path": "stdlib",
"vulns": []
}
]
-- ID/GO-1999-0001.json --
{
"schema_version": "1.3.1",
"id": "GO-1999-0001",
"modified": "2000-01-01T00:00:00Z",
"published": "1999-01-01T00:00:00Z",
"aliases": [
"CVE-1999-1111"
],
"summary": "A summary",
"details": "Some details",
"affected": [
{
"package": {
"name": "stdlib",
"ecosystem": "Go"
},
"ranges": [
{
"type": "SEMVER",
"events": [
{
"introduced": "0"
},
{
"fixed": "1.1.0"
},
{
"introduced": "1.2.0"
},
{
"fixed": "1.2.2"
}
]
}
],
"ecosystem_specific": {
"imports": [
{
"path": "package",
"symbols": [
"Symbol"
]
}
]
}
}
],
"references": [
{
"type": "FIX",
"url": "https://example.com/cl/123"
}
],
"database_specific": {
"url": "https://pkg.go.dev/vuln/GO-1999-0001"
}
}
|
testdata
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/internal/database/testdata/invalid-db-meta.txtar
|
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//
// Test database for the Go vulnerability database v1 schema.
// This database is invalid because the modified time in db.json
// is incorrect.
-- index/db.json --
{
"modified": "2003-01-01T00:00:00Z"
}
-- index/vulns.json --
[
{
"id": "GO-1999-0001",
"modified": "2000-01-01T00:00:00Z",
"aliases": [
"CVE-1999-1111"
]
}
]
-- index/modules.json --
[
{
"path": "stdlib",
"vulns": [
{
"id": "GO-1999-0001",
"modified": "2000-01-01T00:00:00Z",
"fixed": "1.2.2"
}
]
}
]
-- ID/GO-1999-0001.json --
{
"schema_version": "1.3.1",
"id": "GO-1999-0001",
"modified": "2000-01-01T00:00:00Z",
"published": "1999-01-01T00:00:00Z",
"aliases": [
"CVE-1999-1111"
],
"summary": "A summary",
"details": "Some details",
"affected": [
{
"package": {
"name": "stdlib",
"ecosystem": "Go"
},
"ranges": [
{
"type": "SEMVER",
"events": [
{
"introduced": "0"
},
{
"fixed": "1.1.0"
},
{
"introduced": "1.2.0"
},
{
"fixed": "1.2.2"
}
]
}
],
"ecosystem_specific": {
"imports": [
{
"path": "package",
"symbols": [
"Symbol"
]
}
]
}
}
],
"references": [
{
"type": "FIX",
"url": "https://example.com/cl/123"
}
],
"database_specific": {
"url": "https://pkg.go.dev/vuln/GO-1999-0001"
}
}
|
testdata
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/internal/database/testdata/invalid-entries.txtar
|
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//
// Test database for the Go vulnerability database v1 schema.
// This database is invalid because the entry "ID/GO-1999-0001.json"
// is formatted as an array of OSV entries instead of a single entry.
-- index/db.json --
{
"modified": "2000-01-01T00:00:00Z"
}
-- index/vulns.json --
[
{
"id": "GO-1999-0001",
"modified": "2000-01-01T00:00:00Z",
"aliases": [
"CVE-1999-1111"
]
}
]
-- index/modules.json --
[
{
"path": "stdlib",
"vulns": [
{
"id": "GO-1999-0001",
"modified": "2000-01-01T00:00:00Z",
"fixed": "1.2.2"
}
]
}
]
-- ID/GO-1999-0001.json --
[
{
"schema_version": "1.3.1",
"id": "GO-1999-0001",
"modified": "2000-01-01T00:00:00Z",
"published": "1999-01-01T00:00:00Z",
"aliases": [
"CVE-1999-1111"
],
"summary": "A summary",
"details": "Some details",
"affected": [
{
"package": {
"name": "stdlib",
"ecosystem": "Go"
},
"ranges": [
{
"type": "SEMVER",
"events": [
{
"introduced": "0"
},
{
"fixed": "1.1.0"
},
{
"introduced": "1.2.0"
},
{
"fixed": "1.2.2"
}
]
}
],
"ecosystem_specific": {
"imports": [
{
"path": "package",
"symbols": [
"Symbol"
]
}
]
}
}
],
"references": [
{
"type": "FIX",
"url": "https://example.com/cl/123"
}
],
"database_specific": {
"url": "https://pkg.go.dev/vuln/GO-1999-0001"
}
}
]
|
testdata
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/internal/database/testdata/db.txtar
|
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//
// Test database for the Go vulnerability database v1 schema with
// three entries.
-- index/db.json --
{
"modified": "2003-01-01T00:00:00Z"
}
-- index/vulns.json --
[
{
"id": "GO-1999-0001",
"modified": "2000-01-01T00:00:00Z",
"aliases": [
"CVE-1999-1111"
]
},
{
"id": "GO-2000-0002",
"modified": "2002-01-01T00:00:00Z",
"aliases": [
"CVE-1999-2222"
]
},
{
"id": "GO-2000-0003",
"modified": "2003-01-01T00:00:00Z",
"aliases": [
"CVE-1999-3333",
"GHSA-xxxx-yyyy-zzzz"
]
}
]
-- index/modules.json --
[
{
"path": "example.com/module",
"vulns": [
{
"id": "GO-2000-0002",
"modified": "2002-01-01T00:00:00Z",
"fixed": "1.2.0"
},
{
"id": "GO-2000-0003",
"modified": "2003-01-01T00:00:00Z",
"fixed": "1.1.0"
}
]
},
{
"path": "stdlib",
"vulns": [
{
"id": "GO-1999-0001",
"modified": "2000-01-01T00:00:00Z",
"fixed": "1.2.2"
}
]
}
]
-- ID/GO-1999-0001.json --
{
"schema_version": "1.3.1",
"id": "GO-1999-0001",
"modified": "2000-01-01T00:00:00Z",
"published": "1999-01-01T00:00:00Z",
"aliases": [
"CVE-1999-1111"
],
"summary": "A summary",
"details": "Some details",
"affected": [
{
"package": {
"name": "stdlib",
"ecosystem": "Go"
},
"ranges": [
{
"type": "SEMVER",
"events": [
{
"introduced": "0"
},
{
"fixed": "1.1.0"
},
{
"introduced": "1.2.0"
},
{
"fixed": "1.2.2"
}
]
}
],
"ecosystem_specific": {
"imports": [
{
"path": "package",
"symbols": [
"Symbol"
]
}
]
}
}
],
"references": [
{
"type": "FIX",
"url": "https://example.com/cl/123"
}
],
"database_specific": {
"url": "https://pkg.go.dev/vuln/GO-1999-0001"
}
}
-- ID/GO-2000-0002.json --
{
"schema_version": "1.3.1",
"id": "GO-2000-0002",
"modified": "2002-01-01T00:00:00Z",
"published": "2000-01-01T00:00:00Z",
"aliases": [
"CVE-1999-2222"
],
"summary": "A summary",
"details": "Some details",
"affected": [
{
"package": {
"name": "example.com/module",
"ecosystem": "Go"
},
"ranges": [
{
"type": "SEMVER",
"events": [
{
"introduced": "0"
},
{
"fixed": "1.2.0"
}
]
}
],
"ecosystem_specific": {
"imports": [
{
"path": "example.com/module/package",
"symbols": [
"Symbol"
]
}
]
}
}
],
"references": [
{
"type": "FIX",
"url": "https://example.com/cl/543"
}
],
"database_specific": {
"url": "https://pkg.go.dev/vuln/GO-2000-0002"
}
}
-- ID/GO-2000-0003.json --
{
"schema_version": "1.3.1",
"id": "GO-2000-0003",
"modified": "2003-01-01T00:00:00Z",
"published": "2000-01-01T00:00:00Z",
"aliases": [
"CVE-1999-3333",
"GHSA-xxxx-yyyy-zzzz"
],
"summary": "A summary",
"details": "Some details",
"affected": [
{
"package": {
"name": "example.com/module",
"ecosystem": "Go"
},
"ranges": [
{
"type": "SEMVER",
"events": [
{
"introduced": "0"
},
{
"fixed": "1.1.0"
}
]
}
],
"ecosystem_specific": {
"imports": [
{
"path": "example.com/module/package",
"symbols": [
"Symbol"
]
}
]
}
}
],
"references": [
{
"type": "FIX",
"url": "https://example.com/cl/000"
}
],
"database_specific": {
"url": "https://pkg.go.dev/vuln/GO-2000-0003"
}
}
|
testdata
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/internal/database/testdata/invalid-vulns.txtar
|
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//
// Test database for the Go vulnerability database v1 schema.
// This database is invalid because there is an additional vuln
// in vulns.json that is not present in the ID/ folder.
-- index/db.json --
{
"modified": "2000-01-01T00:00:00Z"
}
-- index/vulns.json --
[
{
"id": "GO-1999-0001",
"modified": "2000-01-01T00:00:00Z",
"aliases": [
"CVE-1999-1111"
]
},
{
"id": "GO-1999-0002"
}
]
-- index/modules.json --
[
{
"path": "stdlib",
"vulns": [
{
"id": "GO-1999-0001",
"modified": "2000-01-01T00:00:00Z",
"fixed": "1.2.2"
}
]
}
]
-- ID/GO-1999-0001.json --
{
"schema_version": "1.3.1",
"id": "GO-1999-0001",
"modified": "2000-01-01T00:00:00Z",
"published": "1999-01-01T00:00:00Z",
"aliases": [
"CVE-1999-1111"
],
"summary": "A summary",
"details": "Some details",
"affected": [
{
"package": {
"name": "stdlib",
"ecosystem": "Go"
},
"ranges": [
{
"type": "SEMVER",
"events": [
{
"introduced": "0"
},
{
"fixed": "1.1.0"
},
{
"introduced": "1.2.0"
},
{
"fixed": "1.2.2"
}
]
}
],
"ecosystem_specific": {
"imports": [
{
"path": "package",
"symbols": [
"Symbol"
]
}
]
}
}
],
"references": [
{
"type": "FIX",
"url": "https://example.com/cl/123"
}
],
"database_specific": {
"url": "https://pkg.go.dev/vuln/GO-1999-0001"
}
}
|
testdata
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/internal/database/testdata/invalid-filename.txtar
|
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//
// Test database for the Go vulnerability database v1 schema.
// This database is invalid because the entry "ID/example.json"
// should be called "ID/GO-1999-0001.json".
-- index/db.json --
{
"modified": "2000-01-01T00:00:00Z"
}
-- index/vulns.json --
[
{
"id": "GO-1999-0001",
"modified": "2000-01-01T00:00:00Z",
"aliases": [
"CVE-1999-1111"
]
}
]
-- index/modules.json --
[
{
"path": "stdlib",
"vulns": [
{
"id": "GO-1999-0001",
"modified": "2000-01-01T00:00:00Z",
"fixed": "1.2.2"
}
]
}
]
-- ID/example.json --
{
"schema_version": "1.3.1",
"id": "GO-1999-0001",
"modified": "2000-01-01T00:00:00Z",
"published": "1999-01-01T00:00:00Z",
"aliases": [
"CVE-1999-1111"
],
"summary": "A summary",
"details": "Some details",
"affected": [
{
"package": {
"name": "stdlib",
"ecosystem": "Go"
},
"ranges": [
{
"type": "SEMVER",
"events": [
{
"introduced": "0"
},
{
"fixed": "1.1.0"
},
{
"introduced": "1.2.0"
},
{
"fixed": "1.2.2"
}
]
}
],
"ecosystem_specific": {
"imports": [
{
"path": "package",
"symbols": [
"Symbol"
]
}
]
}
}
],
"references": [
{
"type": "FIX",
"url": "https://example.com/cl/123"
}
],
"database_specific": {
"url": "https://pkg.go.dev/vuln/GO-1999-0001"
}
}
|
test
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/internal/test/txtar_test.go
|
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package test
import (
"io/fs"
"path/filepath"
"testing"
"github.com/google/go-cmp/cmp"
"golang.org/x/tools/txtar"
)
func TestWriteTxtar(t *testing.T) {
tmp := t.TempDir()
filename := filepath.Join(tmp, "example", "file.txtar")
files := []txtar.File{
{
Name: "a.txt",
Data: []byte("abcdefg\n"),
},
{
Name: "b.txt",
Data: []byte("hijklmnop\n"),
},
}
comment := "Context about this archive"
if err := WriteTxtar(filename, files, comment); err != nil {
t.Fatal(err)
}
got, err := txtar.ParseFile(filename)
if err != nil {
t.Fatal(err)
}
want := &txtar.Archive{
Comment: []byte(addBoilerplate(currentYear(), comment)),
Files: files,
}
if diff := cmp.Diff(want, got); diff != "" {
t.Errorf("mismatch (-want, +got):\n%s", diff)
}
}
func TestReadTxtar(t *testing.T) {
archiveFilename := filepath.Join(t.TempDir(), "archive.txtar")
fname, content := "dir/to/a/file.txt", []byte("some content\n")
files := []txtar.File{
{
Name: fname,
Data: content,
},
}
if err := WriteTxtar(archiveFilename, files, ""); err != nil {
t.Fatal(err)
}
fsys, err := ReadTxtarFS(archiveFilename)
if err != nil {
t.Fatal(err)
}
got, err := fs.ReadFile(fsys, fname)
if err != nil {
t.Error(err)
}
want := content
if !cmp.Equal(got, want) {
t.Errorf("fs.ReadFile = %s, want %s", got, want)
}
gotMatches, err := fs.Glob(fsys, "dir/*/*/*.txt")
if err != nil {
t.Errorf("fs.Glob = %v", err)
}
wantMatches := []string{fname}
if !cmp.Equal(gotMatches, wantMatches) {
t.Errorf("fs.Glob = %s, want %s", gotMatches, wantMatches)
}
}
|
test
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/internal/test/txtar.go
|
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package test
import (
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"regexp"
"strconv"
"testing/fstest"
"time"
"github.com/google/go-cmp/cmp"
"golang.org/x/tools/txtar"
)
func WriteTxtar(filename string, files []txtar.File, comment string) error {
if err := os.MkdirAll(filepath.Dir(filename), os.ModePerm); err != nil {
return err
}
if err := os.WriteFile(filename, txtar.Format(
&txtar.Archive{
Comment: []byte(addBoilerplate(currentYear(), comment)),
Files: files,
},
), 0666); err != nil {
return err
}
return nil
}
// addBoilerplate adds the copyright string for the given year to the
// given comment, and some additional spacing for readability.
func addBoilerplate(year int, comment string) string {
return fmt.Sprintf(`Copyright %d The Go Authors. All rights reserved.
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file.
%s
`, year, comment)
}
func currentYear() int {
year, _, _ := time.Now().Date()
return year
}
var copyrightRE = regexp.MustCompile(`Copyright (\d+)`)
// findCopyrightYear returns the copyright year in this comment,
// or an error if none is found.
func findCopyrightYear(comment string) (int, error) {
matches := copyrightRE.FindStringSubmatch(comment)
if len(matches) != 2 {
return 0, errors.New("comment does not contain a copyright year")
}
year, err := strconv.Atoi(matches[1])
if err != nil {
return 0, err
}
return year, nil
}
// CheckComment checks the validity of a txtar comment.
// It checks that the "got" comment is the same as would be generated
// by WriteTxtar(..., wantComment), but allows any copyright year.
//
// For testing.
func CheckComment(wantComment, got string) error {
year, err := findCopyrightYear(got)
if err != nil {
return err
}
want := addBoilerplate(year, wantComment)
if diff := cmp.Diff(want, got); diff != "" {
return fmt.Errorf("comment mismatch (-want, +got):\n%s", diff)
}
return nil
}
// FindFile returns the first "file" with the given filename in the
// txtar archive, or an error if none is found.
//
// Intended for testing.
func FindFile(ar *txtar.Archive, filename string) (*txtar.File, error) {
for _, f := range ar.Files {
if f.Name == filename {
return &f, nil
}
}
return nil, fmt.Errorf("%s not found", filename)
}
func ReadTxtarFS(filename string) (fs.FS, error) {
ar, err := txtar.ParseFile(filename)
if err != nil {
return nil, err
}
return TxtarArchiveToFS(ar)
}
func TxtarArchiveToFS(ar *txtar.Archive) (fs.FS, error) {
m := make(fstest.MapFS)
for _, a := range ar.Files {
m[a.Name] = &fstest.MapFile{Data: a.Data}
}
return m, nil
}
|
test
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/internal/test/packages.go
|
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package test
import (
"strings"
"testing"
"golang.org/x/tools/go/packages"
)
// VerifyImports verifies that a package only imports from allowed.
func VerifyImports(t *testing.T, allowed ...string) {
cfg := &packages.Config{Mode: packages.NeedImports | packages.NeedDeps}
pkgs, err := packages.Load(cfg, ".")
if err != nil {
t.Fatal(err)
}
check := map[string]struct{}{}
for _, imp := range allowed {
check[imp] = struct{}{}
}
for _, p := range pkgs {
for _, imp := range p.Imports {
// this is an approximate stdlib check that is good enough for these tests
if !strings.ContainsRune(imp.ID, '.') {
continue
}
if _, ok := check[imp.ID]; !ok {
t.Errorf("include of %s is not allowed", imp.ID)
}
}
}
}
|
devtools
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/devtools/curl_worker.sh
|
#!/bin/bash
# Copyright 2021 The Go Authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
# Visit a URL on the vuln worker.
set -e
source devtools/lib.sh || { echo "Are you at repo root?"; exit 1; }
env=$1
path=$2
url=$(worker_url $env)
tok=$(impersonation_token $env)
if [[ $path = update* || $path = issue* ]]; then
args="-X POST"
fi
curl $args -i -H "Authorization: Bearer $tok" $url/$path
|
devtools
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/devtools/deploy_worker.sh
|
#!/bin/bash
# Copyright 2021 The Go Authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
# Deploy the vuln worker to Cloud Run, using Cloud Build.
set -e
source devtools/lib.sh || { echo "Are you at repo root?"; exit 1; }
# Report whether the current repo's workspace has no uncommitted files.
clean_workspace() {
[[ $(git status --porcelain) == '' ]]
}
main() {
local prefix=
if [[ $1 = '-n' ]]; then
prefix='echo dryrun: '
shift
fi
local env=$1
case $env in
dev|prod);;
*)
die "usage: $0 [-n] (dev | prod)"
esac
local project=$(tfvar ${env}_project)
local commit=$(git rev-parse --short HEAD)
local unclean
if ! clean_workspace; then
unclean="-unclean"
fi
$prefix gcloud builds submit \
--project $project \
--config deploy/worker.yaml \
--substitutions SHORT_SHA=${commit}${unclean},_ENV=$env
}
main $@
|
devtools
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/devtools/proxy_worker.sh
|
#!/bin/bash
# Copyright 2022 The Go Authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
# Start the cloud run proxy pointing at a worker.
# To install the proxy:
# go install github.com/GoogleCloudPlatform/cloud-run-proxy@latest
set -e
source devtools/lib.sh || { echo "Are you at repo root?"; exit 1; }
env=$1
case $env in
dev|prod);;
*) die "usage: $0 (dev | prod)"
esac
cloud-run-proxy -host $(worker_url $env) -token $(impersonation_token $env)
|
devtools
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/devtools/lib.sh
|
# Copyright 2021 The Go Authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
# Library of useful bash functions and variables.
RED=; GREEN=; YELLOW=; NORMAL=;
MAXWIDTH=0
if tput setaf 1 >& /dev/null; then
RED=`tput setaf 1`
GREEN=`tput setaf 2`
YELLOW=`tput setaf 3`
NORMAL=`tput sgr0`
MAXWIDTH=$(( $(tput cols) - 2 ))
fi
EXIT_CODE=0
info() { echo -e "${GREEN}$@${NORMAL}" 1>&2; }
warn() { echo -e "${YELLOW}$@${NORMAL}" 1>&2; }
err() { echo -e "${RED}$@${NORMAL}" 1>&2; EXIT_CODE=1; }
die() {
err $@
exit 1
}
dryrun=false
# runcmd prints an info log describing the command that is about to be run, and
# then runs it. It sets EXIT_CODE to non-zero if the command fails, but does not exit
# the script.
runcmd() {
msg="$@"
if $dryrun; then
echo -e "${YELLOW}dryrun${GREEN}\$ $msg${NORMAL}"
return 0
fi
# Truncate command logging for narrow terminals.
# Account for the 2 characters of '$ '.
if [[ $MAXWIDTH -gt 0 && ${#msg} -gt $MAXWIDTH ]]; then
msg="${msg::$(( MAXWIDTH - 3 ))}..."
fi
echo -e "$@\n" 1>&2;
$@ || err "command failed"
}
# tfvar NAME returns the value of NAME in the terraform.tfvars file.
tfvar() {
local name=$1
awk '$1 == "'$name'" { print substr($3, 2, length($3)-2) }' terraform/terraform.tfvars
}
worker_url() {
local env=$1
case $env in
dev) echo https://dev-vuln-worker-ku6ias4ydq-uc.a.run.app;;
prod) echo https://prod-vuln-worker-cf7lo3kiaq-uc.a.run.app;;
*) die "usage: $0 (dev | prod)";;
esac
}
impersonation_service_account() {
local env=$1
case $env in
dev) echo impersonate-for-iap@go-discovery-exp.iam.gserviceaccount.com;;
prod) echo impersonate@go-vuln.iam.gserviceaccount.com;;
*) die "usage: $0 (dev | prod)";;
esac
}
impersonation_token() {
local env=$1
local oauth_client_id=$(tfvar ${env}_client_id)
if [[ $oauth_client_id = '' ]]; then
die "${env}_client_id is missing from your terraform.tfvars file"
fi
gcloud --impersonate-service-account $(impersonation_service_account $env) \
auth print-identity-token \
--audiences $oauth_client_id \
--include-email
}
|
populate_firestore
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/devtools/cmd/populate_firestore/populate_firestore.go
|
// Copyright 2022 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Populate the firestore DB with commit times.
// This is a one-time update to backfill data.
package main
import (
"context"
"flag"
"fmt"
"log"
"strings"
"time"
"cloud.google.com/go/firestore"
"github.com/go-git/go-git/v5/plumbing"
"golang.org/x/vulndb/internal/gitrepo"
"google.golang.org/api/iterator"
)
var (
project = flag.String("project", "", "project ID (required)")
namespace = flag.String("namespace", "", "Firestore namespace (required)")
localRepoPath = flag.String("local-cve-repo", "", "path to local repo")
startAfter = flag.String("start", "", "CVE ID to start after")
limit = flag.Int("limit", 0, "max to process")
)
const (
namespaceCollection = "Namespaces"
cveCollection = "CVEs"
)
func main() {
flag.Parse()
if *project == "" {
log.Fatal("need -project")
}
if *namespace == "" {
log.Fatal("need -namespace")
}
if *localRepoPath == "" {
log.Fatal("need -local-cve-repo")
}
if err := run(context.Background()); err != nil {
log.Fatal(err)
}
}
func run(ctx context.Context) error {
client, err := firestore.NewClient(ctx, *project)
if err != nil {
return err
}
defer client.Close()
repo, err := gitrepo.Open(ctx, *localRepoPath)
if err != nil {
return err
}
nsDoc := client.Collection(namespaceCollection).Doc(*namespace)
commitTimeCache := map[string]time.Time{}
getCommitTime := func(hash string) (time.Time, error) {
if t, ok := commitTimeCache[hash]; ok {
return t, nil
}
commit, err := repo.CommitObject(plumbing.NewHash(hash))
if err != nil {
return time.Time{}, fmt.Errorf("CommitObject(%s): %w", hash, err)
}
ct := commit.Committer.When.In(time.UTC)
fmt.Printf("repo commit %s at %s\n", hash, ct)
commitTimeCache[hash] = ct
return ct, nil
}
q := nsDoc.Collection(cveCollection).Query
if *startAfter != "" {
q = q.OrderBy(firestore.DocumentID, firestore.Asc).StartAfter(*startAfter)
}
if *limit != 0 {
q = q.Limit(*limit)
}
iter := q.Documents(ctx)
defer iter.Stop()
lastID, err := updateDB(ctx, client, iter, func(ds *firestore.DocumentSnapshot, wb *firestore.WriteBatch) (bool, error) {
_, err := ds.DataAt("CommitTime")
if err != nil && strings.Contains(err.Error(), "no field") {
ch, err := ds.DataAt("CommitHash")
if err != nil {
return false, fmt.Errorf(`%s.DataAt("CommitHash"): %w`, ds.Ref.ID, err)
}
ct, err := getCommitTime(ch.(string))
if err != nil {
return false, err
}
wb.Update(ds.Ref, []firestore.Update{{Path: "CommitTime", Value: ct}})
return true, nil
} else {
return false, err
}
})
if err != nil {
return err
}
fmt.Printf("last ID = %s\n", lastID)
return nil
}
const maxBatchSize = 500
func updateDB(ctx context.Context, client *firestore.Client, iter *firestore.DocumentIterator, update func(*firestore.DocumentSnapshot, *firestore.WriteBatch) (bool, error)) (string, error) {
done := false
total := 0
var lastID string
for !done {
wb := client.Batch()
size := 0
for {
ds, err := iter.Next()
if err == iterator.Done {
done = true
break
}
if err != nil {
return "", err
}
lastID = ds.Ref.ID
total++
if total%1000 == 0 {
fmt.Printf("%d records, last ID %s\n", total, lastID)
}
if b, err := update(ds, wb); err != nil {
return "", err
} else if b {
size++
if size >= maxBatchSize {
break
}
}
}
if size > 0 {
_, err := wb.Commit(ctx)
if err != nil {
return "", fmt.Errorf("wb.Commit: %w", err)
}
}
}
return lastID, nil
}
|
checkdeploy
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/cmd/checkdeploy/main.go
|
// Copyright 2022 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Command checkdeploy validates that it is safe to deploy a new
// vulnerability database.
package main
import (
"flag"
"fmt"
"log"
db "golang.org/x/vulndb/internal/database"
)
var (
newPath = flag.String("new", "", "path to new database")
existingPath = flag.String("existing", "", "path to existing database")
)
func main() {
flag.Parse()
if *newPath == "" {
log.Fatalf("flag -new must be set")
}
if *existingPath == "" {
log.Fatalf("flag -existing must be set")
}
if err := db.ValidateDeploy(*newPath, *existingPath); err != nil {
log.Fatal(err)
}
fmt.Printf("ok to deploy v1 database %s on top of %s\n", *newPath, *existingPath)
}
|
gendb
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/cmd/gendb/main.go
|
// Copyright 2021 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Command gendb provides a tool for converting YAML reports into JSON
// Go vulnerability databases.
package main
import (
"context"
"flag"
"log"
db "golang.org/x/vulndb/internal/database"
"golang.org/x/vulndb/internal/gitrepo"
)
var (
repoDir = flag.String("repo", ".", "Directory containing vulndb repo")
jsonDir = flag.String("out", "out", "Directory to write JSON database to")
zipFile = flag.String("zip", "", "if provided, file to write zipped database to (for v1 database only)")
indent = flag.Bool("indent", false, "Indent JSON for debugging")
)
func main() {
flag.Parse()
ctx := context.Background()
repo, err := gitrepo.CloneOrOpen(ctx, *repoDir)
if err != nil {
log.Fatal(err)
}
d, err := db.FromRepo(ctx, repo)
if err != nil {
log.Fatal(err)
}
if err := d.Write(*jsonDir); err != nil {
log.Fatal(err)
}
if *zipFile != "" {
if err := d.WriteZip(*zipFile); err != nil {
log.Fatal(err)
}
}
}
|
worker
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/cmd/worker/Dockerfile
|
# Copyright 2021 The Go Authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
# This Dockerfile expects the build context to be the repo root.
################################################################
FROM golang:1.21 AS builder
# If you change the Go version above, change the FROM line below as well.
# Set the working directory outside $GOPATH to ensure module mode is enabled.
WORKDIR /src
# Copy go.mod and go.sum into the container.
# If they don't change, which is the common case, then docker can
# cache this COPY and the subsequent RUN.
COPY go.mod go.sum checks.bash /
# Download the dependencies.
RUN go mod download
# Copy the repo from local machine into Docker client’s current working
# directory, so that we can use it to build the binary.
# See .dockerignore at the repo root for excluded files.
COPY . /src
# Build the binary.
RUN go build -mod=readonly ./cmd/worker
################################################################
FROM golang:1.21
LABEL maintainer="Go VulnDB Team <go-vulndb-team@google.com>"
# Copy CA certificates to prevent "x509: certificate signed by unknown authority" errors.
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt
WORKDIR app
COPY --from=builder src/worker worker
COPY internal/worker/static internal/worker/static
ARG DOCKER_IMAGE
ENV DOCKER_IMAGE=$DOCKER_IMAGE
CMD ["./worker"]
|
worker
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/cmd/worker/main.go
|
// Copyright 2021 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Command worker runs the vuln worker server.
// It can also be used to perform actions from the command line
// by providing a sub-command.
package main
import (
"bufio"
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"net/http"
"os"
"strings"
"text/tabwriter"
"time"
"golang.org/x/vulndb/internal/cvelistrepo"
"golang.org/x/vulndb/internal/ghsa"
"golang.org/x/vulndb/internal/gitrepo"
"golang.org/x/vulndb/internal/issues"
"golang.org/x/vulndb/internal/pkgsite"
"golang.org/x/vulndb/internal/proxy"
"golang.org/x/vulndb/internal/report"
"golang.org/x/vulndb/internal/worker"
"golang.org/x/vulndb/internal/worker/log"
"golang.org/x/vulndb/internal/worker/store"
)
var (
// Flags only for the command-line tool.
localRepoPath = flag.String("local-cve-repo", "", "path to local repo, instead of cloning remote")
force = flag.Bool("force", false, "force an update or scan to happen")
limit = flag.Int("limit", 0,
"limit on number of things to list or issues to create (0 means unlimited)")
githubTokenFile = flag.String("ghtokenfile", "",
"path to file containing GitHub access token (for creating issues)")
knownModuleFile = flag.String("known-module-file", "", "file with list of all known modules")
)
// Config for both the server and the command-line tool.
var cfg worker.Config
func init() {
flag.StringVar(&cfg.Project, "project", os.Getenv("GOOGLE_CLOUD_PROJECT"), "project ID (required)")
flag.StringVar(&cfg.Namespace, "namespace", os.Getenv("VULN_WORKER_NAMESPACE"), "Firestore namespace (required)")
flag.BoolVar(&cfg.UseErrorReporting, "report-errors", os.Getenv("VULN_WORKER_REPORT_ERRORS") == "true",
"use the error reporting API")
flag.StringVar(&cfg.IssueRepo, "issue-repo", os.Getenv("VULN_WORKER_ISSUE_REPO"), "repo to create issues in")
}
const pkgsiteURL = "https://pkg.go.dev"
func main() {
flag.Usage = func() {
out := flag.CommandLine.Output()
fmt.Fprintln(out, "usage:")
fmt.Fprintln(out, "worker FLAGS")
fmt.Fprintln(out, " run as a server, listening at the PORT env var")
fmt.Fprintln(out, "worker FLAGS SUBCOMMAND ...")
fmt.Fprintln(out, " run as a command-line tool, executing SUBCOMMAND")
fmt.Fprintln(out, " subcommands:")
fmt.Fprintln(out, " update COMMIT: perform an update operation")
fmt.Fprintln(out, " list-updates: display info about update operations")
fmt.Fprintln(out, " list-cves TRIAGE_STATE: display info about CVE records")
fmt.Fprintln(out, " create-issues: create issues for CVEs that need them")
fmt.Fprintln(out, " show ID1 ID2 ...: display CVE records")
fmt.Fprintln(out, "flags:")
flag.PrintDefaults()
}
flag.Parse()
if *githubTokenFile != "" {
data, err := os.ReadFile(*githubTokenFile)
if err != nil {
die("%v", err)
}
cfg.GitHubAccessToken = strings.TrimSpace(string(data))
} else {
cfg.GitHubAccessToken = os.Getenv("VULN_GITHUB_ACCESS_TOKEN")
}
if err := cfg.Validate(); err != nil {
dieWithUsage("%v", err)
}
ctx := context.Background()
if img := os.Getenv("DOCKER_IMAGE"); img != "" {
log.Infof(ctx, "running in docker image %s", img)
}
log.Infof(ctx, "config: project=%s, namespace=%s, issueRepo=%s", cfg.Project, cfg.Namespace, cfg.IssueRepo)
var err error
cfg.Store, err = store.NewFireStore(ctx, cfg.Project, cfg.Namespace, "")
if err != nil {
die("firestore: %v", err)
}
if flag.NArg() > 0 {
err = runCommandLine(ctx)
} else {
err = runServer(ctx)
}
if err != nil {
dieWithUsage("%v", err)
}
}
func runServer(ctx context.Context) error {
if os.Getenv("PORT") == "" {
return errors.New("need PORT")
}
if _, err := worker.NewServer(ctx, cfg); err != nil {
return err
}
addr := ":" + os.Getenv("PORT")
log.Infof(ctx, "Listening on addr %s", addr)
return fmt.Errorf("listening: %v", http.ListenAndServe(addr, nil))
}
const timeFormat = "2006/01/02 15:04:05"
func runCommandLine(ctx context.Context) error {
switch flag.Arg(0) {
case "list-updates":
return listUpdatesCommand(ctx)
case "list-cves":
return listCVEsCommand(ctx, flag.Arg(1))
case "update":
if flag.NArg() != 2 {
return errors.New("usage: update COMMIT")
}
return updateCommand(ctx, flag.Arg(1))
case "create-issues":
return createIssuesCommand(ctx)
case "show":
return showCommand(ctx, flag.Args()[1:])
default:
return fmt.Errorf("unknown command: %q", flag.Arg(1))
}
}
func listUpdatesCommand(ctx context.Context) error {
recs, err := cfg.Store.ListCommitUpdateRecords(ctx, 0)
if err != nil {
return err
}
tw := tabwriter.NewWriter(os.Stdout, 1, 8, 2, ' ', 0)
fmt.Fprintf(tw, "Start\tEnd\tCommit\tID\tCVEs Processed\n")
for i, r := range recs {
if *limit > 0 && i >= *limit {
break
}
endTime := "unfinished"
if !r.EndedAt.IsZero() {
endTime = r.EndedAt.In(time.Local).Format(timeFormat)
}
fmt.Fprintf(tw, "%s\t%s\t%s\t%s\t%d/%d (added %d, modified %d)\n",
r.StartedAt.In(time.Local).Format(timeFormat),
endTime,
r.CommitHash,
r.ID,
r.NumProcessed, r.NumTotal, r.NumAdded, r.NumModified)
}
return tw.Flush()
}
func listCVEsCommand(ctx context.Context, triageState string) error {
ts := store.TriageState(triageState)
if err := ts.Validate(); err != nil {
return err
}
crs, err := cfg.Store.ListCVE4RecordsWithTriageState(ctx, ts)
if err != nil {
return err
}
tw := tabwriter.NewWriter(os.Stdout, 1, 8, 2, ' ', 0)
fmt.Fprintf(tw, "ID\tCVEState\tCommit\tReason\tModule\tIssue\tIssue Created\n")
for i, r := range crs {
if *limit > 0 && i >= *limit {
break
}
fmt.Fprintf(tw, "%s\t%s\t%s\t%s\t%s\t%s\t%s\n",
r.ID, r.CVEState, r.CommitHash, r.TriageStateReason, r.Module, r.IssueReference, worker.FormatTime(r.IssueCreatedAt))
}
return tw.Flush()
}
func updateCommand(ctx context.Context, commitHash string) error {
repoPath := cvelistrepo.URLv4
if *localRepoPath != "" {
repoPath = *localRepoPath
}
pc := pkgsite.Default()
if *knownModuleFile != "" {
known, err := readKnownModules(*knownModuleFile)
if err != nil {
return err
}
pc.SetKnownModules(known)
}
rc, err := report.NewDefaultClient(ctx)
if err != nil {
return err
}
err = worker.UpdateCVEsAtCommit(ctx, repoPath, commitHash, cfg.Store, pc, rc, *force)
if cerr := new(worker.CheckUpdateError); errors.As(err, &cerr) {
return fmt.Errorf("%w; use -force to override", cerr)
}
if err != nil {
return err
}
if cfg.GitHubAccessToken == "" {
fmt.Printf("Missing GitHub access token; not updating GH security advisories.\n")
return nil
}
ghsaClient := ghsa.NewClient(ctx, cfg.GitHubAccessToken)
listSAs := func(ctx context.Context, since time.Time) ([]*ghsa.SecurityAdvisory, error) {
return ghsaClient.List(ctx, since)
}
_, err = worker.UpdateGHSAs(ctx, listSAs, cfg.Store)
return err
}
func readKnownModules(filename string) ([]string, error) {
f, err := os.Open(filename)
if err != nil {
return nil, err
}
defer f.Close()
var mods []string
scan := bufio.NewScanner(f)
for scan.Scan() {
line := strings.TrimSpace(scan.Text())
if line == "" || line[0] == '#' {
continue
}
mods = append(mods, line)
}
if err := scan.Err(); err != nil {
return nil, err
}
fmt.Printf("%d known modules\n", len(mods))
return mods, nil
}
func createIssuesCommand(ctx context.Context) error {
if cfg.IssueRepo == "" {
return errors.New("need -issue-repo")
}
if cfg.GitHubAccessToken == "" {
return errors.New("need -ghtokenfile")
}
owner, repoName, err := gitrepo.ParseGitHubRepo(cfg.IssueRepo)
if err != nil {
return err
}
client := issues.NewClient(ctx, &issues.Config{Owner: owner, Repo: repoName, Token: cfg.GitHubAccessToken})
rc, err := report.NewDefaultClient(ctx)
if err != nil {
return err
}
pc := proxy.NewDefaultClient()
return worker.CreateIssues(ctx, cfg.Store, client, pc, rc, *limit)
}
func showCommand(ctx context.Context, ids []string) error {
for _, id := range ids {
r, err := cfg.Store.GetRecord(ctx, id)
if err != nil {
return err
}
if r == nil {
fmt.Printf("%s not found\n", id)
} else {
// Display as JSON because it's an easy way to get nice formatting.
j, err := json.MarshalIndent(r, "", "\t")
if err != nil {
return err
}
fmt.Printf("%s\n", j)
}
}
return nil
}
func die(format string, args ...interface{}) {
fmt.Fprintf(os.Stderr, format, args...)
fmt.Fprintln(os.Stderr)
os.Exit(1)
}
func dieWithUsage(format string, args ...interface{}) {
fmt.Fprintf(os.Stderr, format, args...)
fmt.Fprintln(os.Stderr)
flag.Usage()
os.Exit(1)
}
|
vulnreport
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/cmd/vulnreport/commit.go
|
// Copyright 2024 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"cmp"
"context"
"errors"
"flag"
"fmt"
"path/filepath"
"slices"
"strings"
"github.com/go-git/go-git/v5"
"golang.org/x/exp/maps"
"golang.org/x/vulndb/cmd/vulnreport/log"
"golang.org/x/vulndb/internal/report"
)
var (
// Note: It would be probably be ideal if -dry did not stage
// the files, but the logic to determine the commit message
// currently depends on the status of the staging area.
dry = flag.Bool("dry", false, "for commit & create-excluded, stage but do not commit files")
batch = flag.Int("batch", 0, "for commit, create batched commits of the specified size")
)
type commit struct {
*committer
*fixer
*filenameParser
toCommit []*yamlReport
// only commit reports with this review status
reviewStatus report.ReviewStatus
}
func (commit) name() string { return "commit" }
func (commit) usage() (string, string) {
const desc = "creates new commits for YAML reports"
return filenameArgs, desc
}
func (c *commit) setup(ctx context.Context, env environment) error {
c.committer = new(committer)
c.fixer = new(fixer)
c.filenameParser = new(filenameParser)
rs, ok := report.ToReviewStatus(*reviewStatus)
if !ok {
return fmt.Errorf("invalid -status=%s", rs)
}
c.reviewStatus = rs
return setupAll(ctx, env, c.committer, c.fixer, c.filenameParser)
}
func (c *commit) parseArgs(ctx context.Context, args []string) (filenames []string, _ error) {
if len(args) != 0 {
return c.filenameParser.parseArgs(ctx, args)
}
// With no arguments, operate on all the changed/added YAML files.
statusMap, err := c.gitStatus()
if err != nil {
return nil, err
}
for fname, status := range statusMap {
if report.IsYAMLReport(fname) && status.Worktree != git.Deleted {
filenames = append(filenames, fname)
}
}
if len(filenames) == 0 {
return nil, fmt.Errorf("no arguments provided, and no added/changed YAML files found")
}
return filenames, nil
}
func (c *commit) close() (err error) {
if len(c.toCommit) != 0 {
batchSize := *batch
slices.SortFunc(c.toCommit, func(a, b *yamlReport) int {
return cmp.Compare(a.ID, b.ID)
})
for start := 0; start < len(c.toCommit); start += batchSize {
end := min(start+batchSize, len(c.toCommit))
log.Infof("committing batch %s-%s", c.toCommit[start].ID, c.toCommit[end-1].ID)
if cerr := c.commit(c.toCommit[start:end]...); err != nil {
err = errors.Join(err, cerr)
}
}
}
return err
}
func (c *commit) skip(input any) string {
r := input.(*yamlReport)
if c.reviewStatus == 0 {
return ""
}
// If the -status=<REVIEW_STATUS> flag is specified, skip reports
// with a different status.
if r.ReviewStatus != c.reviewStatus {
return fmt.Sprintf("review status is %s", r.ReviewStatus)
}
return ""
}
func (c *commit) run(ctx context.Context, input any) error {
r := input.(*yamlReport)
// Clean up the report file and ensure derived files are up-to-date.
// Stop if there any problems.
if err := c.fixAndWriteAll(ctx, r, false); err != nil {
return err
}
if *batch > 0 {
c.toCommit = append(c.toCommit, r)
return nil
}
return c.commit(r)
}
type committer struct {
repo *git.Repository
}
func (c *committer) setup(ctx context.Context, env environment) error {
repo, err := env.ReportRepo(ctx)
if err != nil {
return err
}
c.repo = repo
return nil
}
func (c *committer) gitStatus() (git.Status, error) {
w, err := c.repo.Worktree()
if err != nil {
return nil, err
}
return w.Status()
}
func (c *committer) commit(reports ...*yamlReport) error {
var globs []string
for _, r := range reports {
globs = append(globs, fmt.Sprintf("*%s*", r.ID))
}
// Stage all the files.
if err := gitAdd(globs...); err != nil {
return err
}
status, err := c.gitStatus()
if err != nil {
return err
}
msg, err := newCommitMessage(status, reports)
if err != nil {
return err
}
if *dry {
log.Outf("would commit with message:\n\n%s", msg)
return nil
}
// Commit the files, allowing the user to edit the default commit message.
return gitCommit(msg, globs...)
}
// actionPhrases determines the action phrases to use to describe what is happening
// in the commit, based on the status of the git staging area.
func actionPhrases(status git.Status, r *yamlReport) (reportAction, issueAction string, _ error) {
const (
updateIssueAction = "Updates"
fixIssueAction = "Fixes"
addReportAction = "add"
deleteReportAction = "delete"
unexcludeReportAction = "unexclude"
updateReportAction = "update"
)
stat := status.File(r.Filename).Staging
switch stat {
case git.Deleted:
if r.IsExcluded() {
// It's theoretically OK to just delete an excluded report,
// because they aren't published anywhere.
return deleteReportAction, updateIssueAction, nil
}
// It's not OK to delete a regular report. These can be withdrawn but not deleted.
return "", "", fmt.Errorf("cannot delete regular report %s (use withdrawn field instead)", r.Filename)
case git.Added, git.Untracked:
switch {
case status.File(filepath.Join(report.ExcludedDir, r.ID+".yaml")).Staging == git.Deleted:
// If a corresponding excluded report is being deleted,
// this is an unexclude action.
return unexcludeReportAction, updateIssueAction, nil
case r.CVEMetadata != nil:
// Update instead of fixing the issue because we still need
// to manually publish the CVE record after submitting the CL.
return addReportAction, updateIssueAction, nil
default:
return addReportAction, fixIssueAction, nil
}
case git.Modified:
return updateReportAction, updateIssueAction, nil
default:
return "", "", fmt.Errorf("internal error: could not determine actions for %s (stat: %v)", r.ID, stat)
}
}
func newCommitMessage(status git.Status, reports []*yamlReport) (string, error) {
actions := make(map[string][]*yamlReport)
issueActions := make(map[string][]*yamlReport)
for _, r := range reports {
reportAction, issueAction, err := actionPhrases(status, r)
if err != nil {
return "", err
}
actions[reportAction] = append(actions[reportAction], r)
issueActions[issueAction] = append(issueActions[issueAction], r)
}
b := new(strings.Builder)
var titleSegments, bodySegments, issueSegments []string
for action, rs := range actions {
reportDesc := fmt.Sprintf("%d reports", len(rs))
if len(rs) == 1 {
reportDesc = rs[0].ID
}
titleSegments = append(titleSegments, fmt.Sprintf("%s %s", action, reportDesc))
}
folders := make(map[string]bool)
for issueAction, rs := range issueActions {
for _, r := range rs {
folder, _, issueID, err := report.ParseFilepath(r.Filename)
if err != nil {
return "", err
}
folders[folder] = true
bodySegments = append(bodySegments, r.Filename)
issueSegments = append(issueSegments, fmt.Sprintf("%s golang/vulndb#%d", issueAction, issueID))
}
}
// title
b.WriteString(fmt.Sprintf("%s: %s\n", strings.Join(maps.Keys(folders), ","), strings.Join(titleSegments, ", ")))
// body
b.WriteString(fmt.Sprintf("%s%s\n\n", listItem, strings.Join(bodySegments, listItem)))
// issues
b.WriteString(strings.Join(issueSegments, "\n"))
return b.String(), nil
}
const listItem = "\n - "
|
vulnreport
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/cmd/vulnreport/xref.go
|
// Copyright 2024 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"context"
"fmt"
"golang.org/x/exp/constraints"
"golang.org/x/exp/slices"
"golang.org/x/vulndb/cmd/vulnreport/log"
"golang.org/x/vulndb/cmd/vulnreport/priority"
"golang.org/x/vulndb/internal/report"
)
type xref struct {
*xrefer
*filenameParser
noSkip
}
func (xref) name() string { return "xref" }
func (xref) usage() (string, string) {
const desc = "prints cross references for YAML reports"
return filenameArgs, desc
}
func (x *xref) setup(ctx context.Context, env environment) error {
x.xrefer = new(xrefer)
x.filenameParser = new(filenameParser)
return setupAll(ctx, env, x.xrefer, x.filenameParser)
}
func (x *xref) close() error { return nil }
// xref returns cross-references for a report (information about other reports
// for the same CVE, GHSA, or module), and the priority of a report.
func (x *xref) run(ctx context.Context, input any) (err error) {
r := input.(*yamlReport)
if xrefs := x.xref(r); len(xrefs) > 0 {
log.Out(xrefs)
} else {
log.Infof("%s: no xrefs found", r.Filename)
}
pr, notGo := x.reportPriority(r.Report)
log.Outf("%s: priority is %s\n - %s", r.ID, pr.Priority, pr.Reason)
if notGo != nil {
log.Outf("%s is likely not Go\n - %s", r.ID, notGo.Reason)
}
return nil
}
func (x *xrefer) setup(ctx context.Context, env environment) (err error) {
repo, err := env.ReportRepo(ctx)
if err != nil {
return err
}
rc, err := report.NewClient(repo)
if err != nil {
return err
}
x.rc = rc
mm, err := env.ModuleMap()
if err != nil {
return err
}
x.moduleMap = mm
return nil
}
type xrefer struct {
rc *report.Client
moduleMap map[string]int
}
func (x *xrefer) xref(r *yamlReport) string {
aliasTitle := fmt.Sprintf("%s: found possible duplicates", r.ID)
moduleTitle := fmt.Sprintf("%s: found module xrefs", r.ID)
return x.rc.XRef(r.Report).ToString(aliasTitle, moduleTitle, "")
}
func (x *xrefer) modulePriority(modulePath string) (*priority.Result, *priority.NotGoResult) {
return priority.Analyze(modulePath, x.rc.ReportsByModule(modulePath), x.moduleMap)
}
func (x *xrefer) reportPriority(r *report.Report) (*priority.Result, *priority.NotGoResult) {
return priority.AnalyzeReport(r, x.rc, x.moduleMap)
}
func sorted[E constraints.Ordered](s []E) []E {
s = slices.Clone(s)
slices.Sort(s)
return s
}
|
vulnreport
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/cmd/vulnreport/triage.go
|
// Copyright 2024 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"context"
_ "embed"
"fmt"
"path/filepath"
"strconv"
"strings"
"sync"
"golang.org/x/exp/slices"
"golang.org/x/vulndb/cmd/vulnreport/log"
"golang.org/x/vulndb/cmd/vulnreport/priority"
"golang.org/x/vulndb/internal/issues"
)
type triage struct {
*xrefer
*issueParser
*fixer
mu sync.Mutex // protects aliasesToIssues and stats
aliasesToIssues map[string][]int
stats []issuesList
}
func (*triage) name() string { return "triage" }
func (*triage) usage() (string, string) {
const desc = "determines priority and finds likely duplicates of the given Github issue (with no args, looks at all open issues)"
return "<no args> | " + ghIssueArgs, desc
}
func (t *triage) close() error {
log.Outf("triaged %d issues:%s%s",
len(t.stats[statTriaged]), listItem, strings.Join(toStrings(t.stats[:len(t.stats)-1]), listItem))
// Print the command to create all high priority reports.
if len(t.stats[statHighPriority]) > 0 {
log.Outf("helpful commands:\n $ vulnreport create %s", t.stats[statHighPriority].issNums())
}
return nil
}
func toStrings(stats []issuesList) (strs []string) {
for i, s := range stats {
strs = append(strs, fmt.Sprintf("%d %s", len(s), statNames[i]))
}
return strs
}
func (t *triage) setup(ctx context.Context, env environment) error {
t.aliasesToIssues = make(map[string][]int)
t.stats = make([]issuesList, len(statNames))
t.issueParser = new(issueParser)
t.fixer = new(fixer)
t.xrefer = new(xrefer)
if err := setupAll(ctx, env, t.issueParser, t.fixer, t.xrefer); err != nil {
return err
}
log.Info("creating alias map for open issues")
open, err := t.openIssues(ctx)
if err != nil {
return err
}
for _, iss := range open {
aliases := t.aliases(ctx, iss)
for _, a := range aliases {
t.addAlias(a, iss.Number)
}
}
return nil
}
func (t *triage) skip(input any) string {
iss := input.(*issues.Issue)
if iss.HasLabel(labelDirect) {
return "direct external report"
}
if isExcluded(iss) {
return "excluded"
}
if !*force && iss.HasLabel(labelTriaged) {
return "already triaged; use -f to force re-triage"
}
return skip(iss, t.xrefer)
}
func (t *triage) run(ctx context.Context, input any) (err error) {
iss := input.(*issues.Issue)
t.triage(ctx, iss)
return nil
}
func (t *triage) triage(ctx context.Context, iss *issues.Issue) {
labels := []string{labelTriaged}
defer func() {
// Preserve any existing labels.
labels = append(labels, iss.Labels...)
slices.Sort(labels)
labels = slices.Compact(labels)
if *dry {
log.Infof("issue #%d: would set labels: [%s]", iss.Number, strings.Join(labels, ", "))
} else {
if err := t.ic.SetLabels(ctx, iss.Number, labels); err != nil {
log.Warnf("issue #%d: could not auto-set label(s) %s", iss.Number, labels)
}
}
t.addStat(iss, statTriaged, "")
}()
xrefs := t.findDuplicates(ctx, iss)
if len(xrefs) != 0 {
var strs []string
for ref, aliases := range xrefs {
strs = append(strs, fmt.Sprintf("#%d shares alias(es) %s with %s", iss.Number,
strings.Join(aliases, ", "),
filepath.ToSlash(ref)))
}
t.addStat(iss, statDuplicate, strings.Join(strs, listItem))
labels = append(labels, labelPossibleDuplicate)
}
mp := t.canonicalModule(modulePath(iss))
pr, notGo := t.modulePriority(mp)
t.addStat(iss, toStat(pr.Priority), pr.Reason)
if notGo != nil {
t.addStat(iss, statNotGo, notGo.Reason)
labels = append(labels, labelPossiblyNotGo)
}
if pr.Priority == priority.High {
labels = append(labels, labelHighPriority)
}
}
func toStat(p priority.Priority) int {
switch p {
case priority.Unknown:
return statUnknownPriority
case priority.Low:
return statLowPriority
case priority.High:
return statHighPriority
default:
panic(fmt.Sprintf("unknown priority %d", p))
}
}
func (t *triage) aliases(ctx context.Context, iss *issues.Issue) []string {
aliases := aliases(iss)
if len(aliases) == 0 {
return nil
}
return t.allAliases(ctx, aliases)
}
func (t *triage) findDuplicates(ctx context.Context, iss *issues.Issue) map[string][]string {
aliases := t.aliases(ctx, iss)
if len(aliases) == 0 {
log.Infof("issue #%d: skipping duplicate search (no aliases found)", iss.Number)
return nil
}
xrefs := make(map[string][]string)
for _, a := range aliases {
// Find existing reports with this alias.
if reports := t.rc.ReportsByAlias(a); len(reports) != 0 {
for _, r := range reports {
fname, err := r.YAMLFilename()
if err != nil {
fname = r.ID
}
xrefs[fname] = append(xrefs[fname], a)
}
}
// Find other open issues with this alias.
for _, dup := range t.lookupAlias(a) {
if iss.Number == dup {
continue
}
ref := t.ic.Reference(dup)
xrefs[ref] = append(xrefs[ref], a)
}
}
return xrefs
}
func (t *triage) lookupAlias(a string) []int {
t.mu.Lock()
defer t.mu.Unlock()
return t.aliasesToIssues[a]
}
func (t *triage) addAlias(a string, n int) {
t.mu.Lock()
defer t.mu.Unlock()
t.aliasesToIssues[a] = append(t.aliasesToIssues[a], n)
}
func (t *triage) addStat(iss *issues.Issue, stat int, reason string) {
t.mu.Lock()
defer t.mu.Unlock()
var lg func(string, ...any)
switch stat {
case statTriaged:
// no-op
lg = func(string, ...any) {}
case statLowPriority:
lg = log.Infof
case statHighPriority, statDuplicate, statNotGo:
lg = log.Outf
case statUnknownPriority:
lg = log.Warnf
default:
panic(fmt.Sprintf("BUG: unknown stat: %d", stat))
}
t.stats[stat] = append(t.stats[stat], iss)
lg("issue %s is %s%s%s", t.ic.Reference(iss.Number), statNames[stat], listItem, reason)
}
const (
statHighPriority = iota
statLowPriority
statUnknownPriority
statDuplicate
statNotGo
statTriaged
)
var statNames = []string{
statHighPriority: "high priority",
statLowPriority: "low priority",
statUnknownPriority: "unknown priority",
statDuplicate: "likely duplicate",
statNotGo: "possibly not Go",
statTriaged: "triaged",
}
type issuesList []*issues.Issue
func (i issuesList) issNums() string {
var is []string
for _, iss := range i {
is = append(is, strconv.Itoa(iss.Number))
}
return strings.Join(is, " ")
}
|
vulnreport
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/cmd/vulnreport/suggest.go
|
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"context"
"flag"
"fmt"
"golang.org/x/vulndb/cmd/vulnreport/log"
"golang.org/x/vulndb/internal/genai"
"golang.org/x/vulndb/internal/report"
)
var (
interactive = flag.Bool("i", false, "for suggest, interactive mode")
numSuggestions = flag.Int("n", 1, "for suggest, the number of suggestions to generate (>1 can be slow)")
)
type suggest struct {
*suggester
*filenameParser
*fileWriter
noSkip
}
func (suggest) name() string { return "suggest" }
func (suggest) usage() (string, string) {
const desc = "(EXPERIMENTAL) use AI to suggest summary and description for YAML reports"
return filenameArgs, desc
}
func (s *suggest) setup(ctx context.Context, env environment) error {
s.suggester = new(suggester)
s.filenameParser = new(filenameParser)
s.fileWriter = new(fileWriter)
return setupAll(ctx, env, s.suggester, s.filenameParser, s.fileWriter)
}
func (s *suggest) run(ctx context.Context, input any) (err error) {
r := input.(*yamlReport)
log.Info("contacting the Gemini API...")
suggestions, err := s.suggest(ctx, r, *numSuggestions)
if err != nil {
return err
}
found := len(suggestions)
log.Outf("== AI-generated suggestions for report %s ==\n", r.ID)
for i, sugg := range suggestions {
log.Outf("\nSuggestion %d/%d\nsummary: %s\ndescription: %s\n",
i+1, found, sugg.Summary, sugg.Description)
// In interactive mode, allow user to accept the suggestion,
// see the next one, or quit.
// TODO(tatianabradley): In interactive mode, call the API as requested
// instead of upfront.
if *interactive {
if i == found-1 {
log.Outf("\naccept or quit? (a=accept/Q=quit) ")
} else {
log.Outf("\naccept, see next suggestion, or quit? (a=accept/n=next/Q=quit) ")
}
var choice string
if _, err := fmt.Scanln(&choice); err != nil {
return err
}
switch choice {
case "a":
r.applySuggestion(sugg)
if err := s.write(r); err != nil {
log.Err(err)
}
return nil
case "n":
continue
default:
return nil
}
}
}
return nil
}
type suggester struct {
ac *genai.GeminiClient
}
func (s *suggester) setup(ctx context.Context, _ environment) error {
if s == nil {
return nil
}
ac, err := genai.NewGeminiClient(ctx)
if err != nil {
return err
}
s.ac = ac
return nil
}
func (s *suggester) close() error {
if s != nil && s.ac != nil {
return s.ac.Close()
}
return nil
}
func (s *suggester) suggest(ctx context.Context, r *yamlReport, max int) (suggestions []*genai.Suggestion, err error) {
attempts := 0
maxAttempts := max + 2
for len(suggestions) < max && attempts < maxAttempts {
s, err := genai.Suggest(ctx, s.ac, &genai.Input{
Module: r.Modules[0].Module,
Description: r.Description.String(),
})
if err != nil {
return nil, fmt.Errorf("GenAI API error: %s", err)
}
suggestions = append(suggestions, s...)
attempts++
}
if len(suggestions) > max {
suggestions = suggestions[:max]
}
found := len(suggestions)
if found == 0 {
return nil, fmt.Errorf("could not generate any valid suggestions for report %s after %d attempts", r.ID, attempts)
}
return suggestions, nil
}
func (r *yamlReport) applySuggestion(s *genai.Suggestion) {
r.Summary = report.Summary(s.Summary)
r.Description = report.Description(s.Description)
r.FixText()
}
|
vulnreport
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/cmd/vulnreport/creator.go
|
// Copyright 2024 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"context"
"fmt"
"net/http"
"os"
"strings"
"golang.org/x/exp/slices"
"golang.org/x/vulndb/cmd/vulnreport/log"
"golang.org/x/vulndb/cmd/vulnreport/priority"
"golang.org/x/vulndb/internal/idstr"
"golang.org/x/vulndb/internal/issues"
"golang.org/x/vulndb/internal/osv"
"golang.org/x/vulndb/internal/report"
"golang.org/x/vulndb/internal/symbols"
)
type creator struct {
assignee string
created []*yamlReport
// If non-zero, use this review status
// instead of the default for new reports.
reviewStatus report.ReviewStatus
*fixer
*xrefer
*suggester
}
func (c *creator) setup(ctx context.Context, env environment) (err error) {
user := *user
if user == "" {
user = os.Getenv("GITHUB_USER")
}
c.assignee = user
rs, ok := report.ToReviewStatus(*reviewStatus)
if !ok {
return fmt.Errorf("invalid -status=%s", rs)
}
c.reviewStatus = rs
c.fixer = new(fixer)
c.xrefer = new(xrefer)
if *useAI {
c.suggester = new(suggester)
}
return setupAll(ctx, env, c.fixer, c.xrefer, c.suggester)
}
func (c *creator) skip(input any) string {
iss := input.(*issues.Issue)
if c.assignee != "" && iss.Assignee != c.assignee {
return fmt.Sprintf("assignee = %q, not %q", iss.Assignee, c.assignee)
}
return skip(iss, c.xrefer)
}
func skip(iss *issues.Issue, x *xrefer) string {
if iss.HasLabel(labelOutOfScope) {
return "out of scope"
}
if iss.HasLabel(labelDuplicate) {
return "duplicate issue"
}
if iss.HasLabel(labelSuggestedEdit) {
return "suggested edit"
}
// indicates that there is already a report for this
// vuln but the report needs to be updated
if iss.HasLabel(labelNeedsAlias) {
return "existing report needs alias"
}
if iss.HasLabel(labelPossibleDuplicate) {
return "possible duplicate"
}
if iss.HasLabel(labelPossiblyNotGo) {
return "possibly not Go"
}
if x.rc.HasReport(iss.Number) {
return "already has report"
}
return ""
}
func (c *creator) reportFromIssue(ctx context.Context, iss *issues.Issue) error {
r, err := c.reportFromMeta(ctx, &reportMeta{
id: iss.NewGoID(),
excluded: excludedReason(iss),
modulePath: modulePath(iss),
aliases: aliases(iss),
reviewStatus: reviewStatusOf(iss, c.reviewStatus),
originalCVE: originalCVE(iss),
})
if err != nil {
return err
}
return c.write(ctx, r)
}
func originalCVE(iss *issues.Issue) string {
aliases := aliases(iss)
if iss.HasLabel(labelFirstParty) && len(aliases) == 1 && idstr.IsCVE(aliases[0]) {
return aliases[0]
}
return ""
}
func reviewStatusOf(iss *issues.Issue, reviewStatus report.ReviewStatus) report.ReviewStatus {
d := defaultReviewStatus(iss)
// If a valid review status is provided, it overrides the priority label.
if reviewStatus != 0 {
if d != reviewStatus {
log.Warnf("issue #%d: should be %s based on label(s) but this was overridden with the -status=%s flag", iss.Number, d, reviewStatus)
}
return reviewStatus
}
return d
}
func defaultReviewStatus(iss *issues.Issue) report.ReviewStatus {
if iss.HasLabel(labelHighPriority) ||
iss.HasLabel(labelDirect) ||
iss.HasLabel(labelFirstParty) {
return report.Reviewed
}
return report.Unreviewed
}
func (c *creator) metaToSource(ctx context.Context, meta *reportMeta) report.Source {
if cveID := meta.originalCVE; cveID != "" {
log.Infof("%s: creating original report for Go-CNA-assigned %s", meta.id, cveID)
return report.OriginalCVE(cveID)
}
if src := c.sourceFromBestAlias(ctx, meta.aliases, *preferCVE); src != nil {
log.Infof("%s: picked %s as best source alias (from [%s])", meta.id, src.SourceID(),
strings.Join(meta.aliases, ", "))
return src
}
log.Infof("%s: no suitable alias found, creating basic report", meta.id)
return report.Original()
}
func (c *creator) rawReport(ctx context.Context, meta *reportMeta) *report.Report {
return report.New(c.metaToSource(ctx, meta), c.pxc,
report.WithGoID(meta.id),
report.WithModulePath(meta.modulePath),
report.WithAliases(meta.aliases),
report.WithReviewStatus(meta.reviewStatus),
report.WithUnexcluded(meta.unexcluded),
)
}
func (c *creator) reportFromMeta(ctx context.Context, meta *reportMeta) (*yamlReport, error) {
// Find the underlying module if the "module" provided is actually a package path.
if module, err := c.pxc.FindModule(meta.modulePath); err == nil { // no error
meta.modulePath = module
}
meta.aliases = c.allAliases(ctx, meta.aliases)
raw := c.rawReport(ctx, meta)
if meta.excluded != "" {
raw = &report.Report{
ID: meta.id,
Modules: []*report.Module{
{
Module: meta.modulePath,
},
},
Excluded: meta.excluded,
CVEs: raw.CVEs,
GHSAs: raw.GHSAs,
}
}
// The initial quick triage algorithm doesn't know about all
// affected modules, so double check the priority after the
// report is created.
if raw.IsUnreviewed() {
pr, _ := c.reportPriority(raw)
if pr.Priority == priority.High {
log.Warnf("%s: re-generating; vuln is high priority and should be REVIEWED; reason: %s", raw.ID, pr.Reason)
meta.reviewStatus = report.Reviewed
raw = c.rawReport(ctx, meta)
}
}
fname, err := raw.YAMLFilename()
if err != nil {
return nil, err
}
r := &yamlReport{Report: raw, Filename: fname}
// Find any additional aliases referenced by the source aliases.
r.addMissingAliases(ctx, c.aliasFinder)
if c.suggester != nil {
suggestions, err := c.suggest(ctx, r, 1)
if err != nil {
r.AddNote(report.NoteTypeCreate, "failed to get AI-generated suggestions")
log.Warnf("%s: failed to get AI-generated suggestions: %v", r.ID, err)
} else {
log.Infof("%s: applying AI-generated suggestion", r.ID)
r.applySuggestion(suggestions[0])
}
}
if *populateSymbols {
log.Infof("%s: attempting to auto-populate symbols (this may take a while...)", r.ID)
if err := symbols.Populate(r.Report, false); err != nil {
r.AddNote(report.NoteTypeCreate, "failed to auto-populate symbols")
log.Warnf("%s: could not auto-populate symbols: %s", r.ID, err)
} else {
if err := r.checkSymbols(); err != nil {
log.Warnf("%s: auto-populated symbols have error(s): %s", r.ID, err)
}
}
}
switch {
case raw.IsExcluded():
// nothing
case raw.IsUnreviewed():
r.removeUnreachableRefs()
default:
// Regular, full-length reports.
addTODOs(r)
if xrefs := c.xref(r); len(xrefs) != 0 {
log.Infof("%s: found cross-references: %s", r.ID, xrefs)
}
}
return r, nil
}
func (r *yamlReport) removeUnreachableRefs() {
r.Report.References = slices.DeleteFunc(r.Report.References, func(r *report.Reference) bool {
resp, err := http.Head(r.URL)
if err != nil {
return true
}
defer resp.Body.Close()
return resp.StatusCode == http.StatusNotFound
})
}
func (c *creator) write(ctx context.Context, r *yamlReport) error {
if r.IsReviewed() || r.IsExcluded() {
if err := c.fileWriter.write(r); err != nil {
return err
}
} else { // unreviewed
addNotes := true
if err := c.fixAndWriteAll(ctx, r, addNotes); err != nil {
return err
}
}
c.created = append(c.created, r)
return nil
}
const (
labelDuplicate = "duplicate"
labelDirect = "Direct External Report"
labelSuggestedEdit = "Suggested Edit"
labelNeedsAlias = "NeedsAlias"
labelTriaged = "triaged"
labelHighPriority = "high priority"
labelFirstParty = "first party"
labelPossibleDuplicate = "possible duplicate"
labelPossiblyNotGo = "possibly not Go"
labelOutOfScope = "excluded: OUT_OF_SCOPE"
)
func excludedReason(iss *issues.Issue) report.ExcludedReason {
for _, label := range iss.Labels {
if reason, ok := report.FromLabel(label); ok {
return reason
}
}
return ""
}
func modulePath(iss *issues.Issue) string {
for _, p := range strings.Fields(iss.Title) {
if p == "x/vulndb:" {
continue
}
if strings.HasSuffix(p, ":") || strings.Contains(p, "/") {
// Remove backslashes.
return strings.ReplaceAll(strings.TrimSuffix(p, ":"), "\"", "")
}
}
return ""
}
func aliases(iss *issues.Issue) (aliases []string) {
for _, p := range strings.Fields(iss.Title) {
if idstr.IsAliasType(p) {
aliases = append(aliases, strings.TrimSuffix(p, ","))
}
}
return aliases
}
// Data that can be combined with a source vulnerability
// to create a new report.
type reportMeta struct {
id string
modulePath string
aliases []string
excluded, unexcluded report.ExcludedReason
reviewStatus report.ReviewStatus
originalCVE string
}
const todo = "TODO: "
// addTODOs adds "TODO" comments to unfilled fields of r.
func addTODOs(r *yamlReport) {
if r.Excluded != "" {
return
}
if len(r.Modules) == 0 {
r.Modules = append(r.Modules, &report.Module{
Packages: []*report.Package{{}},
})
}
for _, m := range r.Modules {
if m.Module == "" {
m.Module = todo + "affected module path"
}
if len(m.Versions) == 0 {
m.Versions = report.Versions{
report.Introduced(todo + "introduced version (blank if unknown)"),
report.Fixed(todo + "fixed version"),
}
}
if m.VulnerableAt == nil {
m.VulnerableAt = report.VulnerableAt(todo + "a version at which the package is vulnerable")
}
if len(m.Packages) == 0 {
m.Packages = []*report.Package{
{
Package: todo + "affected package path(s) - blank if all",
},
}
}
for _, p := range m.Packages {
if p.Package == "" {
p.Package = todo + "affected package path"
}
if len(p.Symbols) == 0 {
p.Symbols = []string{todo + "affected symbol(s) - blank if all"}
}
}
}
if r.Summary == "" {
r.Summary = todo + "short (one phrase) summary of the form '<Problem> in <module>(s)'"
}
if r.Description == "" {
r.Description = todo + "description of the vulnerability"
}
if len(r.Credits) == 0 {
r.Credits = []string{todo + "who discovered/reported this vulnerability (optional)"}
}
if r.CVEMetadata == nil && len(r.CVEs) == 0 {
r.CVEs = []string{todo + "CVE id(s) for this vulnerability"}
}
if r.CVEMetadata != nil && r.CVEMetadata.CWE == "" {
r.CVEMetadata.CWE = todo + "CWE ID"
}
addReferenceTODOs(r)
}
// addReferenceTODOs adds a TODO for each important reference type not
// already present in the report.
func addReferenceTODOs(r *yamlReport) {
todos := []*report.Reference{
{Type: osv.ReferenceTypeAdvisory, URL: "TODO: canonical security advisory"},
{Type: osv.ReferenceTypeReport, URL: "TODO: issue tracker link"},
{Type: osv.ReferenceTypeFix, URL: "TODO: PR or commit (commit preferred)"}}
types := make(map[osv.ReferenceType]bool)
for _, r := range r.References {
types[r.Type] = true
}
for _, todo := range todos {
if !types[todo.Type] {
r.References = append(r.References, todo)
}
}
}
|
vulnreport
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/cmd/vulnreport/vulnreport_test.go
|
// Copyright 2024 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"testing"
)
func TestCreate(t *testing.T) {
for _, tc := range []*testCase{
// TODO(tatianabradley): add test cases
} {
runTest(t, &create{}, tc)
}
}
func TestCreateExcluded(t *testing.T) {
for _, tc := range []*testCase{
// TODO(tatianabradley): add test cases
} {
runTest(t, &createExcluded{}, tc)
}
}
func TestCommit(t *testing.T) {
for _, tc := range []*testCase{
// TODO(tatianabradley): add test cases
} {
runTest(t, &commit{}, tc)
}
}
func TestCVE(t *testing.T) {
for _, tc := range []*testCase{
{
name: "ok",
args: []string{"1"},
},
{
name: "err",
args: []string{"4"},
wantErr: true,
},
} {
runTest(t, &cveCmd{}, tc)
}
}
func TestTriage(t *testing.T) {
for _, tc := range []*testCase{
{
name: "all",
// no args
},
} {
runTest(t, &triage{}, tc)
}
}
func TestFix(t *testing.T) {
for _, tc := range []*testCase{
{
name: "no_change",
args: []string{"1"},
},
} {
runTest(t, &fix{}, tc)
}
}
func TestLint(t *testing.T) {
for _, tc := range []*testCase{
{
name: "no_lints",
args: []string{"1"},
},
{
name: "found_lints",
args: []string{"4"},
wantErr: true,
},
} {
runTest(t, &lint{}, tc)
}
}
func TestOSV(t *testing.T) {
for _, tc := range []*testCase{
{
name: "ok",
args: []string{"1"},
},
{
name: "err",
args: []string{"4"},
wantErr: true,
},
} {
runTest(t, &osvCmd{}, tc)
}
}
func TestRegen(t *testing.T) {
for _, tc := range []*testCase{
// TODO(tatianabradley): add test cases
} {
runTest(t, ®enerate{}, tc)
}
}
func TestSetDates(t *testing.T) {
for _, tc := range []*testCase{
// TODO(tatianabradley): add test cases
} {
runTest(t, &setDates{}, tc)
}
}
func TestSuggest(t *testing.T) {
for _, tc := range []*testCase{
// TODO(tatianabradley): add test cases
} {
runTest(t, &suggest{}, tc)
}
}
func TestSymbols(t *testing.T) {
for _, tc := range []*testCase{
// TODO(tatianabradley): add test cases
} {
runTest(t, &symbolsCmd{}, tc)
}
}
func TestUnexclude(t *testing.T) {
for _, tc := range []*testCase{
// TODO(tatianabradley): add test cases
} {
runTest(t, &unexclude{}, tc)
}
}
func TestXref(t *testing.T) {
for _, tc := range []*testCase{
{
name: "no_xrefs",
args: []string{"1"},
},
{
name: "found_xrefs",
args: []string{"4"},
},
} {
runTest(t, &xref{}, tc)
}
}
|
vulnreport
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/cmd/vulnreport/issue_client.go
|
// Copyright 2024 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"cmp"
"context"
"fmt"
"slices"
"golang.org/x/exp/maps"
"golang.org/x/tools/txtar"
"golang.org/x/vulndb/internal/issues"
"gopkg.in/yaml.v3"
)
type issueClient interface {
Issues(context.Context, issues.IssuesOptions) ([]*issues.Issue, error)
Issue(context.Context, int) (*issues.Issue, error)
SetLabels(context.Context, int, []string) error
Reference(int) string
}
var _ issueClient = &memIC{}
type memIC struct {
is map[int]issues.Issue
}
func newMemIC(archive []byte) (*memIC, error) {
ar := txtar.Parse(archive)
m := &memIC{
is: make(map[int]issues.Issue),
}
for _, f := range ar.Files {
var iss issues.Issue
if err := yaml.Unmarshal(f.Data, &iss); err != nil {
return nil, err
}
m.is[iss.Number] = iss
}
return m, nil
}
func (m *memIC) Issue(_ context.Context, n int) (*issues.Issue, error) {
if i, ok := m.is[n]; ok {
return &i, nil
}
return nil, fmt.Errorf("issue %d not found", n)
}
func (m *memIC) Issues(_ context.Context, opts issues.IssuesOptions) (result []*issues.Issue, err error) {
if len(opts.Labels) != 0 {
return nil, fmt.Errorf("label option not supported for in-memory issues client")
}
all := maps.Values(m.is)
slices.SortFunc(all, func(a, b issues.Issue) int { return cmp.Compare(a.Number, b.Number) })
for _, i := range all {
i := i
if opts.State != "" && opts.State != i.State {
continue
}
result = append(result, &i)
}
return result, nil
}
// TODO(tatianabradley): Write the modified issues to the test golden file.
func (m *memIC) SetLabels(_ context.Context, n int, labels []string) error {
if iss, ok := m.is[n]; ok {
iss.Labels = labels
m.is[n] = iss
return nil
}
return fmt.Errorf("issue %d not found", n)
}
func (*memIC) Reference(n int) string {
return fmt.Sprintf("test-issue-tracker/%d", n)
}
|
vulnreport
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/cmd/vulnreport/writer.go
|
// Copyright 2024 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"bytes"
"context"
"encoding/json"
"os"
"path/filepath"
"time"
"golang.org/x/vulndb/cmd/vulnreport/log"
"golang.org/x/vulndb/internal/cve5"
)
type fileWriter struct{ wfs }
func (f *fileWriter) setup(_ context.Context, env environment) error {
f.wfs = env.WFS()
return nil
}
func (f *fileWriter) write(r *yamlReport) error {
w := bytes.NewBuffer(make([]byte, 0))
if err := r.Encode(w); err != nil {
return err
}
modified, err := f.WriteFile(r.Filename, w.Bytes())
if err != nil {
return err
}
return ok(r.Filename, modified)
}
func (f *fileWriter) writeOSV(r *yamlReport) error {
if r.IsExcluded() {
return nil
}
entry, err := r.ToOSV(time.Time{})
if err != nil {
return err
}
return writeJSON(f, r.OSVFilename(), entry)
}
func (f *fileWriter) writeCVE(r *yamlReport) error {
if r.CVEMetadata == nil {
return nil
}
cve, err := cve5.FromReport(r.Report)
if err != nil {
return err
}
return writeJSON(f, r.CVEFilename(), cve)
}
func (f *fileWriter) writeDerived(r *yamlReport) error {
if err := f.writeOSV(r); err != nil {
return err
}
return f.writeCVE(r)
}
func writeJSON(wfs wfs, fname string, v any) error {
j, err := json.MarshalIndent(v, "", " ")
if err != nil {
return err
}
modified, err := wfs.WriteFile(fname, j)
if err != nil {
return err
}
return ok(fname, modified)
}
func ok(fname string, modified bool) error {
if modified {
log.Out(filepath.ToSlash(fname))
}
return nil
}
// a simple representation of a writeable file system
type wfs interface {
WriteFile(string, []byte) (bool, error)
}
type defaultWFS struct{}
var _ wfs = &defaultWFS{}
func (defaultWFS) WriteFile(filename string, b []byte) (bool, error) {
// writing the file would not change its contents
if existing, err := os.ReadFile(filename); err == nil && bytes.Equal(existing, b) {
return false, nil
}
return true, os.WriteFile(filename, b, 0644)
}
|
vulnreport
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/cmd/vulnreport/find_aliases_test.go
|
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"context"
"fmt"
"strings"
"testing"
"github.com/google/go-cmp/cmp"
"golang.org/x/vulndb/cmd/vulnreport/log"
)
func TestAliasesBFS(t *testing.T) {
log.Discard()
tests := []struct {
knownAliases []string
aliasesFor func(ctx context.Context, alias string) ([]string, error)
want []string
}{
{
knownAliases: []string{"CVE-2023-0001"},
aliasesFor: func(ctx context.Context, alias string) ([]string, error) {
switch alias {
case "CVE-2023-0001":
return []string{"GHSA-xxxx-yyyy-zzzz"}, nil
default:
return nil, errBadAlias(t, alias)
}
},
want: []string{"CVE-2023-0001", "GHSA-xxxx-yyyy-zzzz"},
},
{
knownAliases: []string{"CVE-2023-0001", "GHSA-xxxx-yyyy-zzzz"},
aliasesFor: func(ctx context.Context, alias string) ([]string, error) {
switch alias {
case "CVE-2023-0001":
return []string{"GHSA-xxxx-yyyy-zzzz"}, nil
case "GHSA-xxxx-yyyy-zzzz":
return []string{"CVE-2023-0001"}, nil
default:
return nil, errBadAlias(t, alias)
}
},
want: []string{"CVE-2023-0001", "GHSA-xxxx-yyyy-zzzz"},
},
{
knownAliases: []string{"CVE-2023-0001", "GHSA-xxxx-yyyy-zzzz"},
aliasesFor: func(ctx context.Context, alias string) ([]string, error) {
switch alias {
case "CVE-2023-0001":
return []string{"GHSA-xxxx-yyyy-zzzz", "CVE-2023-0002"}, nil
case "GHSA-xxxx-yyyy-zzzz":
return []string{"CVE-2023-0001", "CVE-2023-0002"}, nil
case "CVE-2023-0002":
return []string{"CVE-2023-0001", "GHSA-xxxx-yyyy-zzzz"}, nil
default:
return nil, errBadAlias(t, alias)
}
},
want: []string{"CVE-2023-0001", "CVE-2023-0002", "GHSA-xxxx-yyyy-zzzz"},
},
{
knownAliases: []string{"CVE-2023-0001"},
aliasesFor: func(ctx context.Context, alias string) ([]string, error) {
switch alias {
case "CVE-2023-0001":
return []string{"GHSA-xxxx-yyyy-zzzz"}, nil
case "GHSA-xxxx-yyyy-zzzz":
return []string{"CVE-2023-0002"}, nil
case "CVE-2023-0002":
return []string{"GHSA-xxxx-yyyy-zzzz"}, nil
default:
return nil, errBadAlias(t, alias)
}
},
want: []string{"CVE-2023-0001", "CVE-2023-0002", "GHSA-xxxx-yyyy-zzzz"},
},
{
knownAliases: []string{},
aliasesFor: func(ctx context.Context, alias string) ([]string, error) {
return nil, fmt.Errorf("unsupported alias %s", alias)
},
want: nil,
},
}
for _, test := range tests {
t.Run(strings.Join(test.knownAliases, ","), func(t *testing.T) {
got := aliasesBFS(context.Background(), test.knownAliases, test.aliasesFor)
if diff := cmp.Diff(test.want, got); diff != "" {
t.Errorf("aliasesBFS(%v) = %v, want %v", test.knownAliases, got, test.want)
}
})
}
}
func errBadAlias(t *testing.T, alias string) error {
t.Helper()
t.Logf("alias %s not found", alias)
return fmt.Errorf("bad alias %s", alias)
}
|
vulnreport
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/cmd/vulnreport/run_test.go
|
// Copyright 2024 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"bytes"
"context"
_ "embed"
"flag"
"fmt"
"io/fs"
"path/filepath"
"strings"
"testing"
"time"
"github.com/google/go-cmp/cmp"
"golang.org/x/tools/txtar"
"golang.org/x/vulndb/cmd/vulnreport/log"
"golang.org/x/vulndb/cmd/vulnreport/priority"
"golang.org/x/vulndb/internal/gitrepo"
"golang.org/x/vulndb/internal/pkgsite"
"golang.org/x/vulndb/internal/proxy"
"golang.org/x/vulndb/internal/test"
)
// go test ./cmd/vulnreport -update-test -proxy -pkgsite
var (
testUpdate = flag.Bool("update-test", false, "(for test) whether to update test files")
realProxy = flag.Bool("proxy", false, "(for test) whether to use real proxy")
usePkgsite = flag.Bool("pkgsite", false, "(for test) whether to use real pkgsite")
)
type testCase struct {
name string
args []string
wantErr bool
}
type memWFS struct {
written map[string][]byte
}
func newInMemoryWFS() *memWFS {
return &memWFS{written: make(map[string][]byte)}
}
var _ wfs = &memWFS{}
func (m *memWFS) WriteFile(fname string, b []byte) (bool, error) {
if bytes.Equal(m.written[fname], b) {
return false, nil
}
m.written[fname] = b
return true, nil
}
func testFilename(t *testing.T) string {
return filepath.Join("testdata", t.Name()+".txtar")
}
var (
//go:embed testdata/repo.txtar
testRepo []byte
//go:embed testdata/issue_tracker.txtar
testIssueTracker []byte
//go:embed testdata/legacy_ghsas.txtar
testLegacyGHSAs []byte
//go:embed testdata/modules.csv
testModuleMap []byte
)
// runTest runs the command on the test case in the default test environment.
func runTest(t *testing.T, cmd command, tc *testCase) {
runTestWithEnv(t, cmd, tc, func(t *testing.T) (*environment, error) {
return newDefaultTestEnv(t)
})
}
var testTime = time.Date(2022, 1, 1, 0, 0, 0, 0, time.UTC)
func newDefaultTestEnv(t *testing.T) (*environment, error) {
t.Helper()
ar := txtar.Parse(testRepo)
repo, err := gitrepo.FromTxtarArchive(ar, testTime)
if err != nil {
return nil, err
}
fsys, err := test.TxtarArchiveToFS(ar)
if err != nil {
return nil, err
}
pxc, err := proxy.NewTestClient(t, *realProxy)
if err != nil {
return nil, err
}
pkc, err := pkgsite.TestClient(t, *usePkgsite)
if err != nil {
return nil, err
}
ic, err := newMemIC(testIssueTracker)
if err != nil {
return nil, err
}
gc, err := newMemGC(testLegacyGHSAs)
if err != nil {
return nil, err
}
mm, err := priority.CSVToMap(bytes.NewReader(testModuleMap))
if err != nil {
return nil, err
}
return &environment{
reportRepo: repo,
reportFS: fsys,
pxc: pxc,
pkc: pkc,
wfs: newInMemoryWFS(),
ic: ic,
gc: gc,
moduleMap: mm,
}, nil
}
func runTestWithEnv(t *testing.T, cmd command, tc *testCase, newEnv func(t *testing.T) (*environment, error)) {
log.RemoveColor()
t.Run(tc.name, func(t *testing.T) {
// Re-generate a fresh env for each sub-test.
env, err := newEnv(t)
if err != nil {
t.Error(err)
return
}
out, logs := bytes.NewBuffer([]byte{}), bytes.NewBuffer([]byte{})
log.WriteTo(out, logs)
ctx := context.Background()
err = run(ctx, cmd, tc.args, *env)
if tc.wantErr {
if err == nil {
t.Errorf("run(%s, %s) = %v, want error", cmd.name(), tc.args, err)
}
} else if err != nil {
t.Errorf("run(%s, %s) = %v, want no error", cmd.name(), tc.args, err)
}
got := &golden{out: out.Bytes(), logs: logs.Bytes()}
if *testUpdate {
comment := fmt.Sprintf("Expected output of test %s\ncommand: \"vulnreport %s %s\"", t.Name(), cmd.name(), strings.Join(tc.args, " "))
var written map[string][]byte
if env.wfs != nil {
written = (env.wfs).(*memWFS).written
}
if err := writeGolden(t, got, comment, written); err != nil {
t.Error(err)
return
}
}
want, err := readGolden(t)
if err != nil {
t.Errorf("could not read golden file: %v", err)
return
}
if diff := cmp.Diff(want.String(), got.String()); diff != "" {
t.Errorf("run(%s, %s) mismatch (-want, +got):\n%s", cmd.name(), tc.args, diff)
}
})
}
type golden struct {
out []byte
logs []byte
}
func (g *golden) String() string {
return fmt.Sprintf("out:\n%s\nlogs:\n%s", g.out, g.logs)
}
func readGolden(t *testing.T) (*golden, error) {
fsys, err := test.ReadTxtarFS(testFilename(t))
if err != nil {
return nil, err
}
out, err := fs.ReadFile(fsys, "out")
if err != nil {
return nil, err
}
logs, err := fs.ReadFile(fsys, "logs")
if err != nil {
return nil, err
}
return &golden{out: out, logs: logs}, nil
}
func writeGolden(t *testing.T, g *golden, comment string, written map[string][]byte) error {
files := []txtar.File{
{Name: "out", Data: g.out},
{Name: "logs", Data: g.logs},
}
for fname, b := range written {
files = append(files, txtar.File{Name: fname, Data: b})
}
return test.WriteTxtar(testFilename(t), files, comment)
}
|
vulnreport
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/cmd/vulnreport/symbols.go
|
// Copyright 2024 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"context"
"flag"
"golang.org/x/vulndb/internal/symbols"
)
var (
update = flag.Bool("update", false, "for symbols, populate the FixLinks field for each module")
)
type symbolsCmd struct {
*filenameParser
*fileWriter
noSkip
}
func (symbolsCmd) name() string { return "symbols" }
func (symbolsCmd) usage() (string, string) {
const desc = "finds and populates possible vulnerable symbols for a given report"
return filenameArgs, desc
}
func (s *symbolsCmd) setup(ctx context.Context, env environment) error {
s.filenameParser = new(filenameParser)
s.fileWriter = new(fileWriter)
return setupAll(ctx, env, s.filenameParser, s.fileWriter)
}
func (*symbolsCmd) close() error { return nil }
func (s *symbolsCmd) run(ctx context.Context, input any) (err error) {
r := input.(*yamlReport)
if err = symbols.Populate(r.Report, *update); err != nil {
return err
}
return s.write(r)
}
|
vulnreport
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/cmd/vulnreport/lint.go
|
// Copyright 2024 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"context"
"fmt"
"strings"
"golang.org/x/vulndb/internal/proxy"
)
type lint struct {
*linter
*filenameParser
noSkip
}
func (lint) name() string { return "lint" }
func (lint) usage() (string, string) {
const desc = "lints vulnerability YAML reports"
return filenameArgs, desc
}
func (l *lint) setup(ctx context.Context, env environment) error {
l.linter = new(linter)
l.filenameParser = new(filenameParser)
return setupAll(ctx, env, l.linter, l.filenameParser)
}
func (l *lint) close() error { return nil }
func (l *lint) run(_ context.Context, input any) error {
r := input.(*yamlReport)
return l.lint(r)
}
type linter struct {
pxc *proxy.Client
}
func (l *linter) setup(_ context.Context, env environment) error {
l.pxc = env.ProxyClient()
return nil
}
func (l *linter) lint(r *yamlReport) error {
if lints := r.Lint(l.pxc); len(lints) > 0 {
return fmt.Errorf("%v has %d lint warnings:%s%s", r.ID, len(lints), listItem, strings.Join(lints, listItem))
}
return nil
}
func (l *linter) canonicalModule(mp string) string {
if module, err := l.pxc.FindModule(mp); err == nil { // no error
mp = module
}
if module, err := l.pxc.CanonicalAtLatest(mp); err == nil { // no error
mp = module
}
return mp
}
|
vulnreport
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/cmd/vulnreport/fix.go
|
// Copyright 2024 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"context"
"flag"
"fmt"
"net/http"
"regexp"
"runtime"
"strings"
"github.com/google/go-cmp/cmp"
"golang.org/x/exp/slices"
"golang.org/x/vulndb/cmd/vulnreport/log"
"golang.org/x/vulndb/internal/osvutils"
"golang.org/x/vulndb/internal/pkgsite"
"golang.org/x/vulndb/internal/report"
"golang.org/x/vulndb/internal/symbols"
)
var (
force = flag.Bool("f", false, "for fix, force Fix to run even if there are no lint errors")
skipChecks = flag.Bool("skip-checks", false, "for fix, skip all checks except lint")
skipAlias = flag.Bool("skip-alias", false, "for fix, skip adding new GHSAs and CVEs")
skipSymbols = flag.Bool("skip-symbols", false, "for fix, don't load package for symbols checks")
skipPackages = flag.Bool("skip-packages", false, "for fix, don't check if packages exist")
skipRefs = flag.Bool("skip-refs", false, "for fix, don't check if references exist")
)
type fix struct {
*fixer
*filenameParser
noSkip
}
func (fix) name() string { return "fix" }
func (fix) usage() (string, string) {
const desc = "fix a YAML report"
return filenameArgs, desc
}
func (f *fix) setup(ctx context.Context, env environment) error {
f.fixer = new(fixer)
f.filenameParser = new(filenameParser)
return setupAll(ctx, env, f.fixer, f.filenameParser)
}
func (*fix) close() error { return nil }
func (f *fix) run(ctx context.Context, input any) error {
r := input.(*yamlReport)
return f.fixAndWriteAll(ctx, r, false)
}
type fixer struct {
*linter
*aliasFinder
*fileWriter
pkc *pkgsite.Client
}
func (f *fixer) setup(ctx context.Context, env environment) error {
f.pkc = env.PkgsiteClient()
f.linter = new(linter)
f.aliasFinder = new(aliasFinder)
f.fileWriter = new(fileWriter)
return setupAll(ctx, env, f.linter, f.aliasFinder, f.fileWriter)
}
func (f *fixer) fixAndWriteAll(ctx context.Context, r *yamlReport, addNotes bool) error {
fixed := f.fix(ctx, r, addNotes)
// fix may have partially succeeded, so write the report no matter what.
if err := f.write(r); err != nil {
return err
}
if fixed {
return f.writeDerived(r)
}
return fmt.Errorf("%s: could not fix all errors; requires manual review", r.ID)
}
func (f *fixer) fix(ctx context.Context, r *yamlReport, addNotes bool) (fixed bool) {
fixed = true
if lints := r.Lint(f.pxc); *force || len(lints) > 0 {
r.Fix(f.pxc)
}
if !*skipChecks {
if ok := f.allChecks(ctx, r, addNotes); !ok {
fixed = false
}
}
// Check for remaining lint errors.
if addNotes {
if r.LintAsNotes(f.pxc) {
log.Warnf("%s: still has lint errors after fix", r.ID)
fixed = false
}
} else {
if lints := r.Lint(f.pxc); len(lints) > 0 {
log.Warnf("%s: still has lint errors after fix:\n\t- %s", r.ID, strings.Join(lints, "\n\t- "))
fixed = false
}
}
return fixed
}
// allChecks runs additional checks/fixes that are slow and require a network connection.
// Unlike lint checks which cannot be bypassed, these *should* pass before submit,
// but it is possible to bypass them if needed with the "-skip-checks" flag.
func (f *fixer) allChecks(ctx context.Context, r *yamlReport, addNotes bool) (ok bool) {
ok = true
fixErr := func(f string, v ...any) {
log.Errf(r.ID+": "+f, v...)
if addNotes {
r.AddNote(report.NoteTypeFix, f, v...)
}
ok = false
}
if !*skipPackages {
log.Infof("%s: checking that all packages exist", r.ID)
if err := r.CheckPackages(ctx, f.pkc); err != nil {
fixErr("package error: %s", err)
}
}
if !*skipSymbols {
log.Infof("%s: checking symbols (use -skip-symbols to skip this)", r.ID)
if err := r.checkSymbols(); err != nil {
fixErr("symbol error: %s", err)
}
}
if !*skipAlias {
log.Infof("%s: checking for missing GHSAs and CVEs (use -skip-alias to skip this)", r.ID)
if added := r.addMissingAliases(ctx, f.aliasFinder); added > 0 {
log.Infof("%s: added %d missing aliases", r.ID, added)
}
}
if !*skipRefs {
// For now, this is a fix check instead of a lint.
log.Infof("%s: checking that all references are reachable", r.ID)
checkRefs(r.References, fixErr)
}
return ok
}
func checkRefs(refs []*report.Reference, fixErr func(f string, v ...any)) {
for _, r := range refs {
resp, err := http.Head(r.URL)
if err != nil {
fixErr("%q may not exist: %v", r.URL, err)
continue
}
defer resp.Body.Close()
// For now, only error on status 404, which is unambiguously a problem.
// An experiment to error on all non-200 status codes brought up some
// ambiguous cases where the link is still viewable in a browser, e.g.:
// - 429 Too Many Requests (https://vuldb.com/)
// - 503 Service Unavailable (http://blog.recurity-labs.com/2017-08-10/scm-vulns):
// - 403 Forbidden (https://www.sap.com/documents/2022/02/fa865ea4-167e-0010-bca6-c68f7e60039b.html)
if resp.StatusCode == http.StatusNotFound {
fixErr("%q may not exist: HTTP GET returned status %s", r.URL, resp.Status)
}
}
}
func (r *yamlReport) checkSymbols() error {
if r.IsExcluded() {
log.Infof("%s: excluded, skipping symbol checks", r.ID)
return nil
}
if len(r.Modules) == 0 {
log.Infof("%s: no modules, skipping symbol checks", r.ID)
return nil
}
for _, m := range r.Modules {
if len(m.Packages) == 0 {
log.Infof("%s: module %s has no packages, skipping symbol checks", r.ID, m.Module)
return nil
}
if m.IsFirstParty() {
gover := runtime.Version()
ver := semverForGoVersion(gover)
// If some symbol is in the std library at a different version,
// we may derive the wrong symbols for this package and other.
// In this case, skip updating DerivedSymbols.
ranges, err := m.Versions.ToSemverRanges()
if err != nil {
return err
}
affected, err := osvutils.AffectsSemver(ranges, ver)
if err != nil {
return err
}
if ver == "" || !affected {
log.Warnf("%s: current Go version %q is not in a vulnerable range, skipping symbol checks for module %s", r.ID, gover, m.Module)
continue
}
if m.VulnerableAt == nil || ver != m.VulnerableAt.Version {
log.Warnf("%s: current Go version %q does not match vulnerable_at version (%s) for module %s", r.ID, ver, m.VulnerableAt, m.Module)
}
}
for _, p := range m.Packages {
if len(p.AllSymbols()) == 0 && p.SkipFixSymbols != "" {
log.Warnf("%s: skip_fix not needed", r.Filename)
continue
}
if len(p.AllSymbols()) == 0 {
log.Infof("%s: skipping symbol checks for package %s (no symbols)", r.ID, p.Package)
continue
}
if p.SkipFixSymbols != "" {
log.Infof("%s: skipping symbol checks for package %s (reason: %q)", r.ID, p.Package, p.SkipFixSymbols)
continue
}
syms, err := symbols.Exported(m, p)
if err != nil {
return fmt.Errorf("package %s: %w", p.Package, err)
}
// Remove any derived symbols that were marked as excluded by a human.
syms = removeExcluded(r.ID, syms, p.ExcludedSymbols)
if !cmp.Equal(syms, p.DerivedSymbols) {
p.DerivedSymbols = syms
log.Infof("%s: updated derived symbols for package %s", r.ID, p.Package)
}
}
}
return nil
}
func removeExcluded(id string, syms, excluded []string) []string {
if len(excluded) == 0 {
return syms
}
var newSyms []string
for _, d := range syms {
if slices.Contains(excluded, d) {
log.Infof("%s: removed excluded symbol %s", id, d)
continue
}
newSyms = append(newSyms, d)
}
return newSyms
}
// Regexp for matching go tags. The groups are:
// 1 the major.minor version
// 2 the patch version, or empty if none
// 3 the entire prerelease, if present
// 4 the prerelease type ("beta" or "rc")
// 5 the prerelease number
var tagRegexp = regexp.MustCompile(`^go(\d+\.\d+)(\.\d+|)((beta|rc)(\d+))?$`)
// versionForTag returns the semantic version for a Go version string,
// or "" if the version string doesn't correspond to a Go release or beta.
func semverForGoVersion(v string) string {
m := tagRegexp.FindStringSubmatch(v)
if m == nil {
return ""
}
version := m[1]
if m[2] != "" {
version += m[2]
} else {
version += ".0"
}
if m[3] != "" {
version += "-" + m[4] + "." + m[5]
}
return version
}
|
vulnreport
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/cmd/vulnreport/withdraw.go
|
// Copyright 2024 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"context"
"flag"
"fmt"
"time"
"golang.org/x/vulndb/internal/osv"
"golang.org/x/vulndb/internal/report"
)
var reason = flag.String("reason", "", "the reason this report is being withdrawn")
type withdraw struct {
*fixer
*filenameParser
}
func (withdraw) name() string { return "withdraw" }
func (withdraw) usage() (string, string) {
const desc = "withdraws a report"
return filenameArgs, desc
}
func (w *withdraw) setup(ctx context.Context, env environment) error {
if *reason == "" {
return fmt.Errorf("flag -reason must be provided")
}
w.fixer = new(fixer)
w.filenameParser = new(filenameParser)
return setupAll(ctx, env, w.fixer, w.filenameParser)
}
func (w *withdraw) close() error {
return nil
}
func (w *withdraw) skip(input any) string {
r := input.(*yamlReport)
if r.IsExcluded() {
return "excluded; can't be withdrawn"
}
if r.Withdrawn != nil {
return "already withdrawn"
}
if r.CVEMetadata != nil {
return "withdrawing Go-published report not yet supported"
}
return ""
}
func (w *withdraw) run(ctx context.Context, input any) (err error) {
r := input.(*yamlReport)
r.Withdrawn = &osv.Time{Time: time.Now()}
r.Summary = "WITHDRAWN: " + r.Summary
r.Description = report.Description(
fmt.Sprintf("(This report has been withdrawn with reason: %q). %s",
*reason, r.Description))
return w.fixAndWriteAll(ctx, r, false)
}
|
vulnreport
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/cmd/vulnreport/regenerate.go
|
// Copyright 2024 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"context"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"golang.org/x/vulndb/cmd/vulnreport/log"
"golang.org/x/vulndb/internal/report"
)
type regenerate struct {
*creator
*filenameParser
}
func (regenerate) name() string { return "regen" }
func (regenerate) usage() (string, string) {
const desc = "regenerates reports from source"
return filenameArgs, desc
}
func (u *regenerate) setup(ctx context.Context, env environment) error {
u.creator = new(creator)
u.filenameParser = new(filenameParser)
return setupAll(ctx, env, u.creator, u.filenameParser)
}
func (u *regenerate) close() error {
return closeAll(u.creator)
}
func (u *regenerate) skip(input any) string {
r := input.(*yamlReport)
// Never re-generate an original report.
if r.CVEMetadata != nil || r.IsOriginal() {
return "original report"
}
// Usually, we don't auto-regenerate REVIEWED reports, as doing so
// would likely clobber valuable information.
if r.IsReviewed() {
if *force {
log.Warnf("%s: reviewed; but -f was specified, continuing", r.ID)
return ""
}
return "reviewed; use -f to force"
}
return ""
}
func (u *regenerate) run(ctx context.Context, input any) (err error) {
oldR := input.(*yamlReport)
for _, note := range oldR.Notes {
// A note with no type was added by a human.
if note.Type == report.NoteTypeNone {
log.Warnf("%s may have been manually edited: %s", oldR.ID, note.Body)
}
}
r, err := u.reportFromMeta(ctx, oldR.meta())
if err != nil {
return err
}
if !cmp.Equal(r, oldR,
cmpopts.IgnoreFields(report.SourceMeta{}, "Created"),
// VulnerableAt can change based on latest published version, so we don't
// need to update the report if only that changed.
cmpopts.IgnoreFields(report.Module{}, "VulnerableAt")) {
return u.write(ctx, r)
} else {
log.Infof("%s: re-generating from source does not change report", r.ID)
}
return nil
}
func (r *yamlReport) meta() *reportMeta {
var modulePath string
if len(r.Modules) > 0 {
modulePath = r.Modules[0].Module
}
return &reportMeta{
id: r.ID,
modulePath: modulePath,
aliases: r.Aliases(),
reviewStatus: r.ReviewStatus,
unexcluded: r.Unexcluded,
}
}
|
vulnreport
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/cmd/vulnreport/command.go
|
// Copyright 2024 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"context"
"errors"
"fmt"
"io/fs"
"golang.org/x/vulndb/cmd/vulnreport/log"
"golang.org/x/vulndb/internal/issues"
"golang.org/x/vulndb/internal/report"
)
// command represents a subcommand of vulnreport.
type command interface {
// name outputs the string used to invoke the subcommand.
name() string
// usage outputs strings indicating how to use the subcommand.
usage() (args string, desc string)
setuper
// parseArgs takes in the raw args passed to the command line,
// and converts them to a representation understood by "run".
// This function need not be one-to-one: there may be more
// inputs than args or vice-versa.
parseArgs(_ context.Context, args []string) (inputs []string, _ error)
lookup(context.Context, string) (any, error)
skip(any) string
run(context.Context, any) error
// close cleans up state and/or completes tasks that should occur
// after run is called on all inputs.
close() error
inputType() string
}
// run executes the given command on the given raw arguments.
func run(ctx context.Context, c command, args []string, env environment) (err error) {
if err := c.setup(ctx, env); err != nil {
return err
}
stats := &counter{}
defer func() {
if cerr := c.close(); cerr != nil {
err = errors.Join(err, cerr)
}
if total := stats.total(); total > 0 {
log.Infof("%s: processed %d %s(s) (success=%d; skip=%d; error=%d)", c.name(), total, c.inputType(), stats.succeeded, stats.skipped, stats.errored)
}
if stats.errored > 0 {
err = errors.Join(err, fmt.Errorf("errored on %d inputs", stats.errored))
}
}()
inputs, err := c.parseArgs(ctx, args)
if err != nil {
return err
}
log.Infof("%s: operating on %d %s(s)", c.name(), len(inputs), c.inputType())
for _, input := range inputs {
in, err := c.lookup(ctx, input)
if err != nil {
stats.errored++
log.Errf("%s: lookup %s failed: %s", c.name(), input, err)
continue
}
if reason := c.skip(in); reason != "" {
stats.skipped++
log.Infof("%s: skipping %s (%s)", c.name(), toString(in), reason)
continue
}
log.Infof("%s %s", c.name(), input)
if err := c.run(ctx, in); err != nil {
stats.errored++
log.Errf("%s: %s", c.name(), err)
continue
}
stats.succeeded++
}
return nil
}
type counter struct {
skipped int
succeeded int
errored int
}
func (c *counter) total() int {
return c.skipped + c.succeeded + c.errored
}
func toString(in any) string {
switch v := in.(type) {
case *yamlReport:
return fmt.Sprintf("report %s", v.Report.ID)
case *issues.Issue:
return fmt.Sprintf("issue #%d", v.Number)
default:
return fmt.Sprintf("%v", v)
}
}
type setuper interface {
// setup populates state needed to run a command.
setup(context.Context, environment) error
}
func setupAll(ctx context.Context, env environment, fs ...setuper) error {
for _, f := range fs {
if err := f.setup(ctx, env); err != nil {
return err
}
}
return nil
}
type closer interface {
close() error
}
func closeAll(cs ...closer) error {
for _, c := range cs {
if err := c.close(); err != nil {
return err
}
}
return nil
}
const (
filenameArgs = "[filename | github-id] ..."
ghIssueArgs = "[github-id] ..."
)
// filenameParser implements the "parseArgs" function of the command
// interface, and can be used by commands that operate on YAML filenames.
type filenameParser struct {
fsys fs.FS
}
func (f *filenameParser) setup(_ context.Context, env environment) error {
f.fsys = env.ReportFS()
return nil
}
func (*filenameParser) inputType() string {
return "report"
}
func (f *filenameParser) parseArgs(_ context.Context, args []string) (filenames []string, allErrs error) {
if len(args) == 0 {
return nil, fmt.Errorf("no arguments provided")
}
for _, arg := range args {
fname, err := argToFilename(arg, f.fsys)
if err != nil {
log.Err(err)
continue
}
filenames = append(filenames, fname)
}
if len(filenames) == 0 {
return nil, fmt.Errorf("could not parse any valid filenames from arguments")
}
return filenames, nil
}
func argToFilename(arg string, fsys fs.FS) (string, error) {
if _, err := fs.Stat(fsys, arg); err != nil {
// If arg isn't a file, see if it might be an issue ID
// with an existing report.
for _, padding := range []string{"", "0", "00", "000"} {
m, _ := fs.Glob(fsys, "data/*/GO-*-"+padding+arg+".yaml")
if len(m) == 1 {
return m[0], nil
}
}
return "", fmt.Errorf("could not parse argument %q: not a valid filename or issue ID with existing report: %w", arg, err)
}
return arg, nil
}
func (f *filenameParser) lookup(_ context.Context, filename string) (any, error) {
r, err := report.ReadStrict(f.fsys, filename)
if err != nil {
return nil, err
}
return &yamlReport{Report: r, Filename: filename}, nil
}
type noSkip bool
func (noSkip) skip(any) string {
return ""
}
type yamlReport struct {
*report.Report
Filename string
}
|
vulnreport
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/cmd/vulnreport/unexclude.go
|
// Copyright 2024 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"context"
"fmt"
"os"
"golang.org/x/vulndb/cmd/vulnreport/log"
"golang.org/x/vulndb/internal/report"
)
type unexclude struct {
*creator
*filenameParser
}
func (unexclude) name() string { return "unexclude" }
func (unexclude) usage() (string, string) {
const desc = "converts excluded YAML reports to regular YAML reports"
return filenameArgs, desc
}
func (u *unexclude) setup(ctx context.Context, env environment) error {
u.creator = new(creator)
u.filenameParser = new(filenameParser)
return setupAll(ctx, env, u.creator, u.filenameParser)
}
func (u *unexclude) close() error {
return closeAll(u.creator)
}
func (u *unexclude) skip(input any) string {
r := input.(*yamlReport)
if !r.IsExcluded() {
return "not excluded"
}
// Usually, we only unexclude reports that are effectively private or not importable.
if ex := r.Excluded; ex != "EFFECTIVELY_PRIVATE" && ex != "NOT_IMPORTABLE" {
if *force {
log.Warnf("%s: excluded for reason %q, but -f was specified, continuing", r.ID, ex)
return ""
}
return fmt.Sprintf("excluded = %s; use -f to force", ex)
}
return ""
}
// unexclude converts an excluded report into a regular report.
func (u *unexclude) run(ctx context.Context, input any) (err error) {
oldR := input.(*yamlReport)
var modulePath string
if len(oldR.Modules) > 0 {
modulePath = oldR.Modules[0].Module
}
r, err := u.reportFromMeta(ctx, &reportMeta{
id: oldR.ID,
modulePath: modulePath,
aliases: oldR.Aliases(),
reviewStatus: report.Unreviewed,
})
if err != nil {
return err
}
r.Unexcluded = oldR.Excluded
if err := u.write(ctx, r); err != nil {
return err
}
remove(oldR)
return nil
}
func remove(r *yamlReport) {
if err := os.Remove(r.Filename); err != nil {
log.Errf("%s: could not remove file %s: %v", r.ID, r.Filename, err)
return
}
log.Infof("%s: removed %s", r.ID, r.Filename)
}
|
vulnreport
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/cmd/vulnreport/issue_parser.go
|
// Copyright 2024 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"context"
"fmt"
"strconv"
"strings"
"golang.org/x/vulndb/internal/issues"
)
// issueParser implements the "parseArgs" function of the command
// interface, and can be used by commands that operate on Github issues.
type issueParser struct {
ic issueClient
toProcess map[string]*issues.Issue
open []*issues.Issue
}
const issueStateOpen = "open"
func (*issueParser) inputType() string {
return "issue"
}
func (ip *issueParser) openIssues(ctx context.Context) ([]*issues.Issue, error) {
if ip.open == nil {
open, err := ip.ic.Issues(ctx, issues.IssuesOptions{State: issueStateOpen})
if err != nil {
return nil, err
}
ip.open = open
}
return ip.open, nil
}
func (ip *issueParser) parseArgs(ctx context.Context, args []string) (issNums []string, _ error) {
if len(args) > 0 {
return argsToIDs(args)
}
// If no arguments are provided, operate on all open issues.
open, err := ip.openIssues(ctx)
if err != nil {
return nil, err
}
for _, iss := range open {
n := strconv.Itoa(iss.Number)
ip.toProcess[n] = iss
issNums = append(issNums, n)
}
return issNums, nil
}
func (ip *issueParser) setup(ctx context.Context, env environment) error {
ic, err := env.IssueClient(ctx)
if err != nil {
return err
}
ip.ic = ic
ip.toProcess = make(map[string]*issues.Issue)
return nil
}
func (ip *issueParser) lookup(ctx context.Context, issNum string) (any, error) {
iss, ok := ip.toProcess[issNum]
if !ok {
n, err := strconv.Atoi(issNum)
if err != nil {
return nil, err
}
iss, err := ip.ic.Issue(ctx, n)
if err != nil {
return nil, err
}
ip.toProcess[issNum] = iss
return iss, nil
}
return iss, nil
}
func argsToIDs(args []string) ([]string, error) {
var githubIDs []string
parseGithubID := func(s string) (int, error) {
id, err := strconv.Atoi(s)
if err != nil {
return 0, fmt.Errorf("invalid GitHub issue ID: %q", s)
}
return id, nil
}
for _, arg := range args {
if !strings.Contains(arg, "-") {
_, err := parseGithubID(arg)
if err != nil {
return nil, err
}
githubIDs = append(githubIDs, arg)
continue
}
from, to, _ := strings.Cut(arg, "-")
fromID, err := parseGithubID(from)
if err != nil {
return nil, err
}
toID, err := parseGithubID(to)
if err != nil {
return nil, err
}
if fromID > toID {
return nil, fmt.Errorf("%v > %v", fromID, toID)
}
for id := fromID; id <= toID; id++ {
githubIDs = append(githubIDs, strconv.Itoa(id))
}
}
return githubIDs, nil
}
|
vulnreport
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/cmd/vulnreport/set_dates.go
|
// Copyright 2024 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"context"
"fmt"
"golang.org/x/vulndb/internal/gitrepo"
"golang.org/x/vulndb/internal/report"
)
type setDates struct {
dates map[string]gitrepo.Dates
*filenameParser
*fileWriter
noSkip
}
func (setDates) name() string { return "set-dates" }
func (setDates) usage() (string, string) {
const desc = "sets PublishDate of YAML reports"
return filenameArgs, desc
}
func (sd *setDates) setup(ctx context.Context, env environment) error {
repo, err := env.ReportRepo(ctx)
if err != nil {
return err
}
dates, err := gitrepo.AllCommitDates(repo, gitrepo.MainReference, report.YAMLDir)
if err != nil {
return err
}
sd.dates = dates
sd.filenameParser = new(filenameParser)
sd.fileWriter = new(fileWriter)
return setupAll(ctx, env, sd.filenameParser, sd.fileWriter)
}
func (sd *setDates) close() error { return nil }
// setDates sets the PublishedDate of the report at filename to the oldest
// commit date in the repo that contains that file. (It may someday also set a
// last-modified date, hence the plural.) Since it looks at the commits from
// origin/master, it will only work for reports that are already submitted. Thus
// it isn't useful to run when you're working on a report, only at a later time.
//
// It isn't crucial to run this for every report, because the same logic exists
// in gendb, ensuring that every report has a PublishedDate before being
// transformed into a DB entry. The advantage of using this command is that
// the dates become permanent (if you create and submit a CL after running it).
//
// This intentionally does not set the LastModified of the report: While the
// publication date of a report may be expected not to change, the modification
// date can. Always using the git history as the source of truth for the
// last-modified date avoids confusion if the report YAML and the git history
// disagree.
func (sd *setDates) run(ctx context.Context, input any) (err error) {
r := input.(*yamlReport)
if !r.Published.IsZero() {
return nil
}
d, ok := sd.dates[r.Filename]
if !ok {
return fmt.Errorf("can't find git repo commit dates for %q", r.Filename)
}
r.Published = d.Oldest
return sd.write(r)
}
|
vulnreport
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/cmd/vulnreport/create.go
|
// Copyright 2024 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"context"
"flag"
"golang.org/x/vulndb/internal/issues"
)
var (
preferCVE = flag.Bool("cve", false, "for create, prefer CVEs over GHSAs as canonical source")
useAI = flag.Bool("ai", false, "for create, use AI to write draft summary and description when creating report")
populateSymbols = flag.Bool("symbols", false, "for create, attempt to auto-populate symbols")
user = flag.String("user", "", "for create & create-excluded, only consider issues assigned to the given user")
reviewStatus = flag.String("status", "", "for create, use this review status (REVIEWED or UNREVIEWED) instead of default based on label; for commit, only commit reports with this status")
)
type create struct {
*issueParser
*creator
}
func (create) name() string { return "create" }
func (create) usage() (string, string) {
const desc = "creates a new vulnerability YAML report"
return ghIssueArgs, desc
}
func (c *create) setup(ctx context.Context, env environment) error {
c.creator = new(creator)
c.issueParser = new(issueParser)
return setupAll(ctx, env, c.creator, c.issueParser)
}
func (c *create) close() error {
return closeAll(c.creator)
}
func (c *create) run(ctx context.Context, input any) error {
iss := input.(*issues.Issue)
return c.reportFromIssue(ctx, iss)
}
|
vulnreport
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/cmd/vulnreport/find_aliases.go
|
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"context"
"fmt"
"golang.org/x/exp/slices"
"golang.org/x/tools/txtar"
"golang.org/x/vulndb/cmd/vulnreport/log"
"golang.org/x/vulndb/internal/cve5"
"golang.org/x/vulndb/internal/genericosv"
"golang.org/x/vulndb/internal/ghsa"
"golang.org/x/vulndb/internal/idstr"
"golang.org/x/vulndb/internal/report"
"gopkg.in/yaml.v3"
)
type aliasFinder struct {
gc ghsaClient
}
func (af *aliasFinder) setup(ctx context.Context, env environment) error {
gc, err := env.GHSAClient(ctx)
if err != nil {
return err
}
af.gc = gc
return nil
}
// addMissingAliases uses the existing aliases in a report to find
// any missing aliases, and adds them to the report.
func (r *yamlReport) addMissingAliases(ctx context.Context, af *aliasFinder) (added int) {
all := af.allAliases(ctx, r.Aliases())
// If we have manually marked an identifier as "related", but
// not actually an alias, don't override this decision.
if len(r.Related) > 0 {
all = removeRelated(all, r.Related)
}
return r.AddAliases(all)
}
func removeRelated(all, related []string) []string {
// This is an uncommon operation, operating on short string slices,
// so it doesn't need to be optimized.
return slices.DeleteFunc(all, func(s string) bool {
return slices.Contains(related, s)
})
}
// allAliases returns a list of all aliases associated with the given knownAliases,
// (including the knownAliases themselves).
func (a *aliasFinder) allAliases(ctx context.Context, knownAliases []string) []string {
aliasesFor := func(ctx context.Context, alias string) ([]string, error) {
switch {
case idstr.IsGHSA(alias):
return aliasesForGHSA(ctx, alias, a.gc)
case idstr.IsCVE(alias):
return aliasesForCVE(ctx, alias, a.gc)
default:
return nil, fmt.Errorf("allAliases(): unsupported alias %s", alias)
}
}
return aliasesBFS(ctx, knownAliases, aliasesFor)
}
func aliasesBFS(ctx context.Context, knownAliases []string,
aliasesFor func(ctx context.Context, alias string) ([]string, error)) (all []string) {
var queue []string
var seen = make(map[string]bool)
queue = append(queue, knownAliases...)
for len(queue) > 0 {
alias := queue[0]
queue = queue[1:]
if seen[alias] {
continue
}
seen[alias] = true
all = append(all, alias)
aliases, err := aliasesFor(ctx, alias)
if err != nil {
log.Warn(err)
continue
}
queue = append(queue, aliases...)
}
slices.Sort(all)
return slices.Compact(all)
}
func aliasesForGHSA(ctx context.Context, alias string, gc ghsaClient) (aliases []string, err error) {
sa, err := gc.FetchGHSA(ctx, alias)
if err != nil {
return nil, fmt.Errorf("aliasesForGHSA(%s): could not fetch GHSA record from GraphQL API", alias)
}
for _, id := range sa.Identifiers {
if id.Type == "CVE" || id.Type == "GHSA" {
aliases = append(aliases, id.Value)
}
}
return aliases, nil
}
func aliasesForCVE(ctx context.Context, cve string, gc ghsaClient) (aliases []string, err error) {
sas, err := gc.ListForCVE(ctx, cve)
if err != nil {
return nil, fmt.Errorf("aliasesForCVE(%s): could not find GHSAs from GraphQL API", cve)
}
for _, sa := range sas {
aliases = append(aliases, sa.ID)
}
return aliases, nil
}
// sourceFromBestAlias returns a report source fetched from the "best" alias in the list.
// By default, it prefers the first GHSA in the list, followed by the first CVE in the list
// (if no GHSA is present).
// If "preferCVE" is true, it prefers CVEs instead.
func (af *aliasFinder) sourceFromBestAlias(ctx context.Context, aliases []string, preferCVE bool) report.Source {
firstChoice := idstr.IsGHSA
secondChoice := idstr.IsCVE
if preferCVE {
firstChoice, secondChoice = secondChoice, firstChoice
}
find := func(f func(string) bool) report.Source {
for _, alias := range aliases {
if f(alias) {
src, err := af.fetch(ctx, alias)
if err != nil {
log.Warnf("could not fetch record for preferred alias %s: %v", alias, err)
continue
}
return src
}
}
return nil
}
if src := find(firstChoice); src != nil {
return src
}
return find(secondChoice)
}
func (a *aliasFinder) fetch(ctx context.Context, alias string) (report.Source, error) {
var f report.Fetcher
switch {
case idstr.IsGHSA(alias):
f = genericosv.NewGHSAFetcher()
case idstr.IsCVE(alias):
f = cve5.NewFetcher()
default:
return nil, fmt.Errorf("alias %s is not supported", alias)
}
return f.Fetch(ctx, alias)
}
type ghsaClient interface {
FetchGHSA(context.Context, string) (*ghsa.SecurityAdvisory, error)
ListForCVE(context.Context, string) ([]*ghsa.SecurityAdvisory, error)
}
type memGC struct {
ghsas map[string]ghsa.SecurityAdvisory
}
func newMemGC(archive []byte) (*memGC, error) {
ar := txtar.Parse(archive)
m := &memGC{
ghsas: make(map[string]ghsa.SecurityAdvisory),
}
for _, f := range ar.Files {
var g ghsa.SecurityAdvisory
if err := yaml.Unmarshal(f.Data, &g); err != nil {
return nil, err
}
m.ghsas[f.Name] = g
}
return m, nil
}
func (m *memGC) FetchGHSA(_ context.Context, id string) (*ghsa.SecurityAdvisory, error) {
if sa, ok := m.ghsas[id]; ok {
return &sa, nil
}
return nil, fmt.Errorf("%s not found", id)
}
func (m *memGC) ListForCVE(_ context.Context, cid string) (result []*ghsa.SecurityAdvisory, _ error) {
for _, sa := range m.ghsas {
for _, id := range sa.Identifiers {
if id.Type == "CVE" || id.Value == cid {
result = append(result, &sa)
}
}
}
return result, nil
}
|
vulnreport
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/cmd/vulnreport/osv.go
|
// Copyright 2024 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"context"
)
type osvCmd struct {
*linter
*fileWriter
*filenameParser
noSkip
}
func (osvCmd) name() string { return "osv" }
func (osvCmd) usage() (string, string) {
const desc = "converts YAML reports to OSV JSON and writes to data/osv"
return filenameArgs, desc
}
func (o *osvCmd) setup(ctx context.Context, env environment) error {
o.linter = new(linter)
o.filenameParser = new(filenameParser)
o.fileWriter = new(fileWriter)
return setupAll(ctx, env, o.linter, o.filenameParser, o.fileWriter)
}
func (o *osvCmd) close() error { return nil }
func (o *osvCmd) run(_ context.Context, input any) error {
r := input.(*yamlReport)
if err := o.lint(r); err != nil {
return err
}
return o.writeOSV(r)
}
|
vulnreport
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/cmd/vulnreport/review.go
|
// Copyright 2024 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"context"
"golang.org/x/vulndb/internal/report"
)
type review struct {
*creator
*filenameParser
}
func (review) name() string { return "review" }
func (review) usage() (string, string) {
const desc = "converts unreviewed reports to reviewed"
return filenameArgs, desc
}
func (u *review) setup(ctx context.Context, env environment) error {
u.creator = new(creator)
u.filenameParser = new(filenameParser)
return setupAll(ctx, env, u.creator, u.filenameParser)
}
func (u *review) close() error {
return closeAll(u.creator)
}
func (u *review) skip(input any) string {
r := input.(*yamlReport)
if r.IsExcluded() {
return "excluded; use vulnreport unexclude instead"
}
if r.IsReviewed() {
return "already reviewed"
}
return ""
}
func (u *review) run(ctx context.Context, input any) (err error) {
meta := input.(*yamlReport).meta()
meta.reviewStatus = report.Reviewed
r, err := u.reportFromMeta(ctx, meta)
if err != nil {
return err
}
return u.write(ctx, r)
}
|
vulnreport
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/cmd/vulnreport/environment.go
|
// Copyright 2024 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"context"
"fmt"
"io/fs"
"os"
"github.com/go-git/go-git/v5"
"golang.org/x/vulndb/cmd/vulnreport/priority"
"golang.org/x/vulndb/internal/ghsa"
"golang.org/x/vulndb/internal/gitrepo"
"golang.org/x/vulndb/internal/issues"
"golang.org/x/vulndb/internal/pkgsite"
"golang.org/x/vulndb/internal/proxy"
)
// environment stores fakes/mocks of external dependencies for testing.
type environment struct {
reportRepo *git.Repository
reportFS fs.FS
pxc *proxy.Client
pkc *pkgsite.Client
wfs wfs
ic issueClient
gc ghsaClient
moduleMap map[string]int
}
func defaultEnv() environment {
return environment{}
}
func (e *environment) ReportRepo(ctx context.Context) (*git.Repository, error) {
if v := e.reportRepo; v != nil {
return v, nil
}
return gitrepo.Open(ctx, *reportRepo)
}
func (e *environment) ReportFS() fs.FS {
if v := e.reportFS; v != nil {
return v
}
return os.DirFS(*reportRepo)
}
func (e *environment) ProxyClient() *proxy.Client {
if v := e.pxc; v != nil {
return v
}
return proxy.NewDefaultClient()
}
func (e *environment) PkgsiteClient() *pkgsite.Client {
if v := e.pkc; v != nil {
return v
}
return pkgsite.Default()
}
func (e *environment) WFS() wfs {
if v := e.wfs; v != nil {
return v
}
return defaultWFS{}
}
func (e *environment) IssueClient(ctx context.Context) (issueClient, error) {
if e.ic != nil {
return e.ic, nil
}
if *githubToken == "" {
return nil, fmt.Errorf("githubToken must be provided")
}
owner, repoName, err := gitrepo.ParseGitHubRepo(*issueRepo)
if err != nil {
return nil, err
}
return issues.NewClient(ctx, &issues.Config{Owner: owner, Repo: repoName, Token: *githubToken}), nil
}
func (e *environment) GHSAClient(ctx context.Context) (ghsaClient, error) {
if v := e.gc; v != nil {
return v, nil
}
if *githubToken == "" {
return nil, fmt.Errorf("githubToken must be provided")
}
return ghsa.NewClient(ctx, *githubToken), nil
}
func (e *environment) ModuleMap() (map[string]int, error) {
if v := e.moduleMap; v != nil {
return v, nil
}
return priority.LoadModuleMap()
}
|
vulnreport
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/cmd/vulnreport/main.go
|
// Copyright 2021 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Command vulnreport provides a tool for creating a YAML vulnerability report for
// x/vulndb.
package main
import (
"context"
"flag"
"fmt"
"log"
"os"
"runtime/pprof"
"text/tabwriter"
vlog "golang.org/x/vulndb/cmd/vulnreport/log"
)
var (
githubToken = flag.String("ghtoken", "", "GitHub access token (default: value of VULN_GITHUB_ACCESS_TOKEN)")
cpuprofile = flag.String("cpuprofile", "", "write cpuprofile to this file")
quiet = flag.Bool("q", false, "quiet mode (suppress info logs)")
colorize = flag.Bool("color", os.Getenv("NO_COLOR") == "", "show colors in logs")
issueRepo = flag.String("issue-repo", "github.com/golang/vulndb", "repo to locate Github issues")
reportRepo = flag.String("local-repo", ".", "local path to repo to locate YAML reports")
)
func init() {
out := flag.CommandLine.Output()
flag.Usage = func() {
fmt.Fprintf(out, "usage: vulnreport [flags] [cmd] [args]\n\n")
tw := tabwriter.NewWriter(out, 2, 4, 2, ' ', 0)
for _, command := range commands {
argUsage, desc := command.usage()
fmt.Fprintf(tw, " %s\t%s\t%s\n", command.name(), argUsage, desc)
}
tw.Flush()
fmt.Fprint(out, "\nsupported flags:\n\n")
flag.PrintDefaults()
}
}
// The subcommands supported by vulnreport.
// To add a new command, implement the command interface and
// add the command to this list.
var commands = map[string]command{
"create": &create{},
"create-excluded": &createExcluded{},
"commit": &commit{},
"cve": &cveCmd{},
"triage": &triage{},
"fix": &fix{},
"lint": &lint{},
"regen": ®enerate{},
"review": &review{},
"set-dates": &setDates{},
"suggest": &suggest{},
"symbols": &symbolsCmd{},
"osv": &osvCmd{},
"unexclude": &unexclude{},
"withdraw": &withdraw{},
"xref": &xref{},
}
func main() {
ctx := context.Background()
flag.Parse()
if flag.NArg() < 1 {
flag.Usage()
log.Fatal("subcommand required")
}
if *quiet {
vlog.SetQuiet()
}
if !*colorize {
vlog.RemoveColor()
}
if *githubToken == "" {
*githubToken = os.Getenv("VULN_GITHUB_ACCESS_TOKEN")
}
// Start CPU profiler.
if *cpuprofile != "" {
f, err := os.Create(*cpuprofile)
if err != nil {
log.Fatal(err)
}
_ = pprof.StartCPUProfile(f)
defer pprof.StopCPUProfile()
}
cmdName := flag.Arg(0)
args := flag.Args()[1:]
cmd, ok := commands[cmdName]
if !ok {
flag.Usage()
log.Fatalf("unsupported command: %q", cmdName)
}
if err := run(ctx, cmd, args, defaultEnv()); err != nil {
log.Fatalf("%s: %s", cmdName, err)
}
}
|
vulnreport
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/cmd/vulnreport/cve.go
|
// Copyright 2024 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"context"
)
type cveCmd struct {
*linter
*filenameParser
*fileWriter
noSkip
}
func (cveCmd) name() string { return "cve" }
func (cveCmd) usage() (string, string) {
const desc = "creates and saves CVE 5.0 record from the provided YAML reports"
return filenameArgs, desc
}
func (c *cveCmd) setup(ctx context.Context, env environment) error {
c.linter = new(linter)
c.filenameParser = new(filenameParser)
c.fileWriter = new(fileWriter)
return setupAll(ctx, env, c.linter, c.filenameParser, c.fileWriter)
}
func (c *cveCmd) close() error { return nil }
func (c *cveCmd) run(_ context.Context, input any) error {
r := input.(*yamlReport)
if err := c.lint(r); err != nil {
return err
}
return c.writeCVE(r)
}
|
vulnreport
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/cmd/vulnreport/create_excluded.go
|
// Copyright 2024 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"context"
"errors"
"fmt"
"golang.org/x/vulndb/internal/issues"
"golang.org/x/vulndb/internal/report"
)
type createExcluded struct {
*creator
*committer
*issueParser
}
func (createExcluded) name() string { return "create-excluded" }
func (createExcluded) usage() (string, string) {
const desc = "creates and commits reports for Github issues marked excluded"
return "", desc
}
func (c *createExcluded) close() (err error) {
defer func() {
if cerr := closeAll(c.creator); cerr != nil {
err = errors.Join(err, cerr)
}
}()
err = c.commit(c.created...)
return err
}
func (c *createExcluded) setup(ctx context.Context, env environment) error {
c.creator = new(creator)
c.committer = new(committer)
c.issueParser = new(issueParser)
return setupAll(ctx, env, c.creator, c.committer, c.issueParser)
}
func (c *createExcluded) run(ctx context.Context, input any) (err error) {
iss := input.(*issues.Issue)
return c.reportFromIssue(ctx, iss)
}
func (c *createExcluded) skip(input any) string {
iss := input.(*issues.Issue)
if !isExcluded(iss) {
return "not excluded"
}
if c.assignee != "" && iss.Assignee != c.assignee {
return fmt.Sprintf("assigned to %s, not %s", iss.Assignee, c.assignee)
}
return c.creator.skip(iss)
}
func isExcluded(iss *issues.Issue) bool {
for _, er := range report.ExcludedReasons {
if iss.HasLabel(er.ToLabel()) {
return true
}
}
return false
}
|
vulnreport
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/cmd/vulnreport/git.go
|
// Copyright 2021 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"os"
"os/exec"
"golang.org/x/vulndb/internal/derrors"
)
func gitAdd(files ...string) (err error) {
derrors.Wrap(&err, "git add")
addArgs := []string{"add"}
return irun("git", append(addArgs, files...)...)
}
func gitCommit(msg string, files ...string) (err error) {
derrors.Wrap(&err, "git commit")
commitArgs := []string{"commit", "-m", msg, "-e"}
commitArgs = append(commitArgs, files...)
return irun("git", commitArgs...)
}
func irun(name string, arg ...string) error {
// Exec git commands rather than using go-git so as to run commit hooks
// and give the user a chance to edit the commit message.
cmd := exec.Command(name, arg...)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
}
|
log
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/cmd/vulnreport/log/log.go
|
// Copyright 2024 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package log
import (
"fmt"
"io"
"os"
"log"
"golang.org/x/vulndb/cmd/vulnreport/color"
)
func SetQuiet() {
loggers[infoLvl] = log.New(io.Discard, "", 0)
}
func RemoveColor() {
for lvl := range loggers {
loggers[lvl].SetPrefix(metas[lvl].prefix)
}
colorize = false
}
func Discard() {
for lvl := range loggers {
loggers[lvl].SetOutput(io.Discard)
}
}
func WriteTo(out io.Writer, log io.Writer) {
for lvl := range loggers {
loggers[lvl].SetOutput(log)
}
loggers[outLvl].SetOutput(out)
}
const (
infoLvl int = iota
outLvl
warnLvl
errLvl
)
func defaultLoggers() []*log.Logger {
ls := make([]*log.Logger, len(metas))
for lvl, lm := range metas {
ls[lvl] = log.New(lm.w, lm.color+lm.prefix, 0)
}
return ls
}
var (
loggers = defaultLoggers()
// Whether to display colors in logs.
colorize bool = true
metas = []*metadata{
infoLvl: {
prefix: "info: ",
color: color.Faint,
w: os.Stderr,
},
outLvl: {
prefix: "",
color: color.Reset,
w: os.Stdout,
},
warnLvl: {
prefix: "WARNING: ",
color: color.YellowHi,
w: os.Stderr,
},
errLvl: {
prefix: "ERROR: ",
color: color.RedHi,
w: os.Stderr,
},
}
)
type metadata struct {
prefix string
color string
w io.Writer
}
func printf(lvl int, format string, v ...any) {
println(lvl, fmt.Sprintf(format, v...))
}
func println(lvl int, v ...any) {
l := loggers[lvl]
l.Println(v...)
if colorize {
fmt.Fprint(l.Writer(), color.Reset)
}
}
func Infof(format string, v ...any) {
printf(infoLvl, format, v...)
}
func Outf(format string, v ...any) {
printf(outLvl, format, v...)
}
func Warnf(format string, v ...any) {
printf(warnLvl, format, v...)
}
func Errf(format string, v ...any) {
printf(errLvl, format, v...)
}
func Info(v ...any) {
println(infoLvl, v...)
}
func Out(v ...any) {
println(outLvl, v...)
}
func Warn(v ...any) {
println(warnLvl, v...)
}
func Err(v ...any) {
println(errLvl, v...)
}
|
priority
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/cmd/vulnreport/priority/load.go
|
// Copyright 2024 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package priority
import (
"bytes"
"compress/gzip"
_ "embed"
"encoding/csv"
"io"
"strconv"
)
//go:embed data/importers.csv.gz
var importers []byte
func LoadModuleMap() (map[string]int, error) {
return gzCSVToMap(importers)
}
func gzCSVToMap(b []byte) (map[string]int, error) {
gzr, err := gzip.NewReader(bytes.NewReader(b))
if err != nil {
return nil, err
}
return CSVToMap(gzr)
}
func CSVToMap(r io.Reader) (map[string]int, error) {
reader := csv.NewReader(r)
records, err := reader.ReadAll()
if err != nil {
return nil, err
}
m := make(map[string]int)
for _, record := range records[1:] {
if len(record) != 2 {
continue
}
n, err := strconv.Atoi(record[1])
if err != nil {
continue
}
m[record[0]] = n
}
return m, nil
}
|
priority
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/cmd/vulnreport/priority/priority.go
|
// Copyright 2024 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package priority contains utilities for prioritizing vulnerability reports.
package priority
import (
"fmt"
"strings"
"golang.org/x/vulndb/internal/report"
)
type Result struct {
Priority Priority
Reason string
}
type NotGoResult struct {
Reason string
}
type Priority int
func (p Priority) String() string {
switch p {
case Unknown:
return "unknown"
case High:
return "high"
case Low:
return "low"
default:
return fmt.Sprintf("%d", p)
}
}
const (
Unknown Priority = iota
Low
High
)
// AnalyzeReport returns the results for a report as a whole:
// - priority is the priority of its highest-priority module
// - not Go if all modules are not Go
func AnalyzeReport(r *report.Report, rc *report.Client, modulesToImports map[string]int) (*Result, *NotGoResult) {
var overall Priority
var reasons []string
var notGoReasons []string
for _, m := range r.Modules {
mp := m.Module
result, notGo := Analyze(mp, rc.ReportsByModule(mp), modulesToImports)
if result.Priority > overall {
overall = result.Priority
}
reasons = append(reasons, result.Reason)
if notGo != nil {
notGoReasons = append(notGoReasons, notGo.Reason)
}
}
result := &Result{
Priority: overall, Reason: strings.Join(reasons, "; "),
}
// If all modules are not Go, the report is not Go.
if len(notGoReasons) == len(r.Modules) {
return result, &NotGoResult{Reason: strings.Join(notGoReasons, "; ")}
}
return result, nil
}
func Analyze(mp string, reportsForModule []*report.Report, modulesToImports map[string]int) (*Result, *NotGoResult) {
sc := stateCounts(reportsForModule)
notGo := isPossiblyNotGo(len(reportsForModule), sc)
importers, ok := modulesToImports[mp]
if !ok {
return &Result{
Priority: Unknown,
Reason: fmt.Sprintf("module %s not found", mp),
}, notGo
}
return priority(mp, importers, sc), notGo
}
// override takes precedence over all other metrics in determining
// a module's priority.
var override map[string]Priority = map[string]Priority{
// argo-cd is primarily a binary and usually has correct version
// information without intervention.
"github.com/argoproj/argo-cd": Low,
"github.com/argoproj/argo-cd/v2": Low,
}
func priority(mp string, importers int, sc map[reportState]int) *Result {
if pr, ok := override[mp]; ok {
return &Result{pr, fmt.Sprintf("%s is in the override list (priority=%s)", mp, pr)}
}
const highPriority = 100
importersStr := func(comp string) string {
return fmt.Sprintf("%s has %d importers (%s %d)", mp, importers, comp, highPriority)
}
if importers >= highPriority {
rev := sc[reviewed]
binary := sc[excludedBinary] + sc[unreviewedUnexcluded]
getReason := func(conj1, conj2 string) string {
return fmt.Sprintf("%s %s reviewed (%d) %s likely-binary reports (%d)",
importersStr(">="), conj1, rev, conj2, binary)
}
if rev > binary {
return &Result{High, getReason("and more", "than")}
} else if rev == binary {
return &Result{High, getReason("and as many", "as")}
}
return &Result{Low, getReason("but fewer", "than")}
}
return &Result{Low, importersStr("<")}
}
func isPossiblyNotGo(numReports int, sc map[reportState]int) *NotGoResult {
if (float32(sc[excludedNotGo])/float32(numReports))*100 > 20 {
return &NotGoResult{
Reason: fmt.Sprintf("more than 20 percent of reports (%d of %d) with this module are NOT_GO_CODE", sc[excludedNotGo], numReports),
}
}
return nil
}
type reportState int
const (
unknownReportState reportState = iota
reviewed
unreviewedStandard
unreviewedUnexcluded
excludedBinary
excludedNotGo
excludedOther
)
func state(r *report.Report) reportState {
if r.IsExcluded() {
switch e := r.Excluded; e {
case "NOT_GO_CODE":
return excludedNotGo
case "EFFECTIVELY_PRIVATE", "NOT_IMPORTABLE", "LEGACY_FALSE_POSITIVE":
return excludedBinary
case "NOT_A_VULNERABILITY", "DEPENDENT_VULNERABILITY":
return excludedOther
default:
return unknownReportState
}
}
switch rs := r.ReviewStatus; rs {
case report.Reviewed:
return reviewed
case report.Unreviewed:
if r.Unexcluded != "" {
return unreviewedUnexcluded
}
return unreviewedStandard
}
return unknownReportState
}
func stateCounts(rs []*report.Report) map[reportState]int {
counts := make(map[reportState]int)
for _, r := range rs {
st := state(r)
if st == unknownReportState {
panic("could not determine report state for " + r.ID)
}
counts[st]++
}
return counts
}
|
priority
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/cmd/vulnreport/priority/priority_test.go
|
// Copyright 2024 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package priority
import (
"testing"
"github.com/google/go-cmp/cmp"
"golang.org/x/vulndb/internal/report"
)
var (
notGo1 = &report.Report{
Excluded: "NOT_GO_CODE",
}
reviewed1 = &report.Report{
ReviewStatus: report.Reviewed,
}
reviewed2 = &report.Report{
ReviewStatus: report.Reviewed,
}
reviewedBinary = &report.Report{
ReviewStatus: report.Reviewed,
Unexcluded: "NOT_IMPORTABLE",
}
unreviewed1 = &report.Report{
ReviewStatus: report.Unreviewed,
}
binary1 = &report.Report{
Excluded: "NOT_IMPORTABLE",
}
binary2 = &report.Report{
Excluded: "EFFECTIVELY_PRIVATE",
}
binary3 = &report.Report{
Excluded: "LEGACY_FALSE_POSITIVE",
}
unreviewedBinary = &report.Report{
ReviewStatus: report.Unreviewed,
Unexcluded: "NOT_IMPORTABLE",
}
notAVuln1 = &report.Report{
Excluded: "NOT_A_VULNERABILITY",
}
dependent1 = &report.Report{
Excluded: "DEPENDENT_VULNERABILITY",
}
)
func TestAnalyze(t *testing.T) {
for _, tc := range []struct {
name string
module string
reportsForModule []*report.Report
modulesToImports map[string]int
want *Result
wantNotGo *NotGoResult
}{
{
name: "unknown priority",
module: "example.com/module",
modulesToImports: map[string]int{},
want: &Result{
Priority: Unknown,
Reason: "module example.com/module not found",
},
},
{
name: "low priority",
module: "example.com/module",
reportsForModule: []*report.Report{},
modulesToImports: map[string]int{"example.com/module": 99},
want: &Result{
Priority: Low,
Reason: "example.com/module has 99 importers (< 100)",
},
},
{
name: "high priority",
module: "example.com/module",
reportsForModule: []*report.Report{},
modulesToImports: map[string]int{"example.com/module": 100},
want: &Result{
Priority: High,
Reason: "example.com/module has 100 importers (>= 100) and as many reviewed (0) as likely-binary reports (0)",
},
},
{
name: "high priority more reviewed",
module: "example.com/module",
reportsForModule: []*report.Report{reviewed1, reviewed2, binary1},
modulesToImports: map[string]int{"example.com/module": 101},
want: &Result{
Priority: High,
Reason: "example.com/module has 101 importers (>= 100) and more reviewed (2) than likely-binary reports (1)",
},
},
{
name: "low priority more binaries",
module: "example.com/module",
reportsForModule: []*report.Report{
reviewed1,
binary1, binary2, binary3,
unreviewed1, notAVuln1, dependent1, // ignored
},
modulesToImports: map[string]int{"example.com/module": 101},
want: &Result{
Priority: Low,
Reason: "example.com/module has 101 importers (>= 100) but fewer reviewed (1) than likely-binary reports (3)",
},
},
{
name: "unexcluded unreviewed considered binaries",
module: "example.com/module",
reportsForModule: []*report.Report{
reviewed1, reviewedBinary, // reviewed
binary1, binary2, unreviewedBinary, // binary
unreviewed1, notAVuln1, dependent1, // ignored
},
modulesToImports: map[string]int{"example.com/module": 101},
want: &Result{
Priority: Low,
Reason: "example.com/module has 101 importers (>= 100) but fewer reviewed (2) than likely-binary reports (3)",
},
},
{
name: "low priority and not Go",
module: "example.com/module",
reportsForModule: []*report.Report{notGo1, reviewed1, binary1, unreviewed1},
modulesToImports: map[string]int{"example.com/module": 99},
want: &Result{
Priority: Low,
Reason: "example.com/module has 99 importers (< 100)",
},
wantNotGo: &NotGoResult{
Reason: "more than 20 percent of reports (1 of 4) with this module are NOT_GO_CODE",
},
},
} {
t.Run(tc.name, func(t *testing.T) {
got, gotNotGo := Analyze(tc.module, tc.reportsForModule, tc.modulesToImports)
want := tc.want
if diff := cmp.Diff(want, got); diff != "" {
t.Errorf("result mismatch (-want, +got):\n%s", diff)
}
if diff := cmp.Diff(tc.wantNotGo, gotNotGo); diff != "" {
t.Errorf("not go mismatch (-want, +got):\n%s", diff)
}
})
}
}
|
priority
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/cmd/vulnreport/priority/priority/main.go
|
// Copyright 2024 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Command priority gives direct access to the module prioritization
// code used by vulnreport triage.
// Prints the priority result for the given module(s).
// Can be used for experimentation / debugging.
// Usage: $ go run ./cmd/vulnreport/priority/priority <module_path>
package main
import (
"context"
"log"
"os"
vlog "golang.org/x/vulndb/cmd/vulnreport/log"
"golang.org/x/vulndb/cmd/vulnreport/priority"
"golang.org/x/vulndb/internal/report"
)
func main() {
args := os.Args[1:]
if len(args) == 0 {
log.Fatal("missing module paths")
}
ctx := context.Background()
ms, err := priority.LoadModuleMap()
if err != nil {
log.Fatal(err)
}
rc, err := report.NewDefaultClient(ctx)
if err != nil {
log.Fatal(err)
}
for _, arg := range args {
pr, notGo := priority.Analyze(arg, rc.ReportsByModule(arg), ms)
vlog.Outf("%s:\npriority = %s\n%s", arg, pr.Priority, pr.Reason)
if notGo != nil {
vlog.Outf("%s is likely not Go because %s", arg, notGo.Reason)
}
}
}
|
testdata
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/cmd/vulnreport/testdata/legacy_ghsas.txtar
|
# Copyright 2024 The Go Authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
# Represents the GHSAs accessible via the Github GraphQL API.
-- GHSA-xxxx-yyyy-zzzz --
id: GHSA-xxxx-yyyy-zzzz
identifiers:
- identifier:
- type: CVE
id: CVE-1999-0005
-- GHSA-xxxx-yyyy-0001 --
id: GHSA-xxxx-yyyy-0001
|
testdata
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/cmd/vulnreport/testdata/modules.csv
|
module_path,imported_by
golang.org/x/tools,50
golang.org/x/vuln,101
collectd.org,0
|
testdata
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/cmd/vulnreport/testdata/repo.txtar
|
# Copyright 2024 The Go Authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
-- data/reports/GO-9999-0001.yaml --
id: GO-9999-0001
modules:
- module: golang.org/x/vulndb
vulnerable_at: 0.0.0-20240716161253-dd7900b89e20
packages:
- package: golang.org/x/vulndb/cmd/vulnreport
summary: A problem with golang.org/x/vulndb
description: A description of the issue
review_status: REVIEWED
-- data/reports/GO-9999-0004.yaml --
id: GO-9999-0004
modules:
- module: golang.org/x/tools
summary: A problem with golang.org/x/tools
ghsas:
- GHSA-9999-abcd-efgh
review_status: UNREVIEWED
-- data/reports/GO-9999-0005.yaml --
id: GO-9999-0005
modules:
- module: golang.org/x/tools
cves:
- CVE-9999-0005
review_status: REVIEWED
-- data/excluded/GO-9999-0002.yaml --
id: GO-9999-0002
modules:
- module: golang.org/x/exp
cve_metadata:
id: CVE-9999-0002
excluded: EFFECTIVELY_PRIVATE
-- data/excluded/GO-9999-0003.yaml --
id: GO-9999-0003
modules:
- module: collectd.org
cve_metadata:
id: CVE-9999-0003
excluded: NOT_GO_CODE
|
testdata
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/cmd/vulnreport/testdata/issue_tracker.txtar
|
# Copyright 2024 The Go Authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
# Represents a Github issue tracker.
-- 1 --
number: 1
title: "x/vulndb: potential Go vuln in golang.org/x/vulndb: GHSA-xxxx-yyyy-0001"
assignee: user1
state: open
-- 7 --
number: 7
title: "x/vulndb: potential Go vuln in golang.org/x/tools: CVE-9999-0005"
assignee: user2
state: open
-- 10 --
number: 10
title: "x/vulndb: potential Go vuln in golang.org/x/vuln: GHSA-xxxx-yyyy-zzzz"
state: open
-- 11 --
number: 11
title: "x/vulndb: potential Go vuln in collectd.org: CVE-2021-0000"
state: open
|
TestCVE
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/cmd/vulnreport/testdata/TestCVE/ok.txtar
|
Copyright 2024 The Go Authors. All rights reserved.
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file.
Expected output of test TestCVE/ok
command: "vulnreport cve 1"
-- out --
-- logs --
info: cve: operating on 1 report(s)
info: cve data/reports/GO-9999-0001.yaml
info: cve: processed 1 report(s) (success=1; skip=0; error=0)
|
TestCVE
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/cmd/vulnreport/testdata/TestCVE/err.txtar
|
Copyright 2024 The Go Authors. All rights reserved.
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file.
Expected output of test TestCVE/err
command: "vulnreport cve 4"
-- out --
-- logs --
info: cve: operating on 1 report(s)
info: cve data/reports/GO-9999-0004.yaml
ERROR: cve: GO-9999-0004 has 1 lint warnings:
- references: missing advisory (required because report has no description or is UNREVIEWED)
info: cve: processed 1 report(s) (success=0; skip=0; error=1)
|
TestXref
|
/home/linuxreitt/Michinereitt/Tuning/Workshop_Scripts/hf-codegen/data/golang_public_repos/vulndb/cmd/vulnreport/testdata/TestXref/found_xrefs.txtar
|
Copyright 2024 The Go Authors. All rights reserved.
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file.
Expected output of test TestXref/found_xrefs
command: "vulnreport xref 4"
-- out --
GO-9999-0004: found module xrefs
- golang.org/x/tools appears in 1 other report(s):
- data/reports/GO-9999-0005.yaml (https://github.com/golang/vulndb#5)
GO-9999-0004: priority is low
- golang.org/x/tools has 50 importers (< 100)
-- logs --
info: xref: operating on 1 report(s)
info: xref data/reports/GO-9999-0004.yaml
info: xref: processed 1 report(s) (success=1; skip=0; error=0)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.