Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support top-level SPDX package and graph #1934

Merged
merged 14 commits into from
Jul 26, 2023
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ VERSION
*.hpi
*.zip
.idea/
*.iml
*.log
.images
.tmp/
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ require (
github.com/charmbracelet/lipgloss v0.7.1
github.com/dave/jennifer v1.6.1
github.com/deitch/magic v0.0.0-20230404182410-1ff89d7342da
github.com/docker/distribution v2.8.2+incompatible
github.com/docker/docker v24.0.2+incompatible
github.com/github/go-spdx/v2 v2.1.2
github.com/gkampitakis/go-snaps v0.4.7
Expand Down Expand Up @@ -98,7 +99,6 @@ require (
github.com/containerd/stargz-snapshotter/estargz v0.14.3 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/docker/cli v23.0.5+incompatible // indirect
github.com/docker/distribution v2.8.2+incompatible // indirect
github.com/docker/docker-credential-helpers v0.7.0 // indirect
github.com/docker/go-connections v0.4.0 // indirect
github.com/docker/go-units v0.5.0 // indirect
Expand Down
149 changes: 143 additions & 6 deletions syft/formats/common/spdxhelpers/to_format_model.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"strings"
"time"

"github.com/docker/distribution/reference"
"github.com/spdx/tools-golang/spdx"
"golang.org/x/exp/maps"
"golang.org/x/exp/slices"
Expand All @@ -21,10 +22,20 @@ import (
"github.com/anchore/syft/syft/formats/common/util"
"github.com/anchore/syft/syft/pkg"
"github.com/anchore/syft/syft/sbom"
"github.com/anchore/syft/syft/source"
)

const (
noAssertion = "NOASSERTION"

spdxPrimaryPurposeContainer = "CONTAINER"
spdxPrimaryPurposeFile = "FILE"
spdxPrimaryPurposeOther = "OTHER"

prefixImage = "Image"
prefixDirectory = "Directory"
prefixFile = "File"
prefixUnknown = "Unknown"
)

// ToFormatModel creates and populates a new SPDX document struct that follows the SPDX 2.3
Expand All @@ -33,23 +44,37 @@ const (
//nolint:funlen
func ToFormatModel(s sbom.SBOM) *spdx.Document {
name, namespace := DocumentNameAndNamespace(s.Source)

packages := toPackages(s.Artifacts.Packages, s)

relationships := toRelationships(s.RelationshipsSorted())

// for valid SPDX we need a document describes relationship
// TODO: remove this placeholder after deciding on correct behavior
// for the primary package purpose field:
// https://spdx.github.io/spdx-spec/v2.3/package-information/#724-primary-package-purpose-field
describesID := spdx.ElementID("DOCUMENT")

rootPackage := toRootPackage(s)
if rootPackage != nil {
describesID = rootPackage.PackageSPDXIdentifier

// add all relationships from the document root to all other packages
relationships = append(relationships, toRootRelationships(rootPackage, packages)...)

// append the root package
packages = append(packages, rootPackage)
}

// add a relationship for the package the document describes
documentDescribesRelationship := &spdx.Relationship{
RefA: spdx.DocElementID{
ElementRefID: "DOCUMENT",
},
Relationship: string(DescribesRelationship),
RefB: spdx.DocElementID{
ElementRefID: "DOCUMENT",
ElementRefID: describesID,
},
RelationshipComment: "",
}

// add the root document relationship
relationships = append(relationships, documentDescribesRelationship)

return &spdx.Document{
Expand Down Expand Up @@ -123,13 +148,113 @@ func ToFormatModel(s sbom.SBOM) *spdx.Document {
// Cardinality: optional, one
CreatorComment: "",
},
Packages: toPackages(s.Artifacts.Packages, s),
Packages: packages,
Files: toFiles(s),
Relationships: relationships,
OtherLicenses: toOtherLicenses(s.Artifacts.Packages),
}
}

func toRootRelationships(rootPackage *spdx.Package, packages []*spdx.Package) (out []*spdx.Relationship) {
for _, p := range packages {
out = append(out, &spdx.Relationship{
RefA: spdx.DocElementID{
ElementRefID: rootPackage.PackageSPDXIdentifier,
},
Relationship: string(ContainsRelationship),
RefB: spdx.DocElementID{
ElementRefID: p.PackageSPDXIdentifier,
},
})
}
return
}

//nolint:funlen
func toRootPackage(s sbom.SBOM) *spdx.Package {
kzantow marked this conversation as resolved.
Show resolved Hide resolved
var prefix string

name := s.Source.Name
nameIfUnset := func(n string) {
if name != "" {
return
}
name = n
}

version := s.Source.Version
versionIfUnset := func(v string) {
if version != "" && version != "latest" {
return
}
version = v
}

purpose := ""
var checksums []spdx.Checksum
switch m := s.Source.Metadata.(type) {
case source.StereoscopeImageSourceMetadata:
prefix = prefixImage
ref, err := reference.Parse(m.UserInput)
if err != nil {
log.Debugf("unable to parse image ref: %s", m.UserInput)
break
}
if ref, ok := ref.(reference.Named); ok {
nameIfUnset(ref.Name())
} else {
nameIfUnset(m.UserInput)
}
if ref, ok := ref.(reference.NamedTagged); ok {
versionIfUnset(ref.Tag())
}
if ref, ok := ref.(reference.Digested); ok {
versionIfUnset(ref.Digest().String())
}
versionIfUnset(m.ID)
purpose = spdxPrimaryPurposeContainer

c := toChecksum(m.ID)
kzantow marked this conversation as resolved.
Show resolved Hide resolved
if c != nil {
checksums = append(checksums, *c)
}
case source.DirectorySourceMetadata:
prefix = prefixDirectory
nameIfUnset(m.Path)
purpose = spdxPrimaryPurposeFile
case source.FileSourceMetadata:
prefix = prefixFile
nameIfUnset(m.Path)
if len(m.Digests) > 0 {
d := m.Digests[0]
versionIfUnset(fmt.Sprintf("%s:%s", toChecksumAlgorithm(d.Algorithm), d.Value))
}
for _, d := range m.Digests {
checksums = append(checksums, spdx.Checksum{
Algorithm: toChecksumAlgorithm(d.Algorithm),
Value: d.Value,
})
}
purpose = spdxPrimaryPurposeFile
default:
prefix = prefixUnknown
name = s.Source.ID
purpose = spdxPrimaryPurposeOther
}

p := &spdx.Package{
PackageName: name,
PackageSPDXIdentifier: spdx.ElementID(SanitizeElementID(fmt.Sprintf("DocumentRoot-%s-%s", prefix, name))),
PackageVersion: version,
PackageChecksums: checksums,
PackageSupplier: nil,
PackageExternalReferences: nil,
PrimaryPackagePurpose: purpose,
}

return p
}

func toSPDXID(identifiable artifact.Identifiable) spdx.ElementID {
maxLen := 40
id := ""
Expand Down Expand Up @@ -494,6 +619,18 @@ func toFileChecksums(digests []file.Digest) (checksums []spdx.Checksum) {
return checksums
}

// toChecksum takes a checksum in the format <algorithm>:<hash> and returns an spdx.Checksum or nil if the string is invalid
func toChecksum(algorithmHash string) *spdx.Checksum {
parts := strings.Split(algorithmHash, ":")
if len(parts) < 2 {
return nil
}
return &spdx.Checksum{
Algorithm: toChecksumAlgorithm(parts[0]),
Value: parts[1],
}
}

func toChecksumAlgorithm(algorithm string) spdx.ChecksumAlgorithm {
// this needs to be an uppercase version of our algorithm
return spdx.ChecksumAlgorithm(strings.ToUpper(algorithm))
Expand Down
95 changes: 94 additions & 1 deletion syft/formats/common/spdxhelpers/to_format_model_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import (
"regexp"
"testing"

"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"github.com/spdx/tools-golang/spdx"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
Expand All @@ -13,9 +15,100 @@ import (
"github.com/anchore/syft/syft/file"
"github.com/anchore/syft/syft/pkg"
"github.com/anchore/syft/syft/sbom"
"github.com/anchore/syft/syft/source"
)

// TODO: Add ToFormatModel tests
func Test_toFormatModel(t *testing.T) {
kzantow marked this conversation as resolved.
Show resolved Hide resolved
tests := []struct {
name string
in sbom.SBOM
expected *spdx.Document
}{
{
name: "includes root element",
in: sbom.SBOM{
Source: source.Description{
Metadata: source.StereoscopeImageSourceMetadata{
UserInput: "alpine:latest",
ID: "sha256:d34db33f",
},
},
Artifacts: sbom.Artifacts{
Packages: pkg.NewCollection(pkg.Package{
Name: "pkg-1",
Version: "version-1",
}),
},
},
expected: &spdx.Document{
SPDXIdentifier: "DOCUMENT",
SPDXVersion: spdx.Version,
DataLicense: spdx.DataLicense,
DocumentName: "alpine:latest",

Packages: []*spdx.Package{
{
PackageSPDXIdentifier: "Package--pkg-1-pkg-1",
kzantow marked this conversation as resolved.
Show resolved Hide resolved
PackageName: "pkg-1",
PackageVersion: "version-1",
},
{
PackageSPDXIdentifier: "DocumentRoot-Image-alpine",
PackageName: "alpine",
PackageVersion: "sha256:d34db33f",
PrimaryPackagePurpose: "CONTAINER",
PackageChecksums: []spdx.Checksum{{Algorithm: "SHA256", Value: "d34db33f"}},
},
},
Relationships: []*spdx.Relationship{
{
RefA: spdx.DocElementID{
ElementRefID: "DocumentRoot-Image-alpine",
},
RefB: spdx.DocElementID{
ElementRefID: "Package--pkg-1-pkg-1",
},
Relationship: spdx.RelationshipContains,
},
{
RefA: spdx.DocElementID{
ElementRefID: "DOCUMENT",
},
RefB: spdx.DocElementID{
ElementRefID: "DocumentRoot-Image-alpine",
},
Relationship: spdx.RelationshipDescribes,
},
},
},
},
}

for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
// replace IDs with package names
var pkgs []pkg.Package
for p := range test.in.Artifacts.Packages.Enumerate() {
p.OverrideID(artifact.ID(p.Name))
pkgs = append(pkgs, p)
}
test.in.Artifacts.Packages = pkg.NewCollection(pkgs...)

// convert
got := ToFormatModel(test.in)

// check differences
if diff := cmp.Diff(test.expected, got,
cmpopts.IgnoreUnexported(spdx.Document{}, spdx.Package{}),
cmpopts.IgnoreFields(spdx.Document{}, "CreationInfo", "DocumentNamespace"),
cmpopts.IgnoreFields(spdx.Package{}, "PackageDownloadLocation", "IsFilesAnalyzedTagPresent", "PackageSourceInfo", "PackageLicenseConcluded", "PackageLicenseDeclared", "PackageCopyrightText"),
); diff != "" {
t.Error(diff)
}
})
}
}

func Test_toPackageChecksums(t *testing.T) {
tests := []struct {
name string
Expand Down
Loading
Loading