File: merge.go

package info (click to toggle)
golang-github-containers-buildah 1.39.3%2Bds1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 7,724 kB
  • sloc: sh: 2,398; makefile: 236; perl: 187; asm: 16; awk: 12; ansic: 1
file content (296 lines) | stat: -rw-r--r-- 9,283 bytes parent folder | download
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
package sbom

import (
	"encoding/json"
	"fmt"
	"io"
	"os"
	"sort"

	"github.com/containers/buildah/define"
)

// getComponentNameVersionPurl extracts the "name", "version", and "purl"
// fields of a CycloneDX component record
func getComponentNameVersionPurl(anyComponent any) (string, string, error) {
	if component, ok := anyComponent.(map[string]any); ok {
		// read the "name" field
		anyName, ok := component["name"]
		if !ok {
			return "", "", fmt.Errorf("no name in component %v", anyComponent)
		}
		name, ok := anyName.(string)
		if !ok {
			return "", "", fmt.Errorf("name %v is not a string", anyName)
		}
		// read the optional "version" field
		var version string
		anyVersion, ok := component["version"]
		if ok {
			if version, ok = anyVersion.(string); !ok {
				return "", "", fmt.Errorf("version %v is not a string", anyVersion)
			}
		}
		// combine them
		nameWithVersion := name
		if version != "" {
			nameWithVersion += ("@" + version)
		}
		// read the optional "purl" field
		var purl string
		anyPurl, ok := component["purl"]
		if ok {
			if purl, ok = anyPurl.(string); !ok {
				return "", "", fmt.Errorf("purl %v is not a string", anyPurl)
			}
		}
		return nameWithVersion, purl, nil
	}
	return "", "", fmt.Errorf("component %v is not an object", anyComponent)
}

// getPackageNameVersionInfoPurl extracts the "name", "versionInfo", and "purl"
// fields of an SPDX package record
func getPackageNameVersionInfoPurl(anyPackage any) (string, string, error) {
	if pkg, ok := anyPackage.(map[string]any); ok {
		// read the "name" field
		anyName, ok := pkg["name"]
		if !ok {
			return "", "", fmt.Errorf("no name in package %v", anyPackage)
		}
		name, ok := anyName.(string)
		if !ok {
			return "", "", fmt.Errorf("name %v is not a string", anyName)
		}
		// read the optional "versionInfo" field
		var versionInfo string
		if anyVersionInfo, ok := pkg["versionInfo"]; ok {
			if versionInfo, ok = anyVersionInfo.(string); !ok {
				return "", "", fmt.Errorf("versionInfo %v is not a string", anyVersionInfo)
			}
		}
		// combine them
		nameWithVersionInfo := name
		if versionInfo != "" {
			nameWithVersionInfo += ("@" + versionInfo)
		}
		// now look for optional externalRefs[].purl if "referenceCategory"
		// is "PACKAGE-MANAGER" and "referenceType" is "purl"
		var purl string
		if anyExternalRefs, ok := pkg["externalRefs"]; ok {
			if externalRefs, ok := anyExternalRefs.([]any); ok {
				for _, anyExternalRef := range externalRefs {
					if externalRef, ok := anyExternalRef.(map[string]any); ok {
						anyReferenceCategory, ok := externalRef["referenceCategory"]
						if !ok {
							continue
						}
						if referenceCategory, ok := anyReferenceCategory.(string); !ok || referenceCategory != "PACKAGE-MANAGER" {
							continue
						}
						anyReferenceType, ok := externalRef["referenceType"]
						if !ok {
							continue
						}
						if referenceType, ok := anyReferenceType.(string); !ok || referenceType != "purl" {
							continue
						}
						if anyReferenceLocator, ok := externalRef["referenceLocator"]; ok {
							if purl, ok = anyReferenceLocator.(string); !ok {
								return "", "", fmt.Errorf("purl %v is not a string", anyReferenceLocator)
							}
						}
					}
				}
			}
		}
		return nameWithVersionInfo, purl, nil
	}
	return "", "", fmt.Errorf("package %v is not an object", anyPackage)
}

// getLicenseID extracts the "licenseId" field of an SPDX license record
func getLicenseID(anyLicense any) (string, error) {
	var licenseID string
	if lic, ok := anyLicense.(map[string]any); ok {
		anyID, ok := lic["licenseId"]
		if !ok {
			return "", fmt.Errorf("no licenseId in license %v", anyID)
		}
		id, ok := anyID.(string)
		if !ok {
			return "", fmt.Errorf("licenseId %v is not a string", anyID)
		}
		licenseID = id
	}
	return licenseID, nil
}

// mergeSlicesWithoutDuplicates merges a named slice in "base" with items from
// the same slice in "merge", so long as getKey() returns values for them that
// it didn't for items from the "base" slice
func mergeSlicesWithoutDuplicates(base, merge map[string]any, sliceField string, getKey func(record any) (string, error)) error {
	uniqueKeys := make(map[string]struct{})
	// go through all of the values in the base slice, grab their
	// keys, and note them
	baseRecords := base[sliceField]
	baseRecordsSlice, ok := baseRecords.([]any)
	if !ok {
		baseRecordsSlice = []any{}
	}
	for _, anyRecord := range baseRecordsSlice {
		key, err := getKey(anyRecord)
		if err != nil {
			return err
		}
		uniqueKeys[key] = struct{}{}
	}
	// go through all of the record values in the merge doc, grab their
	// associated keys, and append them to the base records slice if we
	// haven't seen the key yet
	mergeRecords := merge[sliceField]
	mergeRecordsSlice, ok := mergeRecords.([]any)
	if !ok {
		mergeRecordsSlice = []any{}
	}
	for _, anyRecord := range mergeRecordsSlice {
		key, err := getKey(anyRecord)
		if err != nil {
			return err
		}
		if _, present := uniqueKeys[key]; !present {
			baseRecordsSlice = append(baseRecordsSlice, anyRecord)
			uniqueKeys[key] = struct{}{}
		}
	}
	if len(baseRecordsSlice) > 0 {
		base[sliceField] = baseRecordsSlice
	}
	return nil
}

// decodeJSON decodes a file into a map
func decodeJSON(inputFile string, document *map[string]any) error {
	src, err := os.Open(inputFile)
	if err != nil {
		return err
	}
	defer src.Close()
	if err = json.NewDecoder(src).Decode(document); err != nil {
		return fmt.Errorf("decoding JSON document from %q: %w", inputFile, err)
	}
	return nil
}

// encodeJSON encodes a map and saves it to a file
func encodeJSON(outputFile string, document any) error {
	dst, err := os.Create(outputFile)
	if err != nil {
		return err
	}
	defer dst.Close()
	if err = json.NewEncoder(dst).Encode(document); err != nil {
		return fmt.Errorf("writing JSON document to %q: %w", outputFile, err)
	}
	return nil
}

// Merge adds the contents of inputSBOM to inputOutputSBOM using one of a
// handful of named strategies.
func Merge(mergeStrategy define.SBOMMergeStrategy, inputOutputSBOM, inputSBOM, outputPURL string) (err error) {
	type purlImageContents struct {
		Dependencies []string `json:"dependencies,omitempty"`
	}
	type purlDocument struct {
		ImageContents purlImageContents `json:"image_contents,omitempty"`
	}
	purls := []string{}
	seenPurls := make(map[string]struct{})

	switch mergeStrategy {
	case define.SBOMMergeStrategyCycloneDXByComponentNameAndVersion:
		var base, merge map[string]any
		if err = decodeJSON(inputOutputSBOM, &base); err != nil {
			return fmt.Errorf("reading first SBOM to be merged from %q: %w", inputOutputSBOM, err)
		}
		if err = decodeJSON(inputSBOM, &merge); err != nil {
			return fmt.Errorf("reading second SBOM to be merged from %q: %w", inputSBOM, err)
		}

		// merge the "components" lists based on unique combinations of
		// "name" and "version" fields, and save unique package URL
		// values
		err = mergeSlicesWithoutDuplicates(base, merge, "components", func(anyPackage any) (string, error) {
			nameWithVersion, purl, err := getComponentNameVersionPurl(anyPackage)
			if purl != "" {
				if _, seen := seenPurls[purl]; !seen {
					purls = append(purls, purl)
					seenPurls[purl] = struct{}{}
				}
			}
			return nameWithVersion, err
		})
		if err != nil {
			return fmt.Errorf("merging the %q field of CycloneDX SBOMs: %w", "components", err)
		}

		// save the updated doc
		err = encodeJSON(inputOutputSBOM, base)

	case define.SBOMMergeStrategySPDXByPackageNameAndVersionInfo:
		var base, merge map[string]any
		if err = decodeJSON(inputOutputSBOM, &base); err != nil {
			return fmt.Errorf("reading first SBOM to be merged from %q: %w", inputOutputSBOM, err)
		}
		if err = decodeJSON(inputSBOM, &merge); err != nil {
			return fmt.Errorf("reading second SBOM to be merged from %q: %w", inputSBOM, err)
		}

		// merge the "packages" lists based on unique combinations of
		// "name" and "versionInfo" fields, and save unique package URL
		// values
		err = mergeSlicesWithoutDuplicates(base, merge, "packages", func(anyPackage any) (string, error) {
			nameWithVersionInfo, purl, err := getPackageNameVersionInfoPurl(anyPackage)
			if purl != "" {
				if _, seen := seenPurls[purl]; !seen {
					purls = append(purls, purl)
					seenPurls[purl] = struct{}{}
				}
			}
			return nameWithVersionInfo, err
		})
		if err != nil {
			return fmt.Errorf("merging the %q field of SPDX SBOMs: %w", "packages", err)
		}

		// merge the "hasExtractedLicensingInfos" lists based on unique
		// "licenseId" values
		err = mergeSlicesWithoutDuplicates(base, merge, "hasExtractedLicensingInfos", getLicenseID)
		if err != nil {
			return fmt.Errorf("merging the %q field of SPDX SBOMs: %w", "hasExtractedLicensingInfos", err)
		}

		// save the updated doc
		err = encodeJSON(inputOutputSBOM, base)

	case define.SBOMMergeStrategyCat:
		dst, err := os.OpenFile(inputOutputSBOM, os.O_RDWR|os.O_APPEND, 0o644)
		if err != nil {
			return err
		}
		defer dst.Close()
		src, err := os.Open(inputSBOM)
		if err != nil {
			return err
		}
		defer src.Close()
		if _, err = io.Copy(dst, src); err != nil {
			return err
		}
	}
	if err == nil {
		sort.Strings(purls)
		err = encodeJSON(outputPURL, &purlDocument{purlImageContents{Dependencies: purls}})
	}
	return err
}