-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
Copy pathunmarshal.go
292 lines (250 loc) · 7.92 KB
/
unmarshal.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
package spdx
import (
"bytes"
"fmt"
"io"
"strings"
"github.com/package-url/packageurl-go"
"github.com/samber/lo"
"github.com/spdx/tools-golang/json"
"github.com/spdx/tools-golang/spdx"
"github.com/spdx/tools-golang/spdx/v2/common"
"github.com/spdx/tools-golang/tagvalue"
"golang.org/x/xerrors"
"github.com/aquasecurity/trivy/pkg/sbom/core"
)
type SPDX struct {
*core.BOM
trivySBOM bool
pkgFilePaths map[common.ElementID]string
}
func NewTVDecoder(r io.Reader) *TVDecoder {
return &TVDecoder{r: r}
}
type TVDecoder struct {
r io.Reader
}
func (tv *TVDecoder) Decode(v any) error {
spdxDocument, err := tagvalue.Read(tv.r)
if err != nil {
return xerrors.Errorf("failed to load tag-value spdx: %w", err)
}
a, ok := v.(*SPDX)
if !ok {
return xerrors.Errorf("invalid struct type tag-value decoder needed SPDX struct")
}
if err = a.unmarshal(spdxDocument); err != nil {
return xerrors.Errorf("failed to unmarshal spdx: %w", err)
}
return nil
}
func (s *SPDX) UnmarshalJSON(b []byte) error {
if s.BOM == nil {
s.BOM = core.NewBOM(core.Options{})
}
if s.pkgFilePaths == nil {
s.pkgFilePaths = make(map[common.ElementID]string)
}
spdxDocument, err := json.Read(bytes.NewReader(b))
if err != nil {
return xerrors.Errorf("failed to load spdx json: %w", err)
}
if err = s.unmarshal(spdxDocument); err != nil {
return xerrors.Errorf("failed to unmarshal spdx: %w", err)
}
return nil
}
func (s *SPDX) unmarshal(spdxDocument *spdx.Document) error {
s.trivySBOM = s.isTrivySBOM(spdxDocument)
// Parse files and find file paths for packages
s.parseFiles(spdxDocument)
// Convert all SPDX packages into Trivy components
components, err := s.parsePackages(spdxDocument)
if err != nil {
return xerrors.Errorf("package parse error: %w", err)
}
// Parse relationships and build the dependency graph
for _, rel := range spdxDocument.Relationships {
// Skip the DESCRIBES relationship.
if rel.Relationship == common.TypeRelationshipDescribe || rel.Relationship == "DESCRIBE" {
continue
}
compA, ok := components[rel.RefA.ElementRefID]
if !ok { // Skip if parent is not Package
continue
}
compB, ok := components[rel.RefB.ElementRefID]
if !ok { // Skip if child is not Package
continue
}
s.BOM.AddRelationship(compA, compB, s.parseRelationshipType(rel.Relationship))
}
return nil
}
// parseFiles parses Relationships and finds filepaths for packages
func (s *SPDX) parseFiles(spdxDocument *spdx.Document) {
fileSPDXIdentifierMap := lo.SliceToMap(spdxDocument.Files, func(file *spdx.File) (common.ElementID, *spdx.File) {
return file.FileSPDXIdentifier, file
})
for _, rel := range spdxDocument.Relationships {
if rel.Relationship != common.TypeRelationshipContains && rel.Relationship != "CONTAIN" {
// Skip the DESCRIBES relationship.
continue
}
// hasFiles field is deprecated
// /~https://github.com/spdx/tools-golang/issues/171
// hasFiles values converted in Relationships
// /~https://github.com/spdx/tools-golang/pull/201
if isFile(rel.RefB.ElementRefID) {
file, ok := fileSPDXIdentifierMap[rel.RefB.ElementRefID]
if ok {
// Save filePaths for packages
// Insert filepath will be later
s.pkgFilePaths[rel.RefA.ElementRefID] = file.FileName
}
continue
}
}
}
func (s *SPDX) parsePackages(spdxDocument *spdx.Document) (map[common.ElementID]*core.Component, error) {
// Find a root package
var rootID common.ElementID
for _, rel := range spdxDocument.Relationships {
if rel.RefA.ElementRefID == DocumentSPDXIdentifier && rel.Relationship == RelationShipDescribe {
rootID = rel.RefB.ElementRefID
break
}
}
// Convert packages into components
components := make(map[common.ElementID]*core.Component)
for _, pkg := range spdxDocument.Packages {
component, err := s.parsePackage(*pkg)
if err != nil {
return nil, xerrors.Errorf("failed to parse package: %w", err)
}
components[pkg.PackageSPDXIdentifier] = component
if pkg.PackageSPDXIdentifier == rootID {
component.Root = true
}
s.BOM.AddComponent(component)
}
return components, nil
}
func (s *SPDX) parsePackage(spdxPkg spdx.Package) (*core.Component, error) {
var err error
component := &core.Component{
Type: s.parseType(spdxPkg),
Name: spdxPkg.PackageName,
Version: spdxPkg.PackageVersion,
}
// PURL
if component.PkgIdentifier.PURL, err = s.parseExternalReferences(spdxPkg.PackageExternalReferences); err != nil {
return nil, xerrors.Errorf("external references error: %w", err)
}
// License
if spdxPkg.PackageLicenseDeclared != "NONE" {
component.Licenses = strings.Split(spdxPkg.PackageLicenseDeclared, ",")
}
// Source package
if strings.HasPrefix(spdxPkg.PackageSourceInfo, SourcePackagePrefix) {
srcPkgName := strings.TrimPrefix(spdxPkg.PackageSourceInfo, fmt.Sprintf("%s: ", SourcePackagePrefix))
component.SrcName, component.SrcVersion, _ = strings.Cut(srcPkgName, " ")
}
// Files
// TODO: handle checksums as well
if path, ok := s.pkgFilePaths[spdxPkg.PackageSPDXIdentifier]; ok {
component.Files = []core.File{
{Path: path},
}
} else if len(spdxPkg.Files) > 0 {
component.Files = []core.File{
{Path: spdxPkg.Files[0].FileName}, // Take the first file name
}
}
// Trivy stores properties in Annotations
// But previous versions stored properties in AttributionTexts
// So we need to check both cases to maintain backward compatibility
var props []string
if len(spdxPkg.Annotations) > 0 {
for _, annotation := range spdxPkg.Annotations {
props = append(props, annotation.AnnotationComment)
}
} else if len(spdxPkg.PackageAttributionTexts) > 0 {
for _, attr := range spdxPkg.PackageAttributionTexts {
props = append(props, attr)
}
}
for _, prop := range props {
k, v, ok := strings.Cut(prop, ": ")
if !ok {
continue
}
component.Properties = append(component.Properties, core.Property{
Name: k,
Value: v,
})
}
// For backward-compatibility
// Older Trivy versions put the file path in "sourceInfo" and the package type in "name".
if s.trivySBOM && component.Type == core.TypeApplication && spdxPkg.PackageSourceInfo != "" {
component.Name = spdxPkg.PackageSourceInfo
component.Properties = append(component.Properties, core.Property{
Name: core.PropertyType,
Value: spdxPkg.PackageName,
})
}
return component, nil
}
func (s *SPDX) parseType(pkg spdx.Package) core.ComponentType {
id := string(pkg.PackageSPDXIdentifier)
switch {
case strings.HasPrefix(id, ElementOperatingSystem):
return core.TypeOS
case strings.HasPrefix(id, ElementApplication):
return core.TypeApplication
case strings.HasPrefix(id, ElementPackage):
return core.TypeLibrary
default:
return core.TypeLibrary // unknown is handled as a library
}
}
func (s *SPDX) parseRelationshipType(rel string) core.RelationshipType {
switch rel {
case common.TypeRelationshipDescribe:
return core.RelationshipDescribes
case common.TypeRelationshipContains, "CONTAIN":
return core.RelationshipContains
case common.TypeRelationshipDependsOn:
return core.RelationshipDependsOn
default:
return core.RelationshipContains
}
}
func (s *SPDX) parseExternalReferences(refs []*spdx.PackageExternalReference) (*packageurl.PackageURL, error) {
for _, ref := range refs {
// Extract the package information from PURL
if ref.RefType != RefTypePurl || ref.Category != CategoryPackageManager {
continue
}
packageURL, err := packageurl.FromString(ref.Locator)
if err != nil {
return nil, xerrors.Errorf("failed to parse purl from string: %w", err)
}
return &packageURL, nil
}
return nil, nil
}
func (s *SPDX) isTrivySBOM(spdxDocument *spdx.Document) bool {
if spdxDocument == nil || spdxDocument.CreationInfo == nil || spdxDocument.CreationInfo.Creators == nil {
return false
}
for _, c := range spdxDocument.CreationInfo.Creators {
if c.CreatorType == "Tool" && strings.HasPrefix(c.Creator, "trivy") {
return true
}
}
return false
}
func isFile(elementID spdx.ElementID) bool {
return strings.HasPrefix(string(elementID), ElementFile)
}