From 417212e0930aa52a27ebdc1b9370d2943ce0f8fa Mon Sep 17 00:00:00 2001 From: DmitriyLewen <91113035+DmitriyLewen@users.noreply.github.com> Date: Wed, 19 Jun 2024 12:55:21 +0600 Subject: [PATCH] fix(cyclonedx): trim non-URL info for `advisory.url` (#6952) --- pkg/sbom/cyclonedx/marshal.go | 16 ++++++++++++++++ pkg/sbom/cyclonedx/marshal_test.go | 4 ++-- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/pkg/sbom/cyclonedx/marshal.go b/pkg/sbom/cyclonedx/marshal.go index 7f4bb0c3b397..9f5437f2d292 100644 --- a/pkg/sbom/cyclonedx/marshal.go +++ b/pkg/sbom/cyclonedx/marshal.go @@ -3,6 +3,7 @@ package cyclonedx import ( "context" "fmt" + "net/url" "slices" "sort" "strconv" @@ -332,6 +333,10 @@ func (*Marshaler) affects(ref, version string) cdx.Affects { func (*Marshaler) advisories(refs []string) *[]cdx.Advisory { refs = lo.Uniq(refs) advs := lo.FilterMap(refs, func(ref string, _ int) (cdx.Advisory, bool) { + // There are cases when `ref` contains extra info + // But we need to use only URL. + // cf. https://github.com/aquasecurity/trivy/issues/6801 + ref = trimNonUrlInfo(ref) return cdx.Advisory{URL: ref}, ref != "" }) @@ -345,6 +350,17 @@ func (*Marshaler) advisories(refs []string) *[]cdx.Advisory { return &advs } +// trimNonUrlInfo returns first valid URL. +func trimNonUrlInfo(ref string) string { + ss := strings.Split(ref, " ") + for _, s := range ss { + if u, err := url.Parse(s); err == nil && u.Scheme != "" && u.Host != "" { + return s + } + } + return "" +} + func (m *Marshaler) marshalVulnerability(bomRef string, vuln core.Vulnerability) *cdx.Vulnerability { v := &cdx.Vulnerability{ ID: vuln.ID, diff --git a/pkg/sbom/cyclonedx/marshal_test.go b/pkg/sbom/cyclonedx/marshal_test.go index d1fc8a455a2a..9209c0c0100c 100644 --- a/pkg/sbom/cyclonedx/marshal_test.go +++ b/pkg/sbom/cyclonedx/marshal_test.go @@ -847,8 +847,8 @@ func TestMarshaler_MarshalReport(t *testing.T) { }, }, References: []string{ - "http://www.openwall.com/lists/oss-security/2022/02/11/5", - "https://access.redhat.com/security/cve/CVE-2022-23633", + " extraPrefix http://www.openwall.com/lists/oss-security/2022/02/11/5", + "https://access.redhat.com/security/cve/CVE-2022-23633 (extra suffix)", }, PublishedDate: lo.ToPtr(time.Date(2022, 2, 11, 21, 15, 0, 0, time.UTC)), LastModifiedDate: lo.ToPtr(time.Date(2022, 2, 22, 21, 47, 0, 0, time.UTC)),