diff --git a/README.md b/README.md
index 9331c63..a36771b 100644
--- a/README.md
+++ b/README.md
@@ -34,6 +34,27 @@ stale. `make test` and `make web-test` run the Go and web suites. See the design
[`docs/architecture/touchstone.md`](docs/architecture/touchstone.md) and
the PRD at [`docs/product/touchstone.md`](docs/product/touchstone.md).
+### Discovery and a supplied SBOM/VEX
+
+Every scan checks `/.well-known/security.txt` (then `/security.txt`),
+`/.well-known/csaf/provider-metadata.json` and `/.well-known/tea` on the
+target's origin. It follows each `CSAF:` field and the provider metadata's
+public ROLIE feeds to the five newest CSAF documents, and reads the products
+of those that are CSAF VEX as High-confidence components. `/.well-known/tea`
+is recorded in `checked` but not queried. Every request is in the report's
+`checked` list.
+
+If you already have the vendor's SBOM or VEX (CycloneDX, SPDX 2.3, OpenVEX
+or CSAF, as JSON), pass it in. Its components are High confidence with
+`SBOM_SUPPLIED` evidence:
+
+```sh
+touchstone scan --sbom vendor-sbom.json https://vendor.example
+touchstone scan --sbom-url https://vendor.example/sbom.json https://vendor.example
+```
+
+The web page has the same two inputs: an upload field and a URL field.
+
### Web page: `touchstone serve`
`touchstone serve` runs the web page and `POST /v1/scans` on one port.
diff --git a/cmd/touchstone/main.go b/cmd/touchstone/main.go
index b0efc86..6ee7430 100644
--- a/cmd/touchstone/main.go
+++ b/cmd/touchstone/main.go
@@ -1,8 +1,10 @@
// Command touchstone scans a vendor URL and prints an evidence-graded
// ScanReport as protojson (--format json, the default) or as Markdown
// (--format md), or serves the web page and POST /v1/scans (serve, slice
-// S9). The scan fetches the page and its scripts passively, looks
-// components up in OSV and NVD, and ranks them with KEV and EPSS.
+// S9). The scan fetches the page and its scripts passively, follows the
+// vendor's security.txt and CSAF VEX documents, reads an SBOM/VEX the
+// reviewer supplies (--sbom, --sbom-url), looks components up in OSV and
+// NVD, and ranks them with KEV and EPSS.
package main
import (
@@ -21,7 +23,7 @@ import (
"google.golang.org/protobuf/encoding/protojson"
)
-const usage = "usage: touchstone scan [--allow-private] [--format json|md] \n touchstone serve [--addr host:port]"
+const usage = "usage: touchstone scan [--allow-private] [--format json|md] [--sbom file] [--sbom-url url] \n touchstone serve [--addr host:port]"
// newService builds the ScanService for one CLI invocation. The fetch
// options carry CLI-only settings such as --allow-private, which the
@@ -62,6 +64,8 @@ func run(ctx context.Context, args []string, out io.Writer, newSvc newService) e
fs.SetOutput(io.Discard)
allowPrivate := fs.Bool("allow-private", false, "allow fetching loopback and private addresses (local fixtures only)")
format := fs.String("format", "json", "output format: json (protojson) or md (Markdown)")
+ sbomFile := fs.String("sbom", "", "an SBOM/VEX file you already have (CycloneDX, SPDX, OpenVEX or CSAF JSON)")
+ sbomURL := fs.String("sbom-url", "", "the URL of an SBOM/VEX document you already have")
if err := fs.Parse(args[1:]); err != nil || fs.NArg() != 1 {
return errors.New(usage)
}
@@ -69,8 +73,14 @@ func run(ctx context.Context, args []string, out io.Writer, newSvc newService) e
if err != nil {
return err
}
+ req := &touchstonev1.ScanRequest{Url: fs.Arg(0), SbomUrl: *sbomURL}
+ if *sbomFile != "" {
+ if req.SbomDocument, err = os.ReadFile(*sbomFile); err != nil {
+ return fmt.Errorf("--sbom: %w", err)
+ }
+ }
svc := newSvc(fetch.Options{AllowPrivate: *allowPrivate, Version: service.ToolVersion})
- rep, err := svc.Scan(ctx, &touchstonev1.ScanRequest{Url: fs.Arg(0)})
+ rep, err := svc.Scan(ctx, req)
if err != nil {
return err
}
diff --git a/cmd/touchstone/main_test.go b/cmd/touchstone/main_test.go
index 3bb0aa5..6d91648 100644
--- a/cmd/touchstone/main_test.go
+++ b/cmd/touchstone/main_test.go
@@ -163,11 +163,40 @@ func TestScanFormatFlag(t *testing.T) {
}
}
+// capture is a ScanService that records the request it was given.
+type capture struct {
+ touchstonev1.UnimplementedScanServiceServer
+ req *touchstonev1.ScanRequest
+}
+
+func (c *capture) Scan(ctx context.Context, req *touchstonev1.ScanRequest) (*touchstonev1.ScanReport, error) {
+ c.req = req
+ return fixedStub(fetch.Options{}).Scan(ctx, req)
+}
+
+func TestScanSuppliedSBOMFlags(t *testing.T) {
+ file := filepath.Join(t.TempDir(), "sbom.json")
+ doc := []byte(`{"bomFormat": "CycloneDX", "components": []}`)
+ if err := os.WriteFile(file, doc, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ c := &capture{}
+ newSvc := func(fetch.Options) touchstonev1.ScanServiceServer { return c }
+ args := []string{"scan", "--sbom", file, "--sbom-url", "https://vendor.example/sbom.json", "https://vendor.example"}
+ if err := run(context.Background(), args, &bytes.Buffer{}, newSvc); err != nil {
+ t.Fatalf("run(%q): %v", args, err)
+ }
+ if !bytes.Equal(c.req.GetSbomDocument(), doc) || c.req.GetSbomUrl() != "https://vendor.example/sbom.json" {
+ t.Errorf("ScanRequest = %v, want the file's bytes as sbom_document and the sbom_url", c.req)
+ }
+}
+
func TestScanRejectsBadArgs(t *testing.T) {
for _, args := range [][]string{
nil, {"scan"}, {"serve", "https://example.com"}, {"scan", "ftp://example.com"}, {"scan", "example.com"},
{"scan", "--allow-private"}, {"scan", "--no-such-flag", "https://example.com"}, {"scan", "https://a.example", "https://b.example"},
{"scan", "--format", "xml", "https://example.com"}, {"scan", "--format", "https://example.com"},
+ {"scan", "--sbom", filepath.Join(t.TempDir(), "missing.json"), "https://example.com"},
} {
if err := run(context.Background(), args, &bytes.Buffer{}, fixedStub); err == nil {
t.Errorf("run(%q) = nil error, want error", args)
diff --git a/internal/discover/discover.go b/internal/discover/discover.go
new file mode 100644
index 0000000..cadac21
--- /dev/null
+++ b/internal/discover/discover.go
@@ -0,0 +1,311 @@
+// Package discover finds evidence a vendor publishes about its own
+// software (see docs/architecture/touchstone.md, "Evidence discovery"):
+// security.txt (RFC 9116), CSAF 2.0 provider metadata and the CSAF VEX
+// documents it lists, the Transparency Exchange API's /.well-known/tea,
+// and GitHub/GitLab repo links on the target page. Every request goes
+// through a fetch.Fetcher: the fixed discovery paths as DISCOVERY_PATH,
+// and URLs named by a fetched discovery document as DECLARED.
+package discover
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net/url"
+ "slices"
+ "strings"
+ "time"
+
+ "github.com/FootprintAI/touchstone/internal/fetch"
+ "github.com/FootprintAI/touchstone/internal/pipeline"
+ "github.com/FootprintAI/touchstone/internal/sbom"
+)
+
+// Per-scan caps on what discovery follows, so one large CSAF provider
+// can't spend the whole request budget.
+const (
+ MaxProviders = 3 // provider-metadata.json documents fetched
+ MaxFeeds = 3 // ROLIE feeds fetched, across providers
+ MaxDocuments = 5 // CSAF documents fetched, newest first
+)
+
+// Result is what discovery found.
+type Result struct {
+ // SecurityTxt is the parsed security.txt; nil if none was found.
+ SecurityTxt *SecurityTxt
+ // ProviderMetadata lists the CSAF provider-metadata.json URLs that
+ // were fetched and parsed.
+ ProviderMetadata []string
+ // VEXDocuments lists the CSAF documents with category csaf_vex that
+ // were fetched and parsed.
+ VEXDocuments []string
+ // TEA is true when /.well-known/tea answered. It is recorded only:
+ // querying TEA needs a TEI the site URL does not give (P1).
+ TEA bool
+ // RepoLinks are the GitHub/GitLab repositories the target page links
+ // to, for the repo scan.
+ RepoLinks []string
+ // Components are the products the CSAF VEX documents name, High
+ // confidence with VEX evidence.
+ Components []pipeline.Component
+}
+
+// Discover probes the target's origin and follows what it declares. The
+// target is the URL the reviewer entered (discovery paths are on its
+// origin); page is the fetched target page, for repo links. A document
+// that was found but can't be read is reported in the error; the rest of
+// the result is still returned.
+func Discover(ctx context.Context, f fetch.Fetcher, target string, page *fetch.Response) (*Result, error) {
+ t, err := url.Parse(target)
+ if err != nil {
+ return nil, err
+ }
+ origin := t.Scheme + "://" + t.Host
+ res := &Result{}
+ var errs []error
+
+ if page != nil {
+ if base, err := url.Parse(page.URL); err == nil {
+ links, err := RepoLinks(base, page.Body)
+ if err != nil {
+ errs = append(errs, fmt.Errorf("discover: repo links: %w", err))
+ }
+ res.RepoLinks = links
+ }
+ }
+
+ // RFC 9116, section 3: /.well-known/ first, the root path as fallback.
+ for _, p := range []string{"/.well-known/security.txt", "/security.txt"} {
+ if body, ok := get(ctx, f, origin+p, fetch.ReasonDiscoveryPath); ok {
+ res.SecurityTxt = ParseSecurityTxt(body)
+ break
+ }
+ }
+
+ // CSAF 2.0, section 7.3: the CSAF fields of security.txt come first,
+ // then the well-known provider metadata.
+ wellKnown := origin + "/.well-known/csaf/provider-metadata.json"
+ var providers []providerDoc
+ wkBody, wkFound := get(ctx, f, wellKnown, fetch.ReasonDiscoveryPath)
+
+ // TEA: recorded in the checked list, never parsed or queried.
+ _, res.TEA = get(ctx, f, origin+"/.well-known/tea", fetch.ReasonDiscoveryPath)
+
+ if res.SecurityTxt != nil {
+ var tried []string
+ for _, raw := range res.SecurityTxt.CSAF {
+ // Leave room for the well-known one, already fetched.
+ if len(tried) >= MaxProviders-1 {
+ break
+ }
+ u, ok := absHTTP(raw)
+ if !ok || u == wellKnown || slices.Contains(tried, u) {
+ continue
+ }
+ tried = append(tried, u)
+ if body, ok := get(ctx, f, u, fetch.ReasonDeclared); ok {
+ providers = append(providers, providerDoc{u, body})
+ }
+ }
+ }
+ if wkFound {
+ providers = append(providers, providerDoc{wellKnown, wkBody})
+ }
+
+ var feeds []string
+ for _, p := range providers {
+ pm, err := parseProviderMetadata(p.body)
+ if err != nil {
+ errs = append(errs, fmt.Errorf("discover: %s: %w", p.url, err))
+ continue
+ }
+ res.ProviderMetadata = append(res.ProviderMetadata, p.url)
+ for _, feed := range pm.feedURLs() {
+ if len(feeds) < MaxFeeds && !slices.Contains(feeds, feed) {
+ feeds = append(feeds, feed)
+ }
+ }
+ }
+
+ var entries []feedEntry
+ for _, feed := range feeds {
+ body, ok := get(ctx, f, feed, fetch.ReasonDeclared)
+ if !ok {
+ continue
+ }
+ es, err := parseROLIEFeed(body)
+ if err != nil {
+ errs = append(errs, fmt.Errorf("discover: %s: %w", feed, err))
+ continue
+ }
+ entries = append(entries, es...)
+ }
+
+ for _, doc := range newest(entries, MaxDocuments) {
+ body, ok := get(ctx, f, doc, fetch.ReasonDeclared)
+ if !ok {
+ continue
+ }
+ d, err := sbom.ParseCSAF(body)
+ if err != nil {
+ errs = append(errs, fmt.Errorf("discover: %s: %w", doc, err))
+ continue
+ }
+ if !d.VEX {
+ continue
+ }
+ res.VEXDocuments = append(res.VEXDocuments, doc)
+ for _, c := range d.Components {
+ res.Components = append(res.Components, pipeline.Component{
+ Name: c.Name,
+ Version: c.Version,
+ Purl: c.Purl,
+ CPE: c.CPE,
+ Confidence: "HIGH",
+ Evidence: []pipeline.Evidence{{Kind: "VEX", Location: doc, Detail: "CSAF VEX product"}},
+ })
+ }
+ }
+ return res, errors.Join(errs...)
+}
+
+type providerDoc struct {
+ url string
+ body []byte
+}
+
+// get fetches u and returns the body of a 2xx answer. Anything else is
+// already in the fetcher's checked list.
+func get(ctx context.Context, f fetch.Fetcher, u string, reason fetch.Reason) ([]byte, bool) {
+ resp, err := f.Get(ctx, u, reason)
+ if err != nil || resp.StatusCode < 200 || resp.StatusCode >= 300 {
+ return nil, false
+ }
+ return resp.Body, true
+}
+
+func absHTTP(raw string) (string, bool) {
+ u, err := url.Parse(strings.TrimSpace(raw))
+ if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
+ return "", false
+ }
+ return u.String(), true
+}
+
+// providerMetadata is the part of a CSAF provider-metadata.json discovery
+// reads (CSAF 2.0, section 7.1.20).
+type providerMetadata struct {
+ CanonicalURL string `json:"canonical_url"`
+ MetadataVersion string `json:"metadata_version"`
+ Distributions []struct {
+ ROLIE *struct {
+ Feeds []struct {
+ URL string `json:"url"`
+ TLPLabel string `json:"tlp_label"`
+ } `json:"feeds"`
+ } `json:"rolie"`
+ } `json:"distributions"`
+}
+
+func parseProviderMetadata(body []byte) (*providerMetadata, error) {
+ var pm providerMetadata
+ if err := json.Unmarshal(body, &pm); err != nil {
+ return nil, fmt.Errorf("provider metadata: %v", err)
+ }
+ if pm.CanonicalURL == "" || pm.MetadataVersion == "" {
+ return nil, errors.New("provider metadata: canonical_url and metadata_version are required")
+ }
+ return &pm, nil
+}
+
+// feedURLs returns the provider's public ROLIE feeds. Directory-based
+// distributions are not followed: their index files are not named by URL
+// in the metadata, and the passive rule forbids synthesizing a path.
+func (pm *providerMetadata) feedURLs() []string {
+ var out []string
+ for _, d := range pm.Distributions {
+ if d.ROLIE == nil {
+ continue
+ }
+ for _, feed := range d.ROLIE.Feeds {
+ tlp := strings.ToUpper(feed.TLPLabel)
+ if tlp != "" && tlp != "WHITE" && tlp != "CLEAR" {
+ continue
+ }
+ if u, ok := absHTTP(feed.URL); ok {
+ out = append(out, u)
+ }
+ }
+ }
+ return out
+}
+
+type rolieFeed struct {
+ Feed *struct {
+ Entry []struct {
+ Updated string `json:"updated"`
+ Link []struct {
+ Rel string `json:"rel"`
+ Href string `json:"href"`
+ } `json:"link"`
+ Content struct {
+ Src string `json:"src"`
+ } `json:"content"`
+ } `json:"entry"`
+ } `json:"feed"`
+}
+
+type feedEntry struct {
+ url string
+ updated time.Time
+}
+
+// parseROLIEFeed lists a CSAF ROLIE feed's documents: each entry's
+// content src, else its self link.
+func parseROLIEFeed(body []byte) ([]feedEntry, error) {
+ var rf rolieFeed
+ if err := json.Unmarshal(body, &rf); err != nil {
+ return nil, fmt.Errorf("ROLIE feed: %v", err)
+ }
+ if rf.Feed == nil {
+ return nil, errors.New("ROLIE feed: no feed object")
+ }
+ var out []feedEntry
+ for _, e := range rf.Feed.Entry {
+ href := e.Content.Src
+ if href == "" {
+ for _, l := range e.Link {
+ if l.Rel == "self" {
+ href = l.Href
+ break
+ }
+ }
+ }
+ u, ok := absHTTP(href)
+ if !ok {
+ continue
+ }
+ updated, _ := time.Parse(time.RFC3339, e.Updated)
+ out = append(out, feedEntry{u, updated})
+ }
+ return out, nil
+}
+
+// newest returns up to n distinct document URLs, most recently updated
+// first; entries without a valid timestamp sort last, in feed order.
+func newest(entries []feedEntry, n int) []string {
+ slices.SortStableFunc(entries, func(a, b feedEntry) int {
+ return b.updated.Compare(a.updated)
+ })
+ var out []string
+ for _, e := range entries {
+ if len(out) >= n {
+ break
+ }
+ if !slices.Contains(out, e.url) {
+ out = append(out, e.url)
+ }
+ }
+ return out
+}
diff --git a/internal/discover/discover_test.go b/internal/discover/discover_test.go
new file mode 100644
index 0000000..015e2c2
--- /dev/null
+++ b/internal/discover/discover_test.go
@@ -0,0 +1,269 @@
+package discover
+
+import (
+ "context"
+ "net/url"
+ "reflect"
+ "testing"
+
+ "github.com/FootprintAI/touchstone/internal/fetch"
+ "github.com/FootprintAI/touchstone/internal/pipeline"
+)
+
+func TestParseSecurityTxt(t *testing.T) {
+ tests := []struct {
+ name string
+ in string
+ want SecurityTxt
+ }{
+ {
+ name: "multiple CSAF fields, comments, CRLF",
+ in: "# Our security contacts\r\n" +
+ "Contact: mailto:security@vendor.example\r\n" +
+ "Expires: 2027-01-01T00:00:00Z\r\n" +
+ "\r\n" +
+ "CSAF: https://vendor.example/.well-known/csaf/provider-metadata.json\r\n" +
+ "csaf: https://csaf.vendor.example/provider-metadata.json\r\n" +
+ "Policy: https://vendor.example/policy\r\n",
+ want: SecurityTxt{
+ Contact: []string{"mailto:security@vendor.example"},
+ Expires: "2027-01-01T00:00:00Z",
+ CSAF: []string{
+ "https://vendor.example/.well-known/csaf/provider-metadata.json",
+ "https://csaf.vendor.example/provider-metadata.json",
+ },
+ },
+ },
+ {
+ name: "OpenPGP cleartext signature",
+ in: "-----BEGIN PGP SIGNED MESSAGE-----\n" +
+ "Hash: SHA256\n\n" +
+ "Contact: https://vendor.example/report\n" +
+ "- CSAF: https://vendor.example/pm.json\n" +
+ "-----BEGIN PGP SIGNATURE-----\n" +
+ "CSAF: https://not-a-field.example/\n" +
+ "-----END PGP SIGNATURE-----\n",
+ want: SecurityTxt{
+ Contact: []string{"https://vendor.example/report"},
+ CSAF: []string{"https://vendor.example/pm.json"},
+ },
+ },
+ {
+ name: "not a security.txt",
+ in: "Not found",
+ want: SecurityTxt{},
+ },
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if got := ParseSecurityTxt([]byte(tt.in)); !reflect.DeepEqual(*got, tt.want) {
+ t.Errorf("ParseSecurityTxt =\n%+v\nwant\n%+v", *got, tt.want)
+ }
+ })
+ }
+}
+
+func TestRepoLinks(t *testing.T) {
+ page, _ := url.Parse("https://vendor.example/about")
+ body := `
+Source
+same repo, other page
+GitLab
+not http
+clone URL
+
+
+badge
+Sign in
+Sponsor
+Share
+profile, not a repo
+
+`
+ got, err := RepoLinks(page, []byte(body))
+ if err != nil {
+ t.Fatalf("RepoLinks: %v", err)
+ }
+ want := []string{
+ "https://github.com/vendor/app",
+ "https://gitlab.com/group/sub/project",
+ "https://github.com/vendor/lib",
+ "https://github.com/vendor/logo",
+ }
+ if !reflect.DeepEqual(got, want) {
+ t.Errorf("RepoLinks =\n%q\nwant\n%q", got, want)
+ }
+}
+
+const (
+ target = "https://vendor.example/"
+ wellKnown = "https://vendor.example/.well-known/csaf/provider-metadata.json"
+ declaredPM = "https://csaf.vendor.example/provider-metadata.json"
+ feedURL = "https://csaf.vendor.example/white/feed.json"
+ vexURL = "https://csaf.vendor.example/white/2026/vex-1.json"
+ advisory = "https://csaf.vendor.example/white/2025/adv-1.json"
+)
+
+const providerMetadataJSON = `{
+ "canonical_url": "` + declaredPM + `",
+ "metadata_version": "2.0",
+ "role": "csaf_provider",
+ "distributions": [
+ {"rolie": {"feeds": [
+ {"tlp_label": "WHITE", "url": "` + feedURL + `"},
+ {"tlp_label": "AMBER", "url": "https://csaf.vendor.example/amber/feed.json"}
+ ]}},
+ {"directory_url": "https://csaf.vendor.example/white/"}
+ ]
+}`
+
+const feedJSON = `{"feed": {"id": "vendor-white", "entry": [
+ {"id": "adv-1", "updated": "2025-03-01T00:00:00Z", "content": {"type": "application/json", "src": "` + advisory + `"}},
+ {"id": "vex-1", "updated": "2026-09-01T00:00:00Z", "link": [{"rel": "self", "href": "` + vexURL + `"}]}
+]}}`
+
+const vexJSON = `{
+ "document": {"category": "csaf_vex", "csaf_version": "2.0"},
+ "product_tree": {"full_product_names": [
+ {"product_id": "P1", "name": "jquery 3.7.1", "product_identification_helper": {"purl": "pkg:npm/jquery@3.7.1"}}
+ ]}
+}`
+
+const advisoryJSON = `{
+ "document": {"category": "csaf_security_advisory", "csaf_version": "2.0"},
+ "product_tree": {"full_product_names": [{"product_id": "P9", "name": "Other product"}]}
+}`
+
+func ok(u, body string) *fetch.Response {
+ return &fetch.Response{URL: u, StatusCode: 200, Body: []byte(body)}
+}
+
+func notFound(u string) *fetch.Response {
+ return &fetch.Response{URL: u, StatusCode: 404}
+}
+
+// vendorFake is a vendor publishing security.txt with two CSAF fields (one
+// the well-known URL), provider metadata with one public ROLIE feed, and a
+// TEA document that names an endpoint discovery must not query.
+func vendorFake() *fetch.Fake {
+ f := fetch.NewFake()
+ f.SetResponse(target+".well-known/security.txt", ok(target+".well-known/security.txt",
+ "Contact: mailto:psirt@vendor.example\nCSAF: "+wellKnown+"\nCSAF: "+declaredPM+"\n"))
+ f.SetResponse(wellKnown, ok(wellKnown, providerMetadataJSON))
+ f.SetResponse(target+".well-known/tea", ok(target+".well-known/tea",
+ `{"endpoints": [{"url": "https://tea.vendor.example/v1"}]}`))
+ f.SetResponse(declaredPM, ok(declaredPM, providerMetadataJSON))
+ f.SetResponse(feedURL, ok(feedURL, feedJSON))
+ f.SetResponse(vexURL, ok(vexURL, vexJSON))
+ f.SetResponse(advisory, ok(advisory, advisoryJSON))
+ return f
+}
+
+func TestDiscoverFollowsSecurityTxtToCSAFVEX(t *testing.T) {
+ f := vendorFake()
+ page := ok(target, `code`)
+ res, err := Discover(context.Background(), f, target, page)
+ if err != nil {
+ t.Fatalf("Discover: %v", err)
+ }
+
+ wantCalls := []fetch.Call{
+ {URL: target + ".well-known/security.txt", Reason: fetch.ReasonDiscoveryPath},
+ {URL: wellKnown, Reason: fetch.ReasonDiscoveryPath},
+ {URL: target + ".well-known/tea", Reason: fetch.ReasonDiscoveryPath},
+ {URL: declaredPM, Reason: fetch.ReasonDeclared},
+ {URL: feedURL, Reason: fetch.ReasonDeclared},
+ {URL: vexURL, Reason: fetch.ReasonDeclared},
+ {URL: advisory, Reason: fetch.ReasonDeclared},
+ }
+ if !reflect.DeepEqual(f.Calls, wantCalls) {
+ t.Errorf("calls =\n%v\nwant\n%v", f.Calls, wantCalls)
+ }
+
+ if res.SecurityTxt == nil || len(res.SecurityTxt.CSAF) != 2 {
+ t.Errorf("SecurityTxt = %+v, want two CSAF fields", res.SecurityTxt)
+ }
+ if want := []string{declaredPM, wellKnown}; !reflect.DeepEqual(res.ProviderMetadata, want) {
+ t.Errorf("ProviderMetadata = %q, want %q", res.ProviderMetadata, want)
+ }
+ if want := []string{vexURL}; !reflect.DeepEqual(res.VEXDocuments, want) {
+ t.Errorf("VEXDocuments = %q, want only the csaf_vex document %q", res.VEXDocuments, want)
+ }
+ if !res.TEA {
+ t.Error("TEA = false, want the /.well-known/tea document recorded")
+ }
+ if want := []string{"https://github.com/vendor/app"}; !reflect.DeepEqual(res.RepoLinks, want) {
+ t.Errorf("RepoLinks = %q, want %q", res.RepoLinks, want)
+ }
+ wantComps := []pipeline.Component{{
+ Name: "jquery", Version: "3.7.1", Purl: "pkg:npm/jquery@3.7.1", Confidence: "HIGH",
+ Evidence: []pipeline.Evidence{{Kind: "VEX", Location: vexURL, Detail: "CSAF VEX product"}},
+ }}
+ if !reflect.DeepEqual(res.Components, wantComps) {
+ t.Errorf("Components =\n%+v\nwant\n%+v", res.Components, wantComps)
+ }
+}
+
+func TestDiscoverFallsBackToRootSecurityTxt(t *testing.T) {
+ f := fetch.NewFake()
+ f.SetResponse(target+".well-known/security.txt", notFound(target+".well-known/security.txt"))
+ f.SetResponse(target+"security.txt", ok(target+"security.txt", "Contact: mailto:a@vendor.example\n"))
+ f.SetResponse(wellKnown, notFound(wellKnown))
+ f.SetResponse(target+".well-known/tea", notFound(target+".well-known/tea"))
+
+ res, err := Discover(context.Background(), f, target, nil)
+ if err != nil {
+ t.Fatalf("Discover: %v", err)
+ }
+ if res.SecurityTxt == nil || len(res.SecurityTxt.Contact) != 1 {
+ t.Errorf("SecurityTxt = %+v, want the root security.txt", res.SecurityTxt)
+ }
+ if res.TEA || len(res.ProviderMetadata) != 0 || len(res.Components) != 0 {
+ t.Errorf("result = %+v, want nothing beyond security.txt", res)
+ }
+ if len(f.Calls) != 4 {
+ t.Errorf("calls = %v, want the four discovery paths only", f.Calls)
+ }
+ for _, c := range f.Calls {
+ if c.Reason != fetch.ReasonDiscoveryPath {
+ t.Errorf("call %v, want only DISCOVERY_PATH requests", c)
+ }
+ }
+}
+
+func TestDiscoverReportsUnreadableDocuments(t *testing.T) {
+ f := fetch.NewFake()
+ f.SetResponse(wellKnown, ok(wellKnown, "soft 404"))
+ res, err := Discover(context.Background(), f, target, nil)
+ if err == nil {
+ t.Fatal("Discover: want an error for provider metadata that is not JSON")
+ }
+ if res == nil || len(res.ProviderMetadata) != 0 {
+ t.Errorf("result = %+v, want a result without provider metadata", res)
+ }
+}
+
+func TestDiscoverCapsDocuments(t *testing.T) {
+ f := fetch.NewFake()
+ f.SetResponse(wellKnown, ok(wellKnown, providerMetadataJSON))
+ feed := `{"feed": {"entry": [`
+ for i := range MaxDocuments + 3 {
+ if i > 0 {
+ feed += ","
+ }
+ feed += `{"content": {"src": "https://csaf.vendor.example/white/d` + string(rune('a'+i)) + `.json"}}`
+ }
+ feed += `]}}`
+ f.SetResponse(feedURL, ok(feedURL, feed))
+
+ _, _ = Discover(context.Background(), f, target, nil)
+ docs := 0
+ for _, c := range f.Calls {
+ if c.Reason == fetch.ReasonDeclared && c.URL != feedURL {
+ docs++
+ }
+ }
+ if docs != MaxDocuments {
+ t.Errorf("fetched %d CSAF documents, want the cap of %d", docs, MaxDocuments)
+ }
+}
diff --git a/internal/discover/repolinks.go b/internal/discover/repolinks.go
new file mode 100644
index 0000000..4c5b68f
--- /dev/null
+++ b/internal/discover/repolinks.go
@@ -0,0 +1,131 @@
+package discover
+
+import (
+ "bytes"
+ "net/url"
+ "path"
+ "strings"
+
+ "golang.org/x/net/html"
+)
+
+// forgeHosts are the hosts whose repo links are extracted, by the name the
+// link is normalized to.
+var forgeHosts = map[string]string{
+ "github.com": "github.com",
+ "www.github.com": "github.com",
+ "gitlab.com": "gitlab.com",
+ "www.gitlab.com": "gitlab.com",
+}
+
+// reservedOwners are first path segments on GitHub and GitLab that are
+// site pages, not accounts: login and share targets, marketing pages,
+// settings, search.
+var reservedOwners = map[string]bool{
+ "-": true, "about": true, "apps": true, "collections": true, "contact": true,
+ "dashboard": true, "enterprise": true, "explore": true, "features": true,
+ "help": true, "join": true, "login": true, "logout": true, "marketplace": true,
+ "new": true, "notifications": true, "orgs": true, "pricing": true, "search": true,
+ "security": true, "sessions": true, "settings": true, "share": true, "signup": true,
+ "site": true, "sponsors": true, "topics": true, "trending": true, "users": true,
+ "users_sign_in": true,
+}
+
+// RepoLinks returns the GitHub and GitLab repositories the page links to
+// with , normalized to https://host/owner/repo (GitLab keeps its
+// subgroups), each once, in page order. Badge links (an image-only link
+// to a badge image, or a link to a badge itself) and links to site pages
+// such as login or share targets are ignored.
+func RepoLinks(page *url.URL, body []byte) ([]string, error) {
+ doc, err := html.Parse(bytes.NewReader(body))
+ if err != nil {
+ return nil, err
+ }
+ var out []string
+ seen := map[string]bool{}
+ var walk func(*html.Node)
+ walk = func(n *html.Node) {
+ if n.Type == html.ElementNode && n.Data == "a" && !isBadge(n) {
+ if repo, ok := repoURL(page, attr(n, "href")); ok && !seen[strings.ToLower(repo)] {
+ seen[strings.ToLower(repo)] = true
+ out = append(out, repo)
+ }
+ }
+ for c := n.FirstChild; c != nil; c = c.NextSibling {
+ walk(c)
+ }
+ }
+ walk(doc)
+ return out, nil
+}
+
+// repoURL normalizes href to a repository URL, if it names one.
+func repoURL(page *url.URL, href string) (string, bool) {
+ ref, err := url.Parse(strings.TrimSpace(href))
+ if err != nil {
+ return "", false
+ }
+ u := page.ResolveReference(ref)
+ host, ok := forgeHosts[strings.ToLower(u.Hostname())]
+ if !ok || (u.Scheme != "http" && u.Scheme != "https") {
+ return "", false
+ }
+ p := strings.ToLower(u.Path)
+ if strings.Contains(p, "badge") || path.Ext(p) == ".svg" || path.Ext(p) == ".png" {
+ return "", false
+ }
+ var segs []string
+ for _, s := range strings.Split(u.Path, "/") {
+ if s == "" {
+ continue
+ }
+ // GitLab puts every page under a project after a "-" segment.
+ if s == "-" {
+ break
+ }
+ segs = append(segs, s)
+ }
+ if host == "github.com" && len(segs) > 2 {
+ segs = segs[:2]
+ }
+ if len(segs) < 2 || reservedOwners[strings.ToLower(segs[0])] {
+ return "", false
+ }
+ segs[len(segs)-1] = strings.TrimSuffix(segs[len(segs)-1], ".git")
+ return "https://" + host + "/" + strings.Join(segs, "/"), true
+}
+
+// isBadge reports whether the link a shows only an image (no text) and
+// that image is a badge, such as a shields.io status badge.
+func isBadge(a *html.Node) bool {
+ badge := false
+ var walk func(*html.Node) bool
+ walk = func(n *html.Node) bool {
+ for c := n.FirstChild; c != nil; c = c.NextSibling {
+ switch {
+ case c.Type == html.TextNode && strings.TrimSpace(c.Data) != "":
+ return false
+ case c.Type == html.ElementNode && c.Data == "img":
+ src := strings.ToLower(attr(c, "src"))
+ if strings.Contains(src, "badge") || strings.Contains(src, "shields.io") {
+ badge = true
+ }
+ case c.Type == html.ElementNode:
+ if !walk(c) {
+ return false
+ }
+ }
+ }
+ return true
+ }
+ return walk(a) && badge
+}
+
+func attr(n *html.Node, name string) string {
+ for _, a := range n.Attr {
+ if a.Key == name {
+ return a.Val
+ }
+ }
+ return ""
+}
diff --git a/internal/discover/securitytxt.go b/internal/discover/securitytxt.go
new file mode 100644
index 0000000..20a65ee
--- /dev/null
+++ b/internal/discover/securitytxt.go
@@ -0,0 +1,59 @@
+package discover
+
+import "strings"
+
+// SecurityTxt is the part of an RFC 9116 security.txt that discovery
+// uses. Field names are matched case-insensitively and every occurrence
+// of a field is kept, in file order.
+type SecurityTxt struct {
+ Contact []string
+ Expires string
+ // CSAF holds the values of every CSAF: field (CSAF 2.0, section
+ // 7.1.8): URLs of provider-metadata.json documents.
+ CSAF []string
+}
+
+// ParseSecurityTxt reads a security.txt. It is lenient, as a reader should
+// be: comments, blank lines, CRLF line endings, unknown fields and an
+// OpenPGP cleartext signature are all accepted, and a line that is not a
+// field is skipped.
+func ParseSecurityTxt(body []byte) *SecurityTxt {
+ st := &SecurityTxt{}
+ inSignature := false
+ for _, line := range strings.Split(string(body), "\n") {
+ line = strings.TrimRight(line, "\r")
+ switch {
+ case strings.HasPrefix(line, "-----BEGIN PGP SIGNATURE-----"):
+ inSignature = true
+ continue
+ case strings.HasPrefix(line, "-----END PGP SIGNATURE-----"):
+ inSignature = false
+ continue
+ case inSignature, strings.HasPrefix(line, "-----BEGIN PGP SIGNED MESSAGE-----"):
+ continue
+ }
+ // Dash-escaped lines of a cleartext-signed message (RFC 4880, 7.1).
+ line = strings.TrimPrefix(line, "- ")
+ line = strings.TrimSpace(line)
+ if line == "" || strings.HasPrefix(line, "#") {
+ continue
+ }
+ name, value, ok := strings.Cut(line, ":")
+ if !ok {
+ continue
+ }
+ value = strings.TrimSpace(value)
+ if value == "" {
+ continue
+ }
+ switch strings.ToLower(strings.TrimSpace(name)) {
+ case "contact":
+ st.Contact = append(st.Contact, value)
+ case "expires":
+ st.Expires = value
+ case "csaf":
+ st.CSAF = append(st.CSAF, value)
+ }
+ }
+ return st
+}
diff --git a/internal/fetch/fetch.go b/internal/fetch/fetch.go
index f3c56a4..e080d82 100644
--- a/internal/fetch/fetch.go
+++ b/internal/fetch/fetch.go
@@ -7,8 +7,9 @@ import "context"
// Reason is why a request is allowed. It mirrors the CheckedLocation.reason
// values in proto/touchstone/v1/scan.proto (TARGET, SUBRESOURCE,
-// DISCOVERY_PATH, DECLARED); FORGE_API is handled by repo.Forge instead,
-// since it never counts against the vendor's request budget.
+// DISCOVERY_PATH, DECLARED), plus SUPPLIED for the SBOM/VEX URL the
+// reviewer entered (decision D1); FORGE_API is handled by repo.Forge
+// instead, since it never counts against the vendor's request budget.
type Reason string
const (
@@ -16,6 +17,7 @@ const (
ReasonSubresource Reason = "SUBRESOURCE"
ReasonDiscoveryPath Reason = "DISCOVERY_PATH"
ReasonDeclared Reason = "DECLARED"
+ ReasonSupplied Reason = "SUPPLIED"
)
// Response is the subset of an HTTP response any evidence source needs.
diff --git a/internal/fetch/passive.go b/internal/fetch/passive.go
index 5cbafea..a3c66b1 100644
--- a/internal/fetch/passive.go
+++ b/internal/fetch/passive.go
@@ -64,6 +64,9 @@ type Options struct {
Version string
// Resolver is used for host names; net.DefaultResolver if nil.
Resolver Resolver
+ // SuppliedURL is the SBOM/VEX URL the reviewer entered, the only URL
+ // a SUPPLIED request may fetch. Empty means SUPPLIED is refused.
+ SuppliedURL string
}
// PassiveFetcher is the only Fetcher that talks to a vendor site. It sends
@@ -72,6 +75,7 @@ type Options struct {
// request (refused ones included) for the report's checked list.
type PassiveFetcher struct {
target *url.URL
+ supplied string
userAgent string
client *http.Client
@@ -112,8 +116,18 @@ func New(target string, opts Options) (*PassiveFetcher, error) {
resolver = net.DefaultResolver
}
+ var supplied string
+ if opts.SuppliedURL != "" {
+ s, err := parseHTTPURL(opts.SuppliedURL)
+ if err != nil {
+ return nil, err
+ }
+ supplied = s.String()
+ }
+
f := &PassiveFetcher{
target: t,
+ supplied: supplied,
userAgent: "Touchstone/" + version + " (+https://github.com/FootprintAI/touchstone)",
timeout: RequestTimeout,
budget: budget,
@@ -219,6 +233,10 @@ func (f *PassiveFetcher) allow(rawURL string, reason Reason) (*url.URL, error) {
if !sameOrigin(u, f.target) || u.RawQuery != "" || !slices.Contains(DiscoveryPaths, u.EscapedPath()) {
return nil, fmt.Errorf("%w: %s is not a discovery path on %s", ErrRefused, u, origin(f.target))
}
+ case ReasonSupplied:
+ if f.supplied == "" || u.String() != f.supplied {
+ return nil, fmt.Errorf("%w: SUPPLIED must be the reviewer's SBOM/VEX URL, got %s", ErrRefused, u)
+ }
case ReasonSubresource, ReasonDeclared:
// Taken from a fetched document by the caller; nothing to check
// beyond the URL itself.
diff --git a/internal/fetch/passive_test.go b/internal/fetch/passive_test.go
index ef98d85..97ff8eb 100644
--- a/internal/fetch/passive_test.go
+++ b/internal/fetch/passive_test.go
@@ -85,6 +85,8 @@ func TestAllowReason(t *testing.T) {
{"discovery unknown path", srv.URL + "/.env", ReasonDiscoveryPath, true},
{"discovery with query", srv.URL + "/.well-known/security.txt?x=1", ReasonDiscoveryPath, true},
{"discovery other origin", "https://other.example/.well-known/security.txt", ReasonDiscoveryPath, true},
+ {"supplied", srv.URL + "/sbom.json", ReasonSupplied, false},
+ {"supplied other URL", srv.URL + "/other.json", ReasonSupplied, true},
{"forge api reason", srv.URL + "/repos/x", Reason("FORGE_API"), true},
{"empty reason", srv.URL + "/x", Reason(""), true},
{"unknown reason", srv.URL + "/x", Reason("CRAWL"), true},
@@ -93,7 +95,7 @@ func TestAllowReason(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- f := mustNew(t, target, Options{AllowPrivate: true})
+ f := mustNew(t, target, Options{AllowPrivate: true, SuppliedURL: srv.URL + "/sbom.json"})
before := s.count()
_, err := f.Get(context.Background(), tt.url, tt.reason)
got := lastChecked(t, f)
@@ -125,6 +127,17 @@ func TestAllowReason(t *testing.T) {
}
}
+func TestSuppliedRefusedWithoutSuppliedURL(t *testing.T) {
+ srv, s := okServer(t)
+ f := mustNew(t, srv.URL+"/", Options{AllowPrivate: true})
+ if _, err := f.Get(context.Background(), srv.URL+"/sbom.json", ReasonSupplied); !errors.Is(err, ErrRefused) {
+ t.Fatalf("Get: err = %v, want ErrRefused", err)
+ }
+ if s.count() != 0 {
+ t.Error("refused request reached the server")
+ }
+}
+
func TestRequestIsPassiveGET(t *testing.T) {
srv, s := okServer(t)
f := mustNew(t, srv.URL+"/page", Options{AllowPrivate: true, Version: "1.2.3"})
diff --git a/internal/sbom/sbom.go b/internal/sbom/sbom.go
new file mode 100644
index 0000000..f78e738
--- /dev/null
+++ b/internal/sbom/sbom.go
@@ -0,0 +1,293 @@
+// Package sbom reads SBOM and VEX documents into normalized components.
+// It does no I/O. This is the minimal reader discovery (slice S5) needs:
+// it detects the format and lists the components or products a document
+// names. Full parsers with VEX statements and their application to
+// vulnerabilities are slice S4.
+package sbom
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net/url"
+ "strings"
+)
+
+// Format names a supported document format.
+type Format string
+
+const (
+ FormatCycloneDX Format = "CycloneDX"
+ FormatSPDX Format = "SPDX"
+ FormatOpenVEX Format = "OpenVEX"
+ FormatCSAF Format = "CSAF"
+)
+
+// ErrUnknownFormat is returned for input that is not a JSON document in a
+// supported format.
+var ErrUnknownFormat = errors.New("sbom: not a CycloneDX, SPDX 2.3, OpenVEX or CSAF 2.0 JSON document")
+
+// Component is one piece of software a document names.
+type Component struct {
+ Name string
+ Version string
+ Purl string
+ CPE string
+}
+
+// Document is a parsed SBOM or VEX document.
+type Document struct {
+ Format Format
+ // VEX is true for OpenVEX, for CSAF with document.category csaf_vex,
+ // and for CycloneDX carrying vulnerabilities (CycloneDX VEX).
+ VEX bool
+ Components []Component
+}
+
+// probe holds the fields that tell the formats apart.
+type probe struct {
+ BOMFormat string `json:"bomFormat"`
+ SPDXVersion string `json:"spdxVersion"`
+ Context string `json:"@context"`
+ Document json.RawMessage `json:"document"`
+}
+
+// Parse detects the format of data and lists its components.
+func Parse(data []byte) (*Document, error) {
+ var p probe
+ if err := json.Unmarshal(data, &p); err != nil {
+ return nil, fmt.Errorf("%w: %v", ErrUnknownFormat, err)
+ }
+ switch {
+ case p.BOMFormat == "CycloneDX":
+ return parseCycloneDX(data)
+ case strings.HasPrefix(p.SPDXVersion, "SPDX-"):
+ return parseSPDX(data)
+ case strings.Contains(p.Context, "openvex"):
+ return parseOpenVEX(data)
+ case len(p.Document) > 0:
+ return ParseCSAF(data)
+ default:
+ return nil, ErrUnknownFormat
+ }
+}
+
+type cdxComponent struct {
+ Name string `json:"name"`
+ Group string `json:"group"`
+ Version string `json:"version"`
+ Purl string `json:"purl"`
+ CPE string `json:"cpe"`
+ Components []cdxComponent `json:"components"`
+}
+
+type cdxBOM struct {
+ Components []cdxComponent `json:"components"`
+ Vulnerabilities []json.RawMessage `json:"vulnerabilities"`
+}
+
+func parseCycloneDX(data []byte) (*Document, error) {
+ var bom cdxBOM
+ if err := json.Unmarshal(data, &bom); err != nil {
+ return nil, fmt.Errorf("sbom: CycloneDX: %v", err)
+ }
+ doc := &Document{Format: FormatCycloneDX, VEX: len(bom.Vulnerabilities) > 0}
+ var walk func([]cdxComponent)
+ walk = func(cs []cdxComponent) {
+ for _, c := range cs {
+ name := c.Name
+ if c.Group != "" {
+ name = c.Group + "/" + c.Name
+ }
+ doc.add(Component{Name: name, Version: c.Version, Purl: c.Purl, CPE: c.CPE})
+ walk(c.Components)
+ }
+ }
+ walk(bom.Components)
+ return doc, nil
+}
+
+type spdxDocument struct {
+ Packages []struct {
+ Name string `json:"name"`
+ VersionInfo string `json:"versionInfo"`
+ ExternalRefs []struct {
+ ReferenceType string `json:"referenceType"`
+ ReferenceLocator string `json:"referenceLocator"`
+ } `json:"externalRefs"`
+ } `json:"packages"`
+}
+
+func parseSPDX(data []byte) (*Document, error) {
+ var sd spdxDocument
+ if err := json.Unmarshal(data, &sd); err != nil {
+ return nil, fmt.Errorf("sbom: SPDX: %v", err)
+ }
+ doc := &Document{Format: FormatSPDX}
+ for _, p := range sd.Packages {
+ c := Component{Name: p.Name, Version: p.VersionInfo}
+ for _, ref := range p.ExternalRefs {
+ switch ref.ReferenceType {
+ case "purl":
+ c.Purl = ref.ReferenceLocator
+ case "cpe23Type", "cpe22Type":
+ if c.CPE == "" {
+ c.CPE = ref.ReferenceLocator
+ }
+ }
+ }
+ doc.add(c)
+ }
+ return doc, nil
+}
+
+type openVEXDocument struct {
+ Statements []struct {
+ Products []struct {
+ ID string `json:"@id"`
+ Identifiers struct {
+ Purl string `json:"purl"`
+ CPE23 string `json:"cpe23"`
+ } `json:"identifiers"`
+ } `json:"products"`
+ } `json:"statements"`
+}
+
+func parseOpenVEX(data []byte) (*Document, error) {
+ var vd openVEXDocument
+ if err := json.Unmarshal(data, &vd); err != nil {
+ return nil, fmt.Errorf("sbom: OpenVEX: %v", err)
+ }
+ doc := &Document{Format: FormatOpenVEX, VEX: true}
+ for _, s := range vd.Statements {
+ for _, p := range s.Products {
+ c := Component{Purl: p.Identifiers.Purl, CPE: p.Identifiers.CPE23}
+ if c.Purl == "" && strings.HasPrefix(p.ID, "pkg:") {
+ c.Purl = p.ID
+ }
+ if c.Purl == "" && c.CPE == "" {
+ c.Name = p.ID
+ }
+ doc.add(c)
+ }
+ }
+ return doc, nil
+}
+
+type csafDocument struct {
+ Document struct {
+ Category string `json:"category"`
+ CSAFVersion string `json:"csaf_version"`
+ } `json:"document"`
+ ProductTree struct {
+ Branches []csafBranch `json:"branches"`
+ FullProductNames []csafProduct `json:"full_product_names"`
+ } `json:"product_tree"`
+}
+
+type csafBranch struct {
+ Category string `json:"category"`
+ Name string `json:"name"`
+ Branches []csafBranch `json:"branches"`
+ Product *csafProduct `json:"product"`
+}
+
+type csafProduct struct {
+ ProductID string `json:"product_id"`
+ Name string `json:"name"`
+ Helper struct {
+ CPE string `json:"cpe"`
+ Purl string `json:"purl"`
+ } `json:"product_identification_helper"`
+}
+
+// ParseCSAF reads a CSAF 2.0 document. Its components are the products in
+// the product tree: the name and version come from the enclosing
+// product_name and product_version branches when present, else from the
+// product's purl, else from its full name.
+func ParseCSAF(data []byte) (*Document, error) {
+ var cd csafDocument
+ if err := json.Unmarshal(data, &cd); err != nil {
+ return nil, fmt.Errorf("sbom: CSAF: %v", err)
+ }
+ if cd.Document.CSAFVersion == "" || cd.Document.Category == "" {
+ return nil, errors.New("sbom: CSAF: document.csaf_version and document.category are required")
+ }
+ doc := &Document{Format: FormatCSAF, VEX: cd.Document.Category == "csaf_vex"}
+ var walk func(bs []csafBranch, name, version string)
+ walk = func(bs []csafBranch, name, version string) {
+ for _, b := range bs {
+ n, v := name, version
+ switch b.Category {
+ case "product_name":
+ n = b.Name
+ case "product_version":
+ v = b.Name
+ }
+ if b.Product != nil {
+ doc.add(csafComponent(*b.Product, n, v))
+ }
+ walk(b.Branches, n, v)
+ }
+ }
+ walk(cd.ProductTree.Branches, "", "")
+ for _, p := range cd.ProductTree.FullProductNames {
+ doc.add(csafComponent(p, "", ""))
+ }
+ return doc, nil
+}
+
+func csafComponent(p csafProduct, name, version string) Component {
+ // A purl names the package better than the product's full name, which
+ // usually includes the vendor and version; add fills it in.
+ if name == "" && p.Helper.Purl == "" {
+ name = p.Name
+ }
+ return Component{Name: name, Version: version, Purl: p.Helper.Purl, CPE: p.Helper.CPE}
+}
+
+// add appends c, filling the name and version from its purl when the
+// document left them out, and skips a component that names nothing or
+// repeats one already listed.
+func (d *Document) add(c Component) {
+ if c.Purl != "" && (c.Name == "" || c.Version == "") {
+ name, version := purlNameVersion(c.Purl)
+ if c.Name == "" {
+ c.Name = name
+ }
+ if c.Version == "" {
+ c.Version = version
+ }
+ }
+ if c.Name == "" && c.Purl == "" && c.CPE == "" {
+ return
+ }
+ for _, have := range d.Components {
+ if have == c {
+ return
+ }
+ }
+ d.Components = append(d.Components, c)
+}
+
+// purlNameVersion returns the name and version of a package URL,
+// pkg:type/namespace/name@version?qualifiers#subpath.
+func purlNameVersion(purl string) (name, version string) {
+ rest := strings.TrimPrefix(purl, "pkg:")
+ if i := strings.IndexAny(rest, "?#"); i >= 0 {
+ rest = rest[:i]
+ }
+ if i := strings.LastIndex(rest, "@"); i >= 0 && i > strings.LastIndex(rest, "/") {
+ version, rest = rest[i+1:], rest[:i]
+ }
+ if i := strings.LastIndex(rest, "/"); i >= 0 {
+ rest = rest[i+1:]
+ }
+ if n, err := url.PathUnescape(rest); err == nil {
+ rest = n
+ }
+ if v, err := url.PathUnescape(version); err == nil {
+ version = v
+ }
+ return rest, version
+}
diff --git a/internal/sbom/sbom_test.go b/internal/sbom/sbom_test.go
new file mode 100644
index 0000000..9c9bf3a
--- /dev/null
+++ b/internal/sbom/sbom_test.go
@@ -0,0 +1,125 @@
+package sbom
+
+import (
+ "errors"
+ "reflect"
+ "testing"
+)
+
+const cycloneDX = `{
+ "bomFormat": "CycloneDX", "specVersion": "1.6",
+ "components": [
+ {"name": "jquery", "version": "3.7.1", "purl": "pkg:npm/jquery@3.7.1",
+ "components": [{"name": "sizzle", "version": "2.3.10", "purl": "pkg:npm/sizzle@2.3.10"}]},
+ {"group": "org.apache.logging.log4j", "name": "log4j-core", "version": "2.17.1"}
+ ]
+}`
+
+const spdx = `{
+ "spdxVersion": "SPDX-2.3",
+ "packages": [
+ {"name": "lodash", "versionInfo": "4.17.21",
+ "externalRefs": [{"referenceCategory": "PACKAGE-MANAGER", "referenceType": "purl", "referenceLocator": "pkg:npm/lodash@4.17.21"}]},
+ {"name": "openssl", "versionInfo": "3.0.13",
+ "externalRefs": [{"referenceCategory": "SECURITY", "referenceType": "cpe23Type", "referenceLocator": "cpe:2.3:a:openssl:openssl:3.0.13:*:*:*:*:*:*:*"}]}
+ ]
+}`
+
+const openVEX = `{
+ "@context": "https://openvex.dev/ns/v0.2.0",
+ "statements": [
+ {"vulnerability": {"name": "CVE-2020-11022"}, "status": "not_affected",
+ "products": [{"@id": "pkg:npm/jquery@1.12.4"}, {"@id": "pkg:npm/jquery@1.12.4"}]}
+ ]
+}`
+
+// csafVEX is a minimal CSAF 2.0 VEX document: one product under
+// vendor/product_name/product_version branches, one full product name.
+const csafVEX = `{
+ "document": {"category": "csaf_vex", "csaf_version": "2.0", "title": "Example VEX"},
+ "product_tree": {
+ "branches": [{"category": "vendor", "name": "Example", "branches": [
+ {"category": "product_name", "name": "nginx", "branches": [
+ {"category": "product_version", "name": "1.25.3",
+ "product": {"product_id": "P1", "name": "Example nginx 1.25.3",
+ "product_identification_helper": {"cpe": "cpe:2.3:a:f5:nginx:1.25.3:*:*:*:*:*:*:*"}}}
+ ]}
+ ]}],
+ "full_product_names": [
+ {"product_id": "P2", "name": "jquery 3.7.1", "product_identification_helper": {"purl": "pkg:npm/jquery@3.7.1"}}
+ ]
+ },
+ "vulnerabilities": [{"cve": "CVE-2023-44487", "product_status": {"known_not_affected": ["P1"]}}]
+}`
+
+func TestParse(t *testing.T) {
+ tests := []struct {
+ name string
+ in string
+ want Document
+ }{
+ {"CycloneDX", cycloneDX, Document{Format: FormatCycloneDX, Components: []Component{
+ {Name: "jquery", Version: "3.7.1", Purl: "pkg:npm/jquery@3.7.1"},
+ {Name: "sizzle", Version: "2.3.10", Purl: "pkg:npm/sizzle@2.3.10"},
+ {Name: "org.apache.logging.log4j/log4j-core", Version: "2.17.1"},
+ }}},
+ {"SPDX", spdx, Document{Format: FormatSPDX, Components: []Component{
+ {Name: "lodash", Version: "4.17.21", Purl: "pkg:npm/lodash@4.17.21"},
+ {Name: "openssl", Version: "3.0.13", CPE: "cpe:2.3:a:openssl:openssl:3.0.13:*:*:*:*:*:*:*"},
+ }}},
+ {"OpenVEX", openVEX, Document{Format: FormatOpenVEX, VEX: true, Components: []Component{
+ {Name: "jquery", Version: "1.12.4", Purl: "pkg:npm/jquery@1.12.4"},
+ }}},
+ {"CSAF VEX", csafVEX, Document{Format: FormatCSAF, VEX: true, Components: []Component{
+ {Name: "nginx", Version: "1.25.3", CPE: "cpe:2.3:a:f5:nginx:1.25.3:*:*:*:*:*:*:*"},
+ {Name: "jquery", Version: "3.7.1", Purl: "pkg:npm/jquery@3.7.1"},
+ }}},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got, err := Parse([]byte(tt.in))
+ if err != nil {
+ t.Fatalf("Parse: %v", err)
+ }
+ if !reflect.DeepEqual(*got, tt.want) {
+ t.Errorf("Parse =\n%+v\nwant\n%+v", *got, tt.want)
+ }
+ })
+ }
+}
+
+func TestParseCSAFAdvisoryIsNotVEX(t *testing.T) {
+ doc, err := ParseCSAF([]byte(`{"document": {"category": "csaf_security_advisory", "csaf_version": "2.0"}}`))
+ if err != nil {
+ t.Fatalf("ParseCSAF: %v", err)
+ }
+ if doc.VEX {
+ t.Error("VEX = true for a security advisory")
+ }
+}
+
+func TestParseRejects(t *testing.T) {
+ for _, in := range []string{"", "not json", "{}", `{"bomFormat": "Other"}`, "", `{"document": {}}`} {
+ if _, err := Parse([]byte(in)); err == nil {
+ t.Errorf("Parse(%q) = nil error, want error", in)
+ }
+ }
+ if _, err := Parse([]byte("")); !errors.Is(err, ErrUnknownFormat) {
+ t.Errorf("Parse(XML): err = %v, want ErrUnknownFormat", err)
+ }
+}
+
+func TestPurlNameVersion(t *testing.T) {
+ tests := []struct{ purl, name, version string }{
+ {"pkg:npm/jquery@1.12.4", "jquery", "1.12.4"},
+ {"pkg:npm/%40angular/core@17.0.0", "core", "17.0.0"},
+ {"pkg:maven/org.apache/log4j-core@2.17.1?type=jar", "log4j-core", "2.17.1"},
+ {"pkg:golang/golang.org/x/net", "net", ""},
+ }
+ for _, tt := range tests {
+ name, version := purlNameVersion(tt.purl)
+ if name != tt.name || version != tt.version {
+ t.Errorf("purlNameVersion(%q) = %q, %q; want %q, %q", tt.purl, name, version, tt.name, tt.version)
+ }
+ }
+}
diff --git a/internal/service/scanner.go b/internal/service/scanner.go
index 06fd461..1eef4a3 100644
--- a/internal/service/scanner.go
+++ b/internal/service/scanner.go
@@ -3,25 +3,31 @@ package service
import (
"context"
"errors"
+ "fmt"
"net/url"
+ "slices"
"strings"
"time"
touchstonev1 "github.com/FootprintAI/touchstone/gen/go/touchstone/v1"
+ "github.com/FootprintAI/touchstone/internal/discover"
"github.com/FootprintAI/touchstone/internal/fetch"
"github.com/FootprintAI/touchstone/internal/fingerprint"
"github.com/FootprintAI/touchstone/internal/pipeline"
+ "github.com/FootprintAI/touchstone/internal/sbom"
"github.com/FootprintAI/touchstone/internal/vuln"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/timestamppb"
)
-// Scanner is the walking-skeleton ScanService (slice S2). It fetches the
-// target page and the scripts it loads through a PassiveFetcher,
-// fingerprints them, looks each component up through vuln.Matcher (OSV by
-// purl, NVD by CPE, enriched with KEV and EPSS), and returns the report.
-// Merging across tiers comes in a later slice.
+// Scanner is the ScanService. It fetches the target page and the scripts
+// it loads through a PassiveFetcher and fingerprints them, discovers
+// vendor-published evidence (security.txt, CSAF VEX, TEA, repo links),
+// reads the reviewer-supplied SBOM/VEX if any, looks each component up
+// through vuln.Matcher (OSV by purl, NVD by CPE, enriched with KEV and
+// EPSS), and returns the report. Components are listed highest tier first
+// and merged by key; conflict recording comes in a later slice.
type Scanner struct {
touchstonev1.UnimplementedScanServiceServer
@@ -48,6 +54,13 @@ func (s *Scanner) Scan(ctx context.Context, req *touchstonev1.ScanRequest) (*tou
}
opts := s.Fetch
opts.Budget = req.GetRequestBudget()
+ if raw := req.GetSbomUrl(); raw != "" {
+ u, err := url.Parse(raw)
+ if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
+ return nil, status.Errorf(codes.InvalidArgument, "sbom_url must be an absolute http(s) URL, got %q", raw)
+ }
+ opts.SuppliedURL = raw
+ }
f, err := fetch.New(target.String(), opts)
if err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error())
@@ -74,13 +87,37 @@ func (s *Scanner) Scan(ctx context.Context, req *touchstonev1.ScanRequest) (*tou
}
rep.ScanStatus = touchstonev1.ScanStatus_SCAN_STATUS_OK
- comps, fpErr := collect(ctx, f, page)
+ fingerprinted, fpErr := collect(ctx, f, page)
rep.Sources = append(rep.Sources, &touchstonev1.SourceStatus{
Source: "fingerprint",
Ok: fpErr == nil,
Error: errText(fpErr),
})
+ var discovered []pipeline.Component
+ found, discErr := discover.Discover(ctx, f, target.String(), page)
+ if found != nil {
+ discovered = found.Components
+ }
+ rep.Sources = append(rep.Sources, &touchstonev1.SourceStatus{
+ Source: "discover",
+ Ok: discErr == nil,
+ Error: errText(discErr),
+ })
+
+ var given []pipeline.Component
+ if req.GetSbomUrl() != "" || len(req.GetSbomDocument()) > 0 {
+ var supErr error
+ given, supErr = supplied(ctx, f, req)
+ rep.Sources = append(rep.Sources, &touchstonev1.SourceStatus{
+ Source: "supplied",
+ Ok: supErr == nil,
+ Error: errText(supErr),
+ })
+ }
+
+ // Highest tier first: merge keeps the first component's confidence.
+ comps := merge(slices.Concat(given, discovered, fingerprinted))
rep.LookupStatus, rep.Components = s.lookup(ctx, rep, comps)
s.finish(rep, f, now)
return rep, nil
@@ -126,6 +163,50 @@ func collect(ctx context.Context, f fetch.Fetcher, page *fetch.Response) ([]pipe
return merge(comps), errors.Join(errs...)
}
+// supplied reads the reviewer's own SBOM/VEX (decision D1): the uploaded
+// document, and the one at sbom_url fetched as SUPPLIED. Its components
+// are High confidence with SBOM_SUPPLIED evidence.
+func supplied(ctx context.Context, f fetch.Fetcher, req *touchstonev1.ScanRequest) ([]pipeline.Component, error) {
+ var comps []pipeline.Component
+ var errs []error
+ read := func(location string, data []byte) {
+ doc, err := sbom.Parse(data)
+ if err != nil {
+ errs = append(errs, fmt.Errorf("%s: %w", location, err))
+ return
+ }
+ for _, c := range doc.Components {
+ comps = append(comps, pipeline.Component{
+ Name: c.Name,
+ Version: c.Version,
+ Purl: c.Purl,
+ CPE: c.CPE,
+ Confidence: "HIGH",
+ Evidence: []pipeline.Evidence{{Kind: "SBOM_SUPPLIED", Location: location, Detail: string(doc.Format)}},
+ })
+ }
+ }
+ if doc := req.GetSbomDocument(); len(doc) > 0 {
+ read(UploadedLocation, doc)
+ }
+ if u := req.GetSbomUrl(); u != "" {
+ resp, err := f.Get(ctx, u, fetch.ReasonSupplied)
+ switch {
+ case err != nil:
+ errs = append(errs, err)
+ case resp.StatusCode < 200 || resp.StatusCode >= 300:
+ errs = append(errs, fmt.Errorf("%s: HTTP %d", u, resp.StatusCode))
+ default:
+ read(u, resp.Body)
+ }
+ }
+ return comps, errors.Join(errs...)
+}
+
+// UploadedLocation is the evidence location of a component read from an
+// uploaded SBOM/VEX document, which has no URL.
+const UploadedLocation = "uploaded SBOM/VEX document"
+
// lookup asks the Matcher about every component (by purl, else CPE) and
// converts the components, with their ranked vulnerabilities, to proto.
// It returns the lookup status, which is COMPLETE only if every lookup
diff --git a/internal/service/scanner_test.go b/internal/service/scanner_test.go
index 7ae63c1..1ebf286 100644
--- a/internal/service/scanner_test.go
+++ b/internal/service/scanner_test.go
@@ -6,6 +6,7 @@ import (
"net/http/httptest"
"os"
"path/filepath"
+ "slices"
"strings"
"testing"
@@ -193,8 +194,8 @@ func TestScannerRanksAndEnriches(t *testing.T) {
}
sources = append(sources, s.GetSource())
}
- if strings.Join(sources, ",") != "fingerprint,OSV,NVD,KEV,EPSS" {
- t.Errorf("sources = %v, want fingerprint,OSV,NVD,KEV,EPSS", sources)
+ if strings.Join(sources, ",") != "fingerprint,discover,OSV,NVD,KEV,EPSS" {
+ t.Errorf("sources = %v, want fingerprint,discover,OSV,NVD,KEV,EPSS", sources)
}
}
@@ -206,17 +207,23 @@ func TestScannerCheckedListMatchesRequests(t *testing.T) {
t.Fatalf("Scan: %v", err)
}
checked := rep.GetChecked()
- if len(checked) != 2 {
- t.Fatalf("checked = %v, want the target and the script", checked)
- }
- want := []struct{ url, reason string }{
- {site.URL + "/", "TARGET"},
- {site.URL + "/js/jquery-1.12.4.min.js", "SUBRESOURCE"},
+ want := []struct {
+ url, reason string
+ result touchstonev1.CheckedLocation_Result
+ }{
+ {site.URL + "/", "TARGET", touchstonev1.CheckedLocation_RESULT_FOUND},
+ {site.URL + "/js/jquery-1.12.4.min.js", "SUBRESOURCE", touchstonev1.CheckedLocation_RESULT_FOUND},
+ {site.URL + "/.well-known/security.txt", "DISCOVERY_PATH", touchstonev1.CheckedLocation_RESULT_NOT_FOUND},
+ {site.URL + "/security.txt", "DISCOVERY_PATH", touchstonev1.CheckedLocation_RESULT_NOT_FOUND},
+ {site.URL + "/.well-known/csaf/provider-metadata.json", "DISCOVERY_PATH", touchstonev1.CheckedLocation_RESULT_NOT_FOUND},
+ {site.URL + "/.well-known/tea", "DISCOVERY_PATH", touchstonev1.CheckedLocation_RESULT_NOT_FOUND},
+ }
+ if len(checked) != len(want) {
+ t.Fatalf("checked = %v, want the target, the script and the four discovery paths", checked)
}
for i, w := range want {
- if checked[i].GetUrl() != w.url || checked[i].GetReason() != w.reason ||
- checked[i].GetResult() != touchstonev1.CheckedLocation_RESULT_FOUND {
- t.Errorf("checked[%d] = %v, want %s %s FOUND", i, checked[i], w.reason, w.url)
+ if checked[i].GetUrl() != w.url || checked[i].GetReason() != w.reason || checked[i].GetResult() != w.result {
+ t.Errorf("checked[%d] = %v, want %s %s %v", i, checked[i], w.reason, w.url, w.result)
}
}
if rep.GetRequestsUsed() != uint32(len(checked)) {
@@ -235,8 +242,13 @@ func TestScannerRecordsScriptRefusedByBudget(t *testing.T) {
t.Fatalf("Scan: %v", err)
}
checked := rep.GetChecked()
- if len(checked) != 2 || checked[1].GetResult() != touchstonev1.CheckedLocation_RESULT_REFUSED {
- t.Fatalf("checked = %v, want the script refused by the budget", checked)
+ if len(checked) != 6 {
+ t.Fatalf("checked = %v, want the target, the script and the four discovery paths", checked)
+ }
+ for _, c := range checked[1:] {
+ if c.GetResult() != touchstonev1.CheckedLocation_RESULT_REFUSED {
+ t.Errorf("checked %v, want it refused by the budget", c)
+ }
}
if rep.GetRequestsUsed() != 1 {
t.Errorf("requests_used = %d, want 1", rep.GetRequestsUsed())
@@ -297,6 +309,180 @@ func TestScannerOSVDownIsPartialLookup(t *testing.T) {
}
}
+// csafSite is vendorSite plus a security.txt whose CSAF field names
+// provider metadata with one ROLIE feed listing one CSAF VEX document. The
+// VEX document names the jQuery the page loads.
+func csafSite(t *testing.T) *httptest.Server {
+ t.Helper()
+ var base string
+ docs := map[string]string{}
+ docs["/.well-known/security.txt"] = "Contact: mailto:psirt@vendor.example\nCSAF: {base}/csaf/provider-metadata.json\n"
+ docs["/csaf/provider-metadata.json"] = `{"canonical_url": "{base}/csaf/provider-metadata.json", "metadata_version": "2.0",
+ "distributions": [{"rolie": {"feeds": [{"tlp_label": "WHITE", "url": "{base}/csaf/feed.json"}]}}]}`
+ docs["/csaf/feed.json"] = `{"feed": {"entry": [{"updated": "2026-10-01T00:00:00Z", "content": {"src": "{base}/csaf/vex-1.json"}}]}}`
+ docs["/csaf/vex-1.json"] = `{"document": {"category": "csaf_vex", "csaf_version": "2.0"},
+ "product_tree": {"full_product_names": [{"product_id": "P1", "name": "jQuery 1.12.4",
+ "product_identification_helper": {"purl": "pkg:npm/jquery@1.12.4"}}]}}`
+ mux := http.NewServeMux()
+ mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
+ if body, ok := docs[r.URL.Path]; ok {
+ _, _ = w.Write([]byte(strings.ReplaceAll(body, "{base}", base)))
+ return
+ }
+ if r.URL.Path != "/" {
+ http.NotFound(w, r)
+ return
+ }
+ w.Header().Set("Content-Type", "text/html")
+ _, _ = w.Write([]byte(fixturePage))
+ })
+ mux.HandleFunc("/js/jquery-1.12.4.min.js", func(w http.ResponseWriter, r *http.Request) {
+ _, _ = w.Write([]byte("/*! jQuery v1.12.4 */"))
+ })
+ srv := httptest.NewServer(mux)
+ base = srv.URL
+ t.Cleanup(srv.Close)
+ return srv
+}
+
+func TestScannerDiscoversCSAFVEX(t *testing.T) {
+ site := csafSite(t)
+ rep, err := newTestScanner(t, recordedOSVSite(t).URL).Scan(context.Background(),
+ &touchstonev1.ScanRequest{Url: site.URL + "/"})
+ if err != nil {
+ t.Fatalf("Scan: %v", err)
+ }
+
+ want := []struct {
+ url, reason string
+ result touchstonev1.CheckedLocation_Result
+ }{
+ {site.URL + "/", "TARGET", touchstonev1.CheckedLocation_RESULT_FOUND},
+ {site.URL + "/js/jquery-1.12.4.min.js", "SUBRESOURCE", touchstonev1.CheckedLocation_RESULT_FOUND},
+ {site.URL + "/.well-known/security.txt", "DISCOVERY_PATH", touchstonev1.CheckedLocation_RESULT_FOUND},
+ {site.URL + "/.well-known/csaf/provider-metadata.json", "DISCOVERY_PATH", touchstonev1.CheckedLocation_RESULT_NOT_FOUND},
+ {site.URL + "/.well-known/tea", "DISCOVERY_PATH", touchstonev1.CheckedLocation_RESULT_NOT_FOUND},
+ {site.URL + "/csaf/provider-metadata.json", "DECLARED", touchstonev1.CheckedLocation_RESULT_FOUND},
+ {site.URL + "/csaf/feed.json", "DECLARED", touchstonev1.CheckedLocation_RESULT_FOUND},
+ {site.URL + "/csaf/vex-1.json", "DECLARED", touchstonev1.CheckedLocation_RESULT_FOUND},
+ }
+ checked := rep.GetChecked()
+ if len(checked) != len(want) {
+ t.Fatalf("checked = %v, want %d locations", checked, len(want))
+ }
+ for i, w := range want {
+ if checked[i].GetUrl() != w.url || checked[i].GetReason() != w.reason || checked[i].GetResult() != w.result {
+ t.Errorf("checked[%d] = %v, want %s %s %v", i, checked[i], w.reason, w.url, w.result)
+ }
+ }
+
+ var jq *touchstonev1.Component
+ for _, c := range rep.GetComponents() {
+ if c.GetPurl() == "pkg:npm/jquery@1.12.4" {
+ jq = c
+ }
+ }
+ if jq == nil {
+ t.Fatalf("no jquery component in %v", rep.GetComponents())
+ }
+ if jq.GetConfidence() != touchstonev1.Confidence_CONFIDENCE_HIGH {
+ t.Errorf("confidence = %v, want HIGH from the CSAF VEX document", jq.GetConfidence())
+ }
+ var kinds []touchstonev1.EvidenceKind
+ for _, e := range jq.GetEvidence() {
+ kinds = append(kinds, e.GetKind())
+ }
+ wantKinds := []touchstonev1.EvidenceKind{
+ touchstonev1.EvidenceKind_EVIDENCE_KIND_VEX, touchstonev1.EvidenceKind_EVIDENCE_KIND_FINGERPRINT_ASSET,
+ }
+ if !slices.Equal(kinds, wantKinds) {
+ t.Errorf("evidence kinds = %v, want %v (both tiers kept)", kinds, wantKinds)
+ }
+ for _, s := range rep.GetSources() {
+ if s.GetSource() == "discover" && !s.GetOk() {
+ t.Errorf("discover source failed: %s", s.GetError())
+ }
+ }
+}
+
+const suppliedCycloneDX = `{"bomFormat": "CycloneDX", "specVersion": "1.6",
+ "components": [{"name": "jquery", "version": "1.12.4", "purl": "pkg:npm/jquery@1.12.4"}]}`
+
+func TestScannerReadsUploadedSBOM(t *testing.T) {
+ site := vendorSite(t)
+ rep, err := newTestScanner(t, recordedOSVSite(t).URL).Scan(context.Background(),
+ &touchstonev1.ScanRequest{Url: site.URL + "/", SbomDocument: []byte(suppliedCycloneDX)})
+ if err != nil {
+ t.Fatalf("Scan: %v", err)
+ }
+ jq := rep.GetComponents()[0]
+ if jq.GetPurl() != "pkg:npm/jquery@1.12.4" || jq.GetConfidence() != touchstonev1.Confidence_CONFIDENCE_HIGH {
+ t.Fatalf("first component = %v, want jquery at HIGH confidence", jq)
+ }
+ first := jq.GetEvidence()[0]
+ if first.GetKind() != touchstonev1.EvidenceKind_EVIDENCE_KIND_SBOM_SUPPLIED || first.GetLocation() != UploadedLocation ||
+ first.GetDetail() != "CycloneDX" {
+ t.Errorf("evidence = %v, want SBOM_SUPPLIED from the upload", first)
+ }
+ var supplied *touchstonev1.SourceStatus
+ for _, s := range rep.GetSources() {
+ if s.GetSource() == "supplied" {
+ supplied = s
+ }
+ }
+ if supplied == nil || !supplied.GetOk() {
+ t.Errorf("supplied source status = %v, want ok", supplied)
+ }
+}
+
+func TestScannerFetchesSuppliedSBOMURL(t *testing.T) {
+ site := vendorSite(t)
+ sbomSite := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ _, _ = w.Write([]byte(suppliedCycloneDX))
+ }))
+ t.Cleanup(sbomSite.Close)
+ sbomURL := sbomSite.URL + "/vendor-sbom.json"
+
+ rep, err := newTestScanner(t, recordedOSVSite(t).URL).Scan(context.Background(),
+ &touchstonev1.ScanRequest{Url: site.URL + "/", SbomUrl: sbomURL})
+ if err != nil {
+ t.Fatalf("Scan: %v", err)
+ }
+ checked := rep.GetChecked()
+ last := checked[len(checked)-1]
+ if last.GetUrl() != sbomURL || last.GetReason() != "SUPPLIED" || last.GetResult() != touchstonev1.CheckedLocation_RESULT_FOUND {
+ t.Errorf("last checked = %v, want the supplied SBOM URL, SUPPLIED, FOUND", last)
+ }
+ jq := rep.GetComponents()[0]
+ if jq.GetConfidence() != touchstonev1.Confidence_CONFIDENCE_HIGH ||
+ jq.GetEvidence()[0].GetKind() != touchstonev1.EvidenceKind_EVIDENCE_KIND_SBOM_SUPPLIED ||
+ jq.GetEvidence()[0].GetLocation() != sbomURL {
+ t.Errorf("first component = %v, want jquery at HIGH with SBOM_SUPPLIED evidence from %s", jq, sbomURL)
+ }
+}
+
+func TestScannerReportsUnreadableSupplied(t *testing.T) {
+ site := vendorSite(t)
+ rep, err := newTestScanner(t, recordedOSVSite(t).URL).Scan(context.Background(),
+ &touchstonev1.ScanRequest{Url: site.URL + "/", SbomDocument: []byte("")})
+ if err != nil {
+ t.Fatalf("Scan: an unreadable SBOM is a source failure, not an RPC error: %v", err)
+ }
+ for _, s := range rep.GetSources() {
+ if s.GetSource() == "supplied" && (s.GetOk() || s.GetError() == "") {
+ t.Errorf("supplied source status = %v, want ok=false with an error", s)
+ }
+ }
+}
+
+func TestScannerRejectsBadSBOMURL(t *testing.T) {
+ _, err := newTestScanner(t, "http://unused").Scan(context.Background(),
+ &touchstonev1.ScanRequest{Url: "https://vendor.example/", SbomUrl: "file:///etc/passwd"})
+ if err == nil {
+ t.Fatal("Scan: want an InvalidArgument error for a file: sbom_url")
+ }
+}
+
func TestScannerRejectsNonHTTPTarget(t *testing.T) {
_, err := newTestScanner(t, "http://unused").Scan(context.Background(),
&touchstonev1.ScanRequest{Url: "ftp://vendor.example/"})
diff --git a/web/src/components/scan-form.tsx b/web/src/components/scan-form.tsx
index d86e4ac..e8cc585 100644
--- a/web/src/components/scan-form.tsx
+++ b/web/src/components/scan-form.tsx
@@ -1,21 +1,47 @@
"use client";
import { useState, type FormEvent } from "react";
+import type { ScanInput } from "../lib/api";
import { isScannableUrl } from "../lib/url";
-/** One URL input. A value that is not an absolute http(s) URL is refused here, before any request. */
-export function ScanForm({ onScan, busy }: { onScan: (url: string) => void; busy: boolean }) {
+/**
+ * One URL input, plus an optional SBOM/VEX the reviewer already has, by URL or
+ * upload. A value that is not an absolute http(s) URL is refused here, before
+ * any request.
+ */
+export function ScanForm({ onScan, busy }: { onScan: (input: ScanInput) => void; busy: boolean }) {
const [value, setValue] = useState("");
+ const [sbomUrl, setSbomUrl] = useState("");
+ const [sbomFile, setSbomFile] = useState(undefined);
const [invalid, setInvalid] = useState(false);
+ const [sbomUrlInvalid, setSbomUrlInvalid] = useState(false);
+ const [fileError, setFileError] = useState(false);
- function submit(event: FormEvent) {
+ async function submit(event: FormEvent) {
event.preventDefault();
const url = value.trim();
+ const supplied = sbomUrl.trim();
const ok = isScannableUrl(url);
+ const suppliedOk = supplied === "" || isScannableUrl(supplied);
setInvalid(!ok);
- if (ok) {
- onScan(url);
+ setSbomUrlInvalid(!suppliedOk);
+ setFileError(false);
+ if (!ok || !suppliedOk) {
+ return;
}
+ const input: ScanInput = { url };
+ if (supplied !== "") {
+ input.sbomUrl = supplied;
+ }
+ if (sbomFile) {
+ try {
+ input.sbomDocument = await readFile(sbomFile);
+ } catch {
+ setFileError(true);
+ return;
+ }
+ }
+ onScan(input);
}
return (
@@ -48,6 +74,60 @@ export function ScanForm({ onScan, busy }: { onScan: (url: string) => void; busy
Enter an absolute http:// or https:// URL.
)}
+
);
}
+
+/** The file's bytes. FileReader works in every browser and in jsdom. */
+function readFile(file: File): Promise {
+ return new Promise((resolve, reject) => {
+ const reader = new FileReader();
+ reader.onload = () => {
+ const result = reader.result;
+ if (result === null || typeof result === "string") {
+ reject(new Error("could not read the SBOM/VEX file"));
+ } else {
+ resolve(new Uint8Array(result));
+ }
+ };
+ reader.onerror = () => reject(reader.error ?? new Error("could not read the SBOM/VEX file"));
+ reader.readAsArrayBuffer(file);
+ });
+}
diff --git a/web/src/components/scan-page.test.tsx b/web/src/components/scan-page.test.tsx
index 1f7ba89..899a2ed 100644
--- a/web/src/components/scan-page.test.tsx
+++ b/web/src/components/scan-page.test.tsx
@@ -42,6 +42,42 @@ describe("ScanPage", () => {
expect(fetchMock.mock.calls[0]?.[1]?.body).toBe(JSON.stringify({ url: "https://example.com" }));
});
+ it("sends a supplied SBOM/VEX URL with the scan", async () => {
+ const fetchMock = stubFetch(async () => new Response(goldenText, { status: 200 }));
+ render();
+
+ fireEvent.change(screen.getByLabelText("SBOM/VEX URL"), { target: { value: " https://example.com/sbom.json " } });
+ scanFor("https://example.com");
+
+ await screen.findByRole("region", { name: "Low confidence" });
+ expect(fetchMock.mock.calls[0]?.[1]?.body).toBe(
+ JSON.stringify({ url: "https://example.com", sbomUrl: "https://example.com/sbom.json" }),
+ );
+ });
+
+ it("refuses an SBOM/VEX URL that is not http(s) without sending a request", () => {
+ const fetchMock = stubFetch(async () => new Response(goldenText));
+ render();
+
+ fireEvent.change(screen.getByLabelText("SBOM/VEX URL"), { target: { value: "file:///sbom.json" } });
+ scanFor("https://example.com");
+
+ expect(screen.getByText(/URL for the SBOM\/VEX/)).toBeTruthy();
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it("uploads a chosen SBOM/VEX file as sbomDocument", async () => {
+ const fetchMock = stubFetch(async () => new Response(goldenText, { status: 200 }));
+ render();
+
+ const file = new File(["{}"], "sbom.json", { type: "application/json" });
+ fireEvent.change(screen.getByLabelText("SBOM/VEX file"), { target: { files: [file] } });
+ scanFor("https://example.com");
+
+ await screen.findByRole("region", { name: "Low confidence" });
+ expect(fetchMock.mock.calls[0]?.[1]?.body).toBe(JSON.stringify({ url: "https://example.com", sbomDocument: "e30=" }));
+ });
+
it("shows the gateway's message as an error, not an empty report", async () => {
stubFetch(
async () => new Response('{"code":13,"message":"internal error","details":[]}', { status: 500 }),
diff --git a/web/src/components/scan-page.tsx b/web/src/components/scan-page.tsx
index c4234a1..98cf8d9 100644
--- a/web/src/components/scan-page.tsx
+++ b/web/src/components/scan-page.tsx
@@ -2,7 +2,7 @@
import { useState } from "react";
import { ScanStatus, type ScanReport } from "../gen/touchstone/v1/scan_pb";
-import { requestScan, ScanError } from "../lib/api";
+import { requestScan, ScanError, type ScanInput } from "../lib/api";
import { ReportView } from "./report-view";
import { ScanForm } from "./scan-form";
@@ -16,10 +16,10 @@ type View =
export function ScanPage() {
const [view, setView] = useState({ kind: "idle" });
- async function scan(url: string) {
+ async function scan(input: ScanInput) {
setView({ kind: "scanning" });
try {
- const report = await requestScan(url);
+ const report = await requestScan(input);
// An unreachable target returns a report with no components, which
// would look like a clean result. Show it as an error instead.
if (report.scanStatus !== ScanStatus.OK) {
diff --git a/web/src/lib/api.test.ts b/web/src/lib/api.test.ts
index 5150271..2463c55 100644
--- a/web/src/lib/api.test.ts
+++ b/web/src/lib/api.test.ts
@@ -11,7 +11,7 @@ describe("requestScan", () => {
it("POSTs the URL to /v1/scans and decodes the reply with the generated parser", async () => {
const fetchFn = vi.fn(async () => jsonResponse(goldenText));
- const report = await requestScan("https://example.com", fetchFn);
+ const report = await requestScan({ url: "https://example.com" }, fetchFn);
expect(fetchFn).toHaveBeenCalledWith("/v1/scans", {
method: "POST",
@@ -23,24 +23,44 @@ describe("requestScan", () => {
expect(report.components[0]?.name).toBe("jquery");
});
+ it("sends a supplied SBOM URL and the uploaded document as base64", async () => {
+ const fetchFn = vi.fn(async () => jsonResponse(goldenText));
+
+ await requestScan(
+ {
+ url: "https://example.com",
+ sbomUrl: "https://example.com/sbom.json",
+ // "{}" as bytes. Not TextEncoder: under jsdom it returns a Uint8Array from
+ // another realm, which protobuf's instanceof check rejects. The page wraps
+ // the FileReader result in this realm's Uint8Array, as here.
+ sbomDocument: Uint8Array.from([0x7b, 0x7d]),
+ },
+ fetchFn,
+ );
+
+ expect(fetchFn.mock.calls[0]?.[1]?.body).toBe(
+ JSON.stringify({ url: "https://example.com", sbomUrl: "https://example.com/sbom.json", sbomDocument: "e30=" }),
+ );
+ });
+
it("uses the gateway's message for an error reply", async () => {
const fetchFn = vi.fn(async () =>
jsonResponse('{"code":3,"message":"url must be an absolute http(s) URL","details":[]}', 400),
);
- await expect(requestScan("ftp://x", fetchFn)).rejects.toThrow("url must be an absolute http(s) URL");
+ await expect(requestScan({ url: "ftp://x" }, fetchFn)).rejects.toThrow("url must be an absolute http(s) URL");
});
it("reports the HTTP status when an error reply has no JSON message", async () => {
const fetchFn = vi.fn(async () => new Response("bad gateway", { status: 502 }));
- await expect(requestScan("https://example.com", fetchFn)).rejects.toThrow("HTTP 502");
+ await expect(requestScan({ url: "https://example.com" }, fetchFn)).rejects.toThrow("HTTP 502");
});
it("rejects a reply with a field the contract does not define", async () => {
const fetchFn = vi.fn(async () => jsonResponse('{"schemaVersion":"1","bogusField":true}'));
- await expect(requestScan("https://example.com", fetchFn)).rejects.toBeInstanceOf(ScanError);
+ await expect(requestScan({ url: "https://example.com" }, fetchFn)).rejects.toBeInstanceOf(ScanError);
});
it("turns a network failure into a ScanError, not a raw TypeError", async () => {
@@ -48,7 +68,7 @@ describe("requestScan", () => {
throw new TypeError("Failed to fetch");
});
- await expect(requestScan("https://example.com", fetchFn)).rejects.toThrow("could not be reached");
+ await expect(requestScan({ url: "https://example.com" }, fetchFn)).rejects.toThrow("could not be reached");
});
});
diff --git a/web/src/lib/api.ts b/web/src/lib/api.ts
index b661938..e9a8e33 100644
--- a/web/src/lib/api.ts
+++ b/web/src/lib/api.ts
@@ -1,5 +1,5 @@
-import { fromJson, type JsonValue } from "@bufbuild/protobuf";
-import { ScanReportSchema, type ScanReport } from "../gen/touchstone/v1/scan_pb";
+import { create, fromJson, toJson, type JsonValue } from "@bufbuild/protobuf";
+import { ScanReportSchema, ScanRequestSchema, type ScanReport } from "../gen/touchstone/v1/scan_pb";
/** The ScanService route, served by `touchstone serve` through grpc-gateway. */
export const SCAN_PATH = "/v1/scans";
@@ -7,18 +7,27 @@ export const SCAN_PATH = "/v1/scans";
/** A scan that produced no report. The message is shown to the reviewer. */
export class ScanError extends Error {}
+/** What the reviewer asks for: the vendor URL, plus an SBOM/VEX they already have, by URL or upload. */
+export type ScanInput = {
+ url: string;
+ sbomUrl?: string;
+ sbomDocument?: Uint8Array;
+};
+
/**
- * POSTs the URL and decodes the reply with the generated parser. Any failure,
- * including a body that is not a ScanReport, becomes a ScanError, so the page
- * never shows a partial or empty report.
+ * POSTs the scan request and decodes the reply with the generated parser. Any
+ * failure, including a body that is not a ScanReport, becomes a ScanError, so
+ * the page never shows a partial or empty report.
*/
-export async function requestScan(url: string, fetchFn: typeof fetch = fetch): Promise {
+export async function requestScan(input: ScanInput, fetchFn: typeof fetch = fetch): Promise {
+ // The generated serializer leaves out empty fields and base64-encodes the upload.
+ const request = toJson(ScanRequestSchema, create(ScanRequestSchema, input));
let res: Response;
try {
res = await fetchFn(SCAN_PATH, {
method: "POST",
headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ url }),
+ body: JSON.stringify(request),
});
} catch {
throw new ScanError("The scan service could not be reached. Is `touchstone serve` running?");