Debian Codegraph @

spdxexp/satisfies.go

raw symbols SCIP
1 package spdxexp
2
3 import (
4 "errors"
5 "sort"
6 "strings"
7 )
8
9 // ValidateLicenses checks if given licenses are valid according to spdx.
10 // Returns true if all licenses are valid; otherwise, false.
11 // Returns all the invalid licenses contained in the `licenses` argument.
12 func ValidateLicenses(licenses []string) (bool, []string) {
13 return ValidateLicensesWithOptions(licenses, ValidateLicensesOptions{})
14 }
15
16 // ValidateLicensesOptions controls how ValidateLicensesWithOptions validates input.
17 type ValidateLicensesOptions struct {
18 // FailComplexExpressions rejects SPDX license expressions (e.g. "MIT AND Apache-2.0").
19 // Single license identifiers (including those with a WITH exception) are still allowed.
20 FailComplexExpressions bool
21
22 // FailDeprecatedLicenses rejects deprecated SPDX license identifiers (e.g. "eCos-2.0").
23 FailDeprecatedLicenses bool
24
25 // FailAllLicenseRefs rejects all SPDX license references (e.g. "LicenseRef-MyLicense").
26 FailAllLicenseRefs bool
27
28 // FailAllDocumentRefs rejects all SPDX document references (e.g. "DocumentRef-MyDocument").
29 FailAllDocumentRefs bool
30 }
31
32 // ValidateLicensesWithOptions checks if given licenses are valid according to SPDX.
33 // Returns true if all licenses are valid; otherwise, false.
34 // Returns all the invalid licenses contained in the `licenses` argument.
35 func ValidateLicensesWithOptions(licenses []string, options ValidateLicensesOptions) (bool, []string) {
36 // handle all other cases with parsing, which will cover both single and multiple licenses and expressions
37 _, invalidLicenses := ValidateAndNormalizeLicensesWithOptions(licenses, options)
38 return len(invalidLicenses) == 0, invalidLicenses
39 }
40
41 // ValidateAndNormalizeLicensesWithOptions checks if given licenses are valid according to SPDX.
42 // Supports validation options as defined in ValidateLicensesOptions.
43 // Returns all validated licenses in their normalized form as the first return value.
44 // Returns any invalid licenses as the second return value.
45 func ValidateAndNormalizeLicensesWithOptions(licenses []string, options ValidateLicensesOptions) (normalizedLicenses, invalidLicenses []string) {
46 normalizedLicenses = []string{}
47 invalidLicenses = []string{}
48 seenNormalized := make(map[string]struct{}, len(licenses))
49
50 addNormalized := func(license string) {
51 if _, ok := seenNormalized[license]; ok {
52 return
53 }
54 seenNormalized[license] = struct{}{}
55 normalizedLicenses = append(normalizedLicenses, license)
56 }
57
58 for _, license := range licenses {
59 // MIT is the most common license, so check for it first before doing any processing to optimize for this case.
60 // By putting the isMIT check here, we can avoid the overhead of parsing for the most common case of MIT.
61 // Having it before trimming means that licenses with leading/trailing whitespace will not be validated
62 // as MIT by isMIT, but will still be correctly identified using activeLicense. As this is uncommon, it
63 // is an acceptable tradeoff to avoid the overhead of trimming for the more common case.
64 if isMIT(license) {
65 addNormalized("MIT")
66 continue
67 }
68
69 license = strings.TrimSpace(license)
70
71 isAtomic := isAtomicLicense(license)
72 if isAtomic {
73 if ok, normalizedLicense := activeLicense(license); ok {
74 addNormalized(normalizedLicense)
75 continue
76 }
77
78 if ok, normalizedLicense := deprecatedLicense(license); ok {
79 if options.FailDeprecatedLicenses {
80 invalidLicenses = append(invalidLicenses, license)
81 continue
82 }
83 addNormalized(normalizedLicense)
84 // if FailDeprecatedLicenses is false, then consider the deprecated license valid and continue
85 continue
86 }
87
88 if options.FailAllLicenseRefs {
89 if strings.HasPrefix(license, "LicenseRef-") {
90 invalidLicenses = append(invalidLicenses, license)
91 continue
92 }
93 }
94
95 if options.FailAllDocumentRefs {
96 if strings.HasPrefix(license, "DocumentRef-") {
97 invalidLicenses = append(invalidLicenses, license)
98 continue
99 }
100 }
101
102 // need to let this pass through to allow parsing LicenseRef and DocumentRef if either are allowed types
103 }
104
105 if !isAtomic {
106 if hasException, licensePart, exceptionPart := isLicenseWithException(license); hasException {
107 // matches pattern "licensePart WITH exceptionPart", so validate both parts separately
108 if ok, normalizedException := exceptionLicense(exceptionPart); ok {
109 if ok, normalizedLicense := activeLicense(licensePart); ok {
110 addNormalized(normalizedLicense + " WITH " + normalizedException)
111 continue
112 }
113 if !options.FailDeprecatedLicenses {
114 if ok, normalizedLicense := deprecatedLicense(licensePart); ok {
115 addNormalized(normalizedLicense + " WITH " + normalizedException)
116 continue
117 }
118 }
119 }
120 invalidLicenses = append(invalidLicenses, license)
121 continue
122 }
123 }
124
125 // all other non-atomic expressions are complex expressions with conjunctions (e.g. "MIT AND Apache-2.0"),
126 // so fail if complex expressions are not allowed
127 if options.FailComplexExpressions && !isAtomic {
128 invalidLicenses = append(invalidLicenses, license)
129 continue
130 }
131
132 // need to parse if allowing any of LicenseRef, DocumentRef, or complex expressions to be able to determine
133 // whether the license expression is valid
134 var parsedLicense *node
135 var err error
136 if parsedLicense, err = parse(license); err != nil {
137 invalidLicenses = append(invalidLicenses, license)
138 } else {
139 normalizedLicense := *parsedLicense.reconstructedLicenseString()
140 addNormalized(normalizedLicense)
141 }
142 }
143 return normalizedLicenses, invalidLicenses
144 }
145
146 // Satisfies determines if the allowed list of licenses satisfies the test license expression.
147 // Returns true if allowed list satisfies test license expression; otherwise, false.
148 // Returns error if error occurs during processing.
149 func Satisfies(testExpression string, allowedList []string) (bool, error) {
150 if len(allowedList) == 0 {
151 return false, errors.New("allowedList requires at least one element, but is empty")
152 }
153
154 // MIT is the most common license, so check for it first before doing any processing to optimize for this case.
155 // By putting the isMIT check here, we can avoid the overhead of parsing for the most common case of MIT.
156 // Having it before trimming means that licenses with leading/trailing whitespace will not be validated
157 // as MIT by isMIT, but will still be correctly identified using activeLicense. As this is uncommon, it
158 // is an acceptable tradeoff to avoid the overhead of trimming for the more common case.
159 if isMIT(testExpression) {
160 for _, allowed := range allowedList {
161 if strings.EqualFold(allowed, "MIT") {
162 return true, nil
163 }
164 }
165 return false, nil
166 }
167
168 testExpression = strings.TrimSpace(testExpression)
169
170 if isAtomicLicense(testExpression) {
171 // if only one license in the test expression, check for active license to avoid the overhead of parsing
172 if ok, _ := activeLicense(testExpression); ok {
173 for _, allowed := range allowedList {
174 if strings.EqualFold(allowed, testExpression) {
175 return true, nil
176 }
177 }
178 }
179
180 // if only one license in the test expression, check for deprecated license to avoid the overhead of parsing
181 if ok, _ := deprecatedLicense(testExpression); ok {
182 for _, allowed := range allowedList {
183 if strings.EqualFold(allowed, testExpression) {
184 return true, nil
185 }
186 }
187 }
188 }
189
190 // if test expression is a single license with exception, check it now to avoid the overhead of parsing
191 if hasException, licensePart, exceptionPart := isLicenseWithException(testExpression); hasException {
192 // matches pattern "licensePart WITH exceptionPart", so validate both parts separately
193 if ok, _ := activeLicense(licensePart); ok {
194 if ok, _ := exceptionLicense(exceptionPart); ok {
195 for _, allowed := range allowedList {
196 if strings.EqualFold(allowed, testExpression) {
197 return true, nil
198 }
199 }
200 }
201 }
202 }
203
204 // handle all other cases with parsing, which will cover both single and multiple licenses and expressions
205 expressionNode, err := parse(testExpression)
206 if err != nil {
207 return false, err
208 }
209 allowedNodes, err := stringsToNodes(allowedList)
210 if err != nil {
211 return false, err
212 }
213 sortAndDedup(allowedNodes)
214
215 expandedExpression := expressionNode.expand(true)
216
217 for _, expressionPart := range expandedExpression {
218 if isCompatible(expressionPart, allowedNodes) {
219 // return once any expressionPart is compatible with the allow list
220 // * each part is an array of licenses that are ANDed, meaning all have to be on the allowedList
221 // * the parts are ORed, meaning only one of the parts need to be compatible
222 return true, nil
223 }
224 }
225 return false, nil
226 }
227
228 // stringsToNodes converts an array of single license strings to to an array of license nodes.
229 func stringsToNodes(licenseStrings []string) ([]*node, error) {
230 nodes := make([]*node, len(licenseStrings))
231 for i, s := range licenseStrings {
232 node, err := parse(s)
233 if err != nil {
234 return nil, err
235 }
236 if node.isExpression() {
237 return nil, errors.New("expressions are not supported in the allowedList")
238 }
239 nodes[i] = node
240 }
241 return nodes, nil
242 }
243
244 // isMIT checks if the test expression is MIT, ignoring case.
245 // NOTE: Caller should trim the test expression before calling this function to avoid false
246 // negatives (e.g. " MIT " would not match "MIT").
247 func isMIT(testExpression string) bool {
248 return strings.EqualFold(testExpression, "MIT")
249 }
250
251 // isAtomicLicense checks if the test expression is a single license identifier (e.g. "MIT").
252 // NOTE: Caller should trim the test expression before calling this function to avoid false
253 // negatives (e.g. " MIT " would not be considered a single license).
254 func isAtomicLicense(testExpression string) bool {
255 return !strings.Contains(testExpression, " ")
256 }
257
258 // isException checks if the test expression contains two licenses separated by WITH
259 // (e.g. "GPL-2.0-or-later WITH Bison-exception-2.2").
260 // NOTE: Caller should trim the test expression before calling this function to avoid false
261 // negatives (e.g. " MIT " would not be considered a single license).
262 func isLicenseWithException(testExpression string) (bool, string, string) {
263 // split by " " and check if there are exactly 3 parts and the middle part is "WITH"
264 parts := strings.Fields(testExpression)
265 if len(parts) == 3 && strings.EqualFold(parts[1], "WITH") {
266 return true, parts[0], parts[2]
267 }
268 return false, "", ""
269 }
270
271 // isCompatible checks if expressionPart is compatible with allowed list.
272 // Expression part is an array of licenses that are ANDed together.
273 // Allowed is an array of licenses that can fulfill the expression.
274 func isCompatible(expressionPart, allowed []*node) bool {
275 for _, expLicense := range expressionPart {
276 compatible := false
277 for _, allowedLicense := range allowed {
278 nodes := &nodePair{firstNode: expLicense, secondNode: allowedLicense}
279 if nodes.licensesAreCompatible() || nodes.licenseRefsAreCompatible() {
280 compatible = true
281 break
282 }
283 }
284 if !compatible {
285 // no compatible license found for one of the required licenses
286 return false
287 }
288 }
289 // found a compatible license in test for each required license
290 return true
291 }
292
293 // expand will expand the given expression into an equivalent array representing ANDed licenses
294 // grouped in an array and ORed licenses each in a separate array.
295 //
296 // Example:
297 //
298 // License node: "MIT" becomes [["MIT"]]
299 // OR Expression: "MIT OR Apache-2.0" becomes [["MIT"], ["Apache-2.0"]]
300 // AND Expression: "MIT AND Apache-2.0" becomes [["MIT", "Apache-2.0"]]
301 // OR-AND Expression: "MIT OR Apache-2.0 AND GPL-2.0" becomes [["MIT"], ["Apache-2.0", "GPL-2.0"]]
302 // OR(AND) Expression: "MIT OR (Apache-2.0 AND GPL-2.0)" becomes [["MIT"], ["Apache-2.0", "GPL-2.0"]]
303 // AND-OR Expression: "MIT AND Apache-2.0 OR GPL-2.0" becomes [["Apache-2.0", "MIT], ["GPL-2.0"]]
304 // AND(OR) Expression: "MIT AND (Apache-2.0 OR GPL-2.0)" becomes [["Apache-2.0", "MIT], ["GPL-2.0", "MIT"]]
305 // OR-AND-OR Expression: "MIT OR ISC AND Apache-2.0 OR GPL-2.0" becomes
306 // [["MIT"], ["Apache-2.0", "ISC"], ["GPL-2.0"]]
307 // (OR)AND(OR) Expression: "(MIT OR ISC) AND (Apache-2.0 OR GPL-2.0)" becomes
308 // [["Apache-2.0", "MIT"], ["GPL-2.0", "MIT"], ["Apache-2.0", "ISC"], ["GPL-2.0", "ISC"]]
309 // OR(AND)OR Expression: "MIT OR (ISC AND Apache-2.0) OR GPL-2.0" becomes
310 // [["MIT"], ["Apache-2.0", "ISC"], ["GPL-2.0"]]
311 // AND-OR-AND Expression: "MIT AND ISC OR Apache-2.0 AND GPL-2.0" becomes
312 // [["ISC", "MIT"], ["Apache-2.0", "GPL-2.0"]]
313 // (AND)OR(AND) Expression: "(MIT AND ISC) OR (Apache-2.0 AND GPL-2.0)" becomes
314 // [["ISC", "MIT"], ["Apache-2.0", "GPL-2.0"]]
315 // AND(OR)AND Expression: "MIT AND (ISC OR Apache-2.0) AND GPL-2.0" becomes
316 // [["GPL-2.0", "ISC", "MIT"], ["Apache-2.0", "GPL-2.0", "MIT"]]
317 func (n *node) expand(withDeepSort bool) [][]*node {
318 if n.isLicense() || n.isLicenseRef() {
319 return [][]*node{{n}}
320 }
321
322 var expanded [][]*node
323 if n.isOrExpression() {
324 expanded = n.expandOr()
325 } else {
326 expanded = n.expandAnd()
327 }
328
329 if withDeepSort {
330 expanded = deepSort(expanded)
331 }
332 return expanded
333 }
334
335 // expandOr expands the given expression into an equivalent array representing ORed licenses each in a separate array.
336 //
337 // Example:
338 //
339 // OR Expression: "MIT OR Apache-2.0" becomes [["MIT"], ["Apache-2.0"]]
340 func (n *node) expandOr() [][]*node {
341 var result [][]*node
342 result = expandOrTerm(n.left(), result)
343 result = expandOrTerm(n.right(), result)
344 return result
345 }
346
347 // expandOrTerm expands the terms of an OR expression.
348 func expandOrTerm(term *node, result [][]*node) [][]*node {
349 if term.isLicense() {
350 result = append(result, []*node{term})
351 } else if term.isExpression() {
352 if term.isOrExpression() {
353 left := term.expandOr()
354 result = append(result, left...)
355 } else if term.isAndExpression() {
356 left := term.expandAnd()[0]
357 result = append(result, left)
358 }
359 }
360 return result
361 }
362
363 // expandAnd expands the given expression into an equivalent array representing ANDed licenses
364 // grouped in an array. When an ORed expression is combined with AND, the ORed
365 // expressions are combined with the ANDed expressions.
366 //
367 // Example:
368 //
369 // AND Expression: "MIT AND Apache-2.0" becomes [["MIT", "Apache-2.0"]]
370 // AND(OR) Expression: "MIT AND (Apache-2.0 OR GPL-2.0)" becomes [["Apache-2.0", "MIT], ["GPL-2.0", "MIT"]]
371 //
372 // See more examples under func expand.
373 func (n *node) expandAnd() [][]*node {
374 left := expandAndTerm(n.left())
375 right := expandAndTerm(n.right())
376
377 if len(left) > 1 || len(right) > 1 {
378 // an OR expression has been processed
379 // somewhere on the left and/or right node path
380 return appendTerms(left, right)
381 }
382
383 // only AND expressions have been processed
384 return mergeTerms(left, right)
385 }
386
387 // expandAndTerm expands the terms of an AND expression.
388 func expandAndTerm(term *node) [][]*node {
389 var result [][]*node
390 if term.isLicense() || term.isLicenseRef() {
391 result = append(result, []*node{term})
392 } else if term.isExpression() {
393 if term.isAndExpression() {
394 result = term.expandAnd()
395 } else if term.isOrExpression() {
396 result = term.expandOr()
397 }
398 }
399 return result
400 }
401
402 // appendTerms appends results from expanding the right expression into the results
403 // from expanding the left expression. When at least one of the left/right
404 // nodes includes an OR expression, the values are spread across at times
405 // producing more results than exists in the left or right results.
406 //
407 // Example:
408 //
409 // left: {{"MIT"}} right: {{"ISC"}, {"Apache-2.0"}} becomes
410 // {{"MIT", "ISC"}, {"MIT", "Apache-2.0"}}
411 func appendTerms(left, right [][]*node) [][]*node {
412 var result [][]*node
413 for _, r := range right {
414 for _, l := range left {
415 tmp := l
416 tmp = append(tmp, r...)
417 result = append(result, tmp)
418 }
419 }
420 return result
421 }
422
423 // mergeTerms merges results from expanding left and right expressions.
424 // When neither left/right nodes includes an OR expression, the values
425 // are merged left and right results.
426 //
427 // Example:
428 //
429 // left: {{"MIT"}} right: {{"ISC", "Apache-2.0"}} becomes
430 // {{"MIT", "ISC", "Apache-2.0"}}
431 func mergeTerms(left, right [][]*node) [][]*node {
432 results := left
433 for _, r := range right {
434 for j, l := range results {
435 results[j] = append(l, r...)
436 }
437 }
438 return results
439 }
440
441 // sortAndDedup sorts an array of license nodes and then removes duplicates.
442 func sortAndDedup(nodes []*node) []*node {
443 if len(nodes) <= 1 {
444 return nodes
445 }
446
447 sortLicenses(nodes)
448 prev := 1
449 for curr := 1; curr < len(nodes); curr++ {
450 if *nodes[curr-1].reconstructedLicenseString() != *nodes[curr].reconstructedLicenseString() {
451 nodes[prev] = nodes[curr]
452 prev++
453 }
454 }
455
456 return nodes[:prev]
457 }
458
459 // deepSort sorts a two-dimensional array of license nodes. Internal arrays are sorted first.
460 // Then each array of nodes are sorted relative to the other arrays.
461 //
462 // Example:
463 //
464 // BEFORE {{"MIT", "GPL-2.0"}, {"ISC", "Apache-2.0"}}
465 // AFTER {{"Apache-2.0", "ISC"}, {"GPL-2.0", "MIT"}}
466 func deepSort(nodes2d [][]*node) [][]*node {
467 if len(nodes2d) == 0 || len(nodes2d) == 1 && len(nodes2d[0]) <= 1 {
468 return nodes2d
469 }
470
471 // sort each array internally
472 // Example:
473 // BEFORE {{"MIT", "GPL-2.0"}, {"ISC", "Apache-2.0"}}
474 // AFTER {{"GPL-2.0", "MIT"}, {"Apache-2.0", "ISC"}}
475 for _, nodes := range nodes2d {
476 if len(nodes) > 1 {
477 sortLicenses(nodes)
478 }
479 }
480
481 // sort arrays relative to each other
482 // Example:
483 // BEFORE {{"GPL-2.0", "MIT"}, {"Apache-2.0", "ISC"}}
484 // AFTER {{"Apache-2.0", "ISC"}, {"GPL-2.0", "MIT"}}
485 sort.Slice(nodes2d, func(i, j int) bool {
486 // TODO: Consider refactor to map nodes to licenseString before processing.
487 for k := range nodes2d[j] {
488 if k >= len(nodes2d[i]) {
489 // if the first k elements are equal and the second array is
490 // longer than the first, the first is considered less than
491 return true
492 }
493 iLicense := *nodes2d[i][k].reconstructedLicenseString()
494 jLicense := *nodes2d[j][k].reconstructedLicenseString()
495 if iLicense != jLicense {
496 // when elements are not equal, return true if first is less than
497 return iLicense < jLicense
498 }
499 }
500 // all elements are equal, return false to avoid a swap
501 return false
502 })
503
504 return nodes2d
505 }