generated from kubernetes/kubernetes-template-project
-
Notifications
You must be signed in to change notification settings - Fork 45
/
parser.go
855 lines (777 loc) · 23.6 KB
/
parser.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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
/*
Copyright 2021 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package spdx
import (
"bufio"
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/url"
"os"
"regexp"
"strings"
"time"
"github.com/sirupsen/logrus"
"sigs.k8s.io/bom/pkg/spdx/json/document"
spdx22JSON "sigs.k8s.io/bom/pkg/spdx/json/v2.2"
spdx23JSON "sigs.k8s.io/bom/pkg/spdx/json/v2.3"
"sigs.k8s.io/release-utils/http"
)
// Regexp to match the tag-value spdx expressions
var (
tagRegExp = regexp.MustCompile(`^([a-z0-9A-Z]+):\s+(.+)`)
relationshioRegExp = regexp.MustCompile(`^*(\S+)\s+([_A-Z]+)\s+(\S+)`)
)
// OpenDoc opens a file, parses a SPDX tag-value file and returns a loaded
// spdx.Document object. This functions has the cyclomatic chec disabled as
// it spans specific cases for each of the tags it recognizes.
func OpenDoc(path string) (doc *Document, err error) {
// support reading SBOMs from STDIN
var file *os.File
var isTemp bool
if path == "-" || path == "" {
if path == "" {
fi, err := os.Stdin.Stat()
if err != nil {
return nil, fmt.Errorf("checking stdin for data: %w", err)
}
if (fi.Mode() & os.ModeCharDevice) != 0 {
return nil, fmt.Errorf("document path not specified")
}
}
isTemp = true
file, err = bufferSTDIN()
if err != nil {
return nil, fmt.Errorf("reading STDIN: %w", err)
}
} else if isURL(path) {
file, err = tempFileFromURL(path)
if err != nil {
return nil, fmt.Errorf("get temp file from url: %w", err)
}
isTemp = true
} else {
file, err = os.Open(path)
if err != nil {
return nil, fmt.Errorf("opening document from %s: %w", path, err)
}
}
defer func() {
file.Close()
if isTemp {
os.Remove(file.Name())
}
}()
format, err := DetectSBOMEncoding(file)
if err != nil {
return nil, fmt.Errorf("detecting sbom encoding: %w", err)
}
logrus.Debugf("document format is %s", format)
switch format {
case "spdx":
return parseTagValue(file)
case "spdx+json":
return parseJSON(file)
}
return nil, errors.New("unknown SBOM encoding")
}
func tempFileFromURL(query string) (*os.File, error) {
response, err := http.GetURLResponse(query, false)
if err != nil {
return nil, fmt.Errorf("retrieving URL resposne from %s: %w", query, err)
}
file, err := os.CreateTemp("", "sbom-")
if err != nil {
return nil, fmt.Errorf("create temp file for URL response: %w", err)
}
if _, err := file.WriteString(response); err != nil {
return nil, fmt.Errorf("write response to file: %w", err)
}
if _, err := file.Seek(0, io.SeekStart); err != nil {
return nil, fmt.Errorf("seek file start: %w", err)
}
return file, nil
}
func isURL(str string) bool {
u, err := url.Parse(str)
return err == nil && u.Scheme != "" && u.Host != ""
}
// parseJSON parses an SPDX document encoded in json
//
//nolint:gocyclo
func parseJSON(file *os.File) (doc *Document, err error) {
var jsonDoc document.Document
// Read the SPDX doc into the json struct
var data []byte
data, err = os.ReadFile(file.Name())
if err != nil {
return nil, fmt.Errorf("reading SBOM file: %w", err)
}
var spdxVersion string
if bytes.Contains(data, []byte("SPDX-2.3")) {
doc := spdx23JSON.Document{
CreationInfo: spdx23JSON.CreationInfo{
Creators: []string{},
},
DocumentDescribes: []string{},
Files: []spdx23JSON.File{},
Packages: []spdx23JSON.Package{},
Relationships: []spdx23JSON.Relationship{},
ExternalDocumentRefs: []spdx23JSON.ExternalDocumentRef{},
}
if err := json.Unmarshal(data, &doc); err != nil {
return nil, fmt.Errorf("parsing SBOM json: %w", err)
}
spdxVersion = "2.3"
jsonDoc = &doc
} else {
doc := spdx22JSON.Document{
CreationInfo: spdx22JSON.CreationInfo{
Creators: []string{},
},
DocumentDescribes: []string{},
Files: []spdx22JSON.File{},
Packages: []spdx22JSON.Package{},
Relationships: []spdx22JSON.Relationship{},
ExternalDocumentRefs: []spdx22JSON.ExternalDocumentRef{},
}
if err := json.Unmarshal(data, &doc); err != nil {
return nil, fmt.Errorf("parsing SBOM json: %w", err)
}
spdxVersion = "2.2"
jsonDoc = &doc
}
doc = &Document{
Version: jsonDoc.GetVersion(),
DataLicense: jsonDoc.GetDataLicense(),
ID: jsonDoc.GetID(),
Name: jsonDoc.GetName(),
Creator: struct {
Person string
Organization string
Tool []string
}{
Tool: []string{},
},
Namespace: jsonDoc.GetNamespace(),
Packages: map[string]*Package{},
Files: map[string]*File{},
ExternalDocRefs: []ExternalDocumentRef{},
}
creationInfo := jsonDoc.GetCreationInfo()
for _, c := range creationInfo.GetCreators() {
// Technical limitation in bom: We only have one person and one org
ps := strings.SplitN(c, ":", 2)
if len(ps) != 2 {
logrus.Errorf("unable to parse creator data: %s", c)
continue
}
ps[1] = strings.TrimSpace(ps[1])
switch ps[0] {
case entPerson:
if doc.Creator.Person == "" {
doc.Creator.Person = ps[1]
} else {
logrus.Warnf("Ignoring additional SBOM Creator Person")
}
case entOrganization:
if doc.Creator.Organization == "" {
doc.Creator.Organization = ps[1]
} else {
logrus.Warnf("Ignoring additional SBOM Creator Organization")
}
case entTool:
doc.Creator.Tool = append(doc.Creator.Tool, ps[1])
default:
logrus.Errorf("Unknown creator record: %s", ps[0])
}
}
doc.LicenseListVersion = creationInfo.GetLicenseListVersion()
createdDate := creationInfo.GetCreated()
if createdDate != "" {
t, err := time.Parse("2006-01-02T15:04:05Z", createdDate)
if err != nil {
logrus.Errorf("unable to parse creation time: %s: %s", createdDate, err)
} else {
doc.Created = t
}
}
allPackages := map[string]*Package{}
for _, pData := range jsonDoc.GetPackages() {
packageID := pData.GetID()
allPackages[packageID] = &Package{
Entity: Entity{
ID: pData.GetID(),
Name: pData.GetName(),
DownloadLocation: pData.GetDownloadLocation(),
CopyrightText: pData.GetCopyrightText(),
LicenseConcluded: pData.GetLicenseDeclared(),
// LicenseComments: pData.LicenseComments,
Relationships: []*Relationship{},
Checksum: map[string]string{},
},
FilesAnalyzed: pData.GetFilesAnalyzed(),
LicenseInfoFromFiles: []string{},
LicenseDeclared: pData.GetLicenseDeclared(),
Version: pData.GetVersion(),
VerificationCode: pData.GetVerificationCode().GetValue(),
// Comment: pData.Comment,
// HomePage: pData.HomePage,
Supplier: struct {
Person string
Organization string
}{},
Originator: struct {
Person string
Organization string
}{},
ExternalRefs: []ExternalRef{},
}
if spdxVersion == "2.3" {
allPackages[packageID].PrimaryPurpose = pData.GetPrimaryPurpose()
}
for _, cs := range pData.GetChecksums() {
allPackages[packageID].Checksum[cs.GetAlgorithm()] = cs.GetValue()
}
for _, eref := range pData.GetExternalRefs() {
allPackages[packageID].ExternalRefs = append(
allPackages[packageID].ExternalRefs, ExternalRef{
Category: eref.GetCategory(),
Type: eref.GetType(),
Locator: eref.GetLocator(),
},
)
}
}
allFiles := map[string]*File{}
for _, fData := range jsonDoc.GetFiles() {
fileID := fData.GetID()
allFiles[fileID] = &File{
Entity: Entity{
ID: fileID,
Name: fData.GetName(),
CopyrightText: fData.GetCopyrightText(),
LicenseConcluded: fData.GetLicenseConcluded(),
// LicenseComments: pData.LicenseComments,
Relationships: []*Relationship{},
Checksum: map[string]string{},
},
FileType: []string{},
LicenseInfoInFile: strings.Join(
fData.GetLicenseInfoInFile(), " AND ",
),
}
for _, cs := range fData.GetChecksums() {
allFiles[fileID].Checksum[cs.GetAlgorithm()] = cs.GetValue()
}
}
seenObjects := map[string]string{}
// Populate the package and file relationships before adding
// the root level elements
for _, r := range jsonDoc.GetRelationships() {
var source Object
var peer Object
var relatedID string
var externalID string
elementID := r.GetElement()
relatedID = r.GetRelated()
typeID := r.GetType()
// Look for the source element
if _, ok := allPackages[elementID]; ok {
source = allPackages[elementID]
} else if _, ok := allFiles[elementID]; ok {
source = allFiles[elementID]
}
if source == nil && elementID != jsonDoc.GetID() {
logrus.Warnf("Unable to find SPDX source element %s", elementID)
continue
}
// Look for the peer element, exception: peer may be
// an external reference
if strings.HasPrefix(relatedID, "DocumentRef-") {
externalID = relatedID
parts := strings.SplitN(relatedID, ":", 2)
if len(parts) != 2 {
logrus.Errorf("Unable to parse external reference %s", relatedID)
continue
}
relatedID = parts[1]
} else if typeID == string(DESCRIBES) && elementID == jsonDoc.GetID() {
// Handle top-level packages marked by a relationship
if p, ok := allPackages[relatedID]; ok {
doc.Packages[relatedID] = p
} else if f, ok := allFiles[relatedID]; ok {
doc.Files[relatedID] = f
} else {
logrus.Warnf("Unable to find SPDX source element %s", relatedID)
continue
}
seenObjects[relatedID] = relatedID
} else {
if _, ok := allPackages[relatedID]; ok {
peer = allPackages[relatedID]
} else if _, ok := allFiles[relatedID]; ok {
peer = allFiles[relatedID]
}
if peer == nil {
logrus.Warnf("unable to find SPDX related element %s", relatedID)
continue
}
relatedID = peer.SPDXID()
}
if source != nil {
rel := Relationship{
PeerReference: relatedID,
PeerExtReference: externalID,
Comment: "",
Type: RelationshipType(typeID),
Peer: peer,
}
source.AddRelationship(&rel)
}
// Note those objects we've seen to keep track of any loose items
if peer != nil {
seenObjects[peer.SPDXID()] = peer.SPDXID()
}
}
// Add the top level packages
for _, el := range jsonDoc.GetDocumentDescribes() {
var p *Package
var f *File
var ok bool
if p, ok = allPackages[el]; ok {
doc.Packages[p.SPDXID()] = p
seenObjects[el] = el
continue
}
if f, ok = allFiles[el]; ok {
doc.Files[f.SPDXID()] = f
seenObjects[el] = el
continue
}
logrus.Errorf("unable to find package %s described by sbom", el)
}
// Delete everything from the all maps to see if we missed anything
for _, id := range seenObjects {
delete(allPackages, id)
delete(allFiles, id)
}
if l := len(allPackages); l > 0 {
logrus.Warnf("%d packages could not be assigned to the SBOM", l)
}
if l := len(allFiles); l > 0 {
logrus.Warnf("%d files could not be assigned to the SBOM", l)
}
// Assign external references
for _, ref := range jsonDoc.GetExternalDocumentRefs() {
cs := ref.GetChecksum()
extRef := ExternalDocumentRef{
ID: ref.GetExternalDocumentID(),
URI: ref.GetSPDXDocument(),
Checksums: map[string]string{
cs.GetAlgorithm(): cs.GetValue(),
},
}
doc.ExternalDocRefs = append(doc.ExternalDocRefs, extRef)
}
return doc, nil
}
// parseTagValue parses an SPDX SBOM in tag-value format
//
//nolint:gocyclo
func parseTagValue(file *os.File) (doc *Document, err error) {
// Create a blank document
doc = &Document{
Packages: map[string]*Package{},
Files: map[string]*File{},
ExternalDocRefs: []ExternalDocumentRef{},
}
// Scan the file, looking for tags
scanner := bufio.NewScanner(file)
i := 0 // Line counter
var currentEntity *Entity
var currentObject Object
var value, tag, textValue string
var captureMultiline bool
objects := map[string]Object{}
rels := []struct {
Source string
Relationship string
Peer string
ExtDoc string
}{}
for scanner.Scan() {
// If we are capturing text for a multiline value, read and add
// the line to the buffer
if captureMultiline {
textValue += scanner.Text() + "\n"
// If we closing tag is not here, continue to the next line
if !strings.Contains(scanner.Text(), "</text>") {
continue
}
// If closing tag found, remove it from value
value = strings.ReplaceAll(textValue, "</text>", "")
textValue = ""
}
// Check if line matches if we are not reading multiline values
if !captureMultiline {
match := tagRegExp.FindStringSubmatch(scanner.Text())
if len(match) != 3 {
continue
}
tag = match[1]
value = match[2]
// If it is a multiline value, start buffering it
if strings.HasPrefix(value, "<text>") {
textValue = strings.ReplaceAll(value, "<text>", "") + "\n"
captureMultiline = true
// It may be that the closing tag is right in the same
// line. If so, capture and finish buffering
if strings.Contains(scanner.Text(), "</text>") {
value = strings.ReplaceAll(textValue, "</text>", "")
textValue = ""
} else {
continue
}
}
}
captureMultiline = false
switch tag {
case "FileName", "PackageName":
// Both FileName or PackageName signal the start of a new entity
// If we have an object, we store it and continue
if currentObject != nil {
currentObject.SetEntity(currentEntity)
if _, ok := objects[currentObject.SPDXID()]; ok {
return nil, fmt.Errorf("duplicate SPDXID %s", currentObject.SPDXID())
}
objects[currentObject.SPDXID()] = currentObject
}
// Create the new entity:
currentEntity = &Entity{}
// And the new SPDX object:
if tag == "FileName" {
currentObject = &File{}
currentEntity.FileName = value
}
if tag == "PackageName" {
currentObject = &Package{}
}
currentEntity.Name = value
case "SPDXID":
logrus.Debugf("Entity ID %s", value)
if currentEntity == nil {
doc.ID = value
} else {
currentEntity.ID = value
}
case "PackageLicenseConcluded", "LicenseConcluded":
if value != NOASSERTION {
currentEntity.LicenseConcluded = value
}
case "PackageCopyrightText", "FileCopyrightText":
if value != NOASSERTION {
currentEntity.CopyrightText = value
}
// Tags for packages
case "FilesAnalyzed":
currentObject.(*Package).FilesAnalyzed = value == "true"
case "PackageVersion":
currentObject.(*Package).Version = value
case "PackageLicenseDeclared":
currentObject.(*Package).LicenseDeclared = value
case "PackageVerificationCode":
currentObject.(*Package).VerificationCode = value
case "PackageComment":
currentObject.(*Package).Comment = value
case "PackageFileName":
currentObject.(*Package).FileName = value
case "PackageHomePage":
currentObject.(*Package).HomePage = value
case "PrimaryPackagePurpose":
purpose := ""
for _, pp := range PackagePurposes {
if pp == value {
purpose = value
}
}
if purpose == "" {
// TODO: Be less strict when parsing
// TODO: Check if the doc is SPDX 2.3 or higher
return nil, fmt.Errorf("invalid package purpose found %s", value)
}
currentObject.(*Package).PrimaryPurpose = purpose
case "PackageLicenseInfoFromFiles":
have := false
// Check if we already have the license
for _, licid := range currentObject.(*Package).LicenseInfoFromFiles {
if licid == value {
have = true
break
}
}
if !have {
currentObject.(*Package).LicenseInfoFromFiles = append(currentObject.(*Package).LicenseInfoFromFiles, value)
}
case "PackageSupplier":
if value == NOASSERTION {
continue
}
// Supplier has a tag/value format inside
match := tagRegExp.FindStringSubmatch(value)
if len(match) != 3 {
return nil, fmt.Errorf("invalid supplier tag syntax at line %d: %s", i, value)
}
switch match[1] {
case entPerson:
currentObject.(*Package).Supplier.Person = match[2]
case entOrganization:
currentObject.(*Package).Supplier.Organization = match[2]
default:
return nil, fmt.Errorf(
"invalid supplier tag '%s' syntax at line %d, valid values are 'Organization' or 'Person'",
match[1], i,
)
}
case "LicenseInfoInFile":
if value != NONE {
currentObject.(*File).LicenseInfoInFile = value
}
case "FileChecksum", "PackageChecksum":
// Checksums are also tag/value -> algo/hash
match := tagRegExp.FindStringSubmatch(value)
if len(match) != 3 {
return nil, fmt.Errorf("invalid checksum tag syntax at line %d", i)
}
if currentEntity.Checksum == nil {
currentEntity.Checksum = map[string]string{}
}
currentEntity.Checksum[match[1]] = match[2]
case "Relationship":
matches := relationshioRegExp.FindStringSubmatch(value)
if len(matches) != 4 {
return nil, fmt.Errorf("invalid SPDX relationship on line %d: %s", i, value)
}
// Check if the relationship is external
ext := ""
if strings.HasPrefix(matches[3], "DocumentRef-") && strings.Contains(matches[3], ":") {
parts := strings.Split(matches[3], ":")
if len(parts) != 2 {
return nil, fmt.Errorf("unable to parse external document reference %s: %w", matches[3], err)
}
matches[3] = parts[0]
ext = parts[1]
}
// Parse the relationship
rels = append(rels, struct {
Source string
Relationship string
Peer string
ExtDoc string
}{
matches[1], matches[2], matches[3], ext,
})
case "PackageDownloadLocation":
if value != NONE {
currentEntity.DownloadLocation = value
}
case "PackageLicenseComments", "LicenseComments":
if value != NONE {
currentEntity.LicenseComments = value
}
// Tags that apply top the doc
case "Created":
t, err := time.Parse("2006-01-02T15:04:05Z", value)
if err != nil {
return nil, fmt.Errorf("parsing time string in file: %s: %w", value, err)
}
doc.Created = t
case "Creator":
// Creator has a tag/value format inside
match := tagRegExp.FindStringSubmatch(value)
if len(match) != 3 {
return nil, fmt.Errorf("invalid creator tag syntax at line %d", i)
}
switch match[1] {
case entPerson:
doc.Creator.Person = match[2]
case entTool:
doc.Creator.Tool = append(doc.Creator.Tool, match[2])
case entOrganization:
doc.Creator.Organization = match[2]
default:
return nil, fmt.Errorf(
"invalid creator tag '%s' syntax at line %d, valid values are 'Tool', 'Organization' or 'Person'",
match[1], i,
)
}
case "DataLicense":
doc.DataLicense = value
case "DocumentName":
doc.Name = value
case "DocumentNamespace":
doc.Namespace = value
case "SPDXVersion":
doc.Version = value
case "ExternalRef":
if _, ok := currentObject.(*Package); ok {
parts := strings.Split(value, " ")
if len(parts) != 3 {
return nil, errors.New("malformed external reference")
}
// Check the external ref category
if _, ok := ExternalRefCategories[parts[0]]; !ok {
return nil, fmt.Errorf("invalid external reference category: %s", parts[0])
}
// And the type
validType := false
for _, t := range ExternalRefCategories[parts[0]] {
if parts[1] == t {
validType = true
break
}
}
if !validType && parts[0] != "OTHER" {
return nil, fmt.Errorf("invalid external reference type: %s", parts[1])
}
currentObject.(*Package).ExternalRefs = append(currentObject.(*Package).ExternalRefs, ExternalRef{
Category: parts[0],
Type: parts[1],
Locator: parts[2],
})
} else {
return nil, errors.New("external reference found outside of package")
}
case "LicenseListVersion":
doc.LicenseListVersion = value
default:
logrus.Debugf("Unknown tag: %s", tag)
}
i++
}
if currentEntity == nil {
return nil, fmt.Errorf("invalid file %s", file.Name())
}
// Add the last object from the doc
currentObject.SetEntity(currentEntity)
if _, ok := objects[currentObject.SPDXID()]; ok {
return nil, fmt.Errorf("duplicate SPDXID %s", currentObject.SPDXID())
}
objects[currentObject.SPDXID()] = currentObject
// If somehow the scanner returned an error. Kill it.
if err := scanner.Err(); err != nil {
return nil, fmt.Errorf("scanned through spdx file, but got an error: %w", err)
}
// Now assign the relationships to the proper objects
owned := map[string]struct{}{}
for _, rdata := range rels {
logrus.Debugf("Procesing %s %s %s", rdata.Source, rdata.Relationship, rdata.Peer)
// If the source is the doc. Add them
if rdata.Source == doc.ID {
if p, ok := objects[rdata.Peer].(*Package); ok {
logrus.Debugf("doc %s describes package %s", doc.ID, rdata.Peer)
doc.Packages[rdata.Peer] = p
}
if f, ok := objects[rdata.Peer].(*File); ok {
logrus.Debugf("doc %s describes file %s", doc.ID, rdata.Peer)
doc.Files[(objects[rdata.Peer]).(*File).SPDXID()] = f
}
continue
}
// Check if the source object is defined
if _, ok := objects[rdata.Source]; !ok {
return nil, fmt.Errorf("unable to find source object with SPDXID %s", rdata.Source)
}
// Check that the peer exists
if _, ok := objects[rdata.Peer]; !ok {
// ... but only if it is not an external document
if rdata.ExtDoc == "" {
return nil, fmt.Errorf("unable to find peer object with SPDXID %s", rdata.Peer)
}
}
if (objects[rdata.Source]).SPDXID() == "" {
logrus.Fatalf("No ID in object %s:\n%+v", rdata.Source, objects[rdata.Source])
}
(objects[rdata.Source]).AddRelationship(&Relationship{
FullRender: false,
PeerReference: rdata.Peer,
Type: RelationshipType(rdata.Relationship),
Peer: objects[rdata.Peer],
PeerExtReference: rdata.ExtDoc,
// Comment: "",
})
owned[rdata.Peer] = struct{}{}
}
// Now, finally any objects not referenced should be made
// leafs of the document
for id, obj := range objects {
if _, ok := owned[id]; !ok {
if p, ok := obj.(*Package); ok {
doc.Packages[id] = p
}
if f, ok := obj.(*File); ok {
doc.Files[id] = f
}
}
}
return doc, nil
}
// detectSBOMEncoding reads a few bytes from the SBOM and returns
func DetectSBOMEncoding(f *os.File) (format string, err error) {
fileScanner := bufio.NewScanner(f)
fileScanner.Split(bufio.ScanLines)
looksLikeCDX := true
for fileScanner.Scan() {
// In JSON, the spdx version field would be quoted
if strings.Contains(fileScanner.Text(), "\"spdxVersion\"") {
format = "spdx+json"
break
} else if strings.Contains(fileScanner.Text(), "SPDXVersion:") {
format = "spdx"
break
}
if strings.Contains(fileScanner.Text(), "bomFormat") && strings.Contains(fileScanner.Text(), "CycloneDX") {
looksLikeCDX = true
}
}
if _, err := f.Seek(0, 0); err != nil {
return "", fmt.Errorf("rewinding file pointer: %w", err)
}
if format != "" {
return format, nil
}
// Print a more accurate warning if trying to ingest a
// CycloneDX document to avoid confusion
if looksLikeCDX {
logrus.Warn("The scanned document looks like a CycloneDX SBOM (not supported by bom)")
} else {
logrus.Warn("Unable to detect SBOM encoding")
}
return "", nil
}
// buyfferSTDIN buffers all of STDIN to a temp file
func bufferSTDIN() (*os.File, error) {
file, err := os.CreateTemp("", "temp-sbom")
if err != nil {
return nil, fmt.Errorf("creating temp file to buffer sbom: %w", err)
}
if _, err := io.Copy(file, os.Stdin); err != nil {
return nil, fmt.Errorf("writing SBOM to temporary file: %w", err)
}
if _, err := file.Seek(0, 0); err != nil {
return nil, fmt.Errorf("rewinding temporary file: %w", err)
}
return file, nil
}