fix: add panic recovery for license parse (#1839)

* fix: add panic recovery for license parse
---------
Signed-off-by: Christopher Phillips <christopher.phillips@anchore.com>
This commit is contained in:
Christopher Angelo Phillips 2023-05-23 12:58:49 -04:00 committed by GitHub
parent 087a6356b9
commit 4ac8fdf6df
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 14 additions and 4 deletions

View File

@ -3,6 +3,7 @@ package license
import ( import (
"fmt" "fmt"
"runtime/debug"
"github.com/github/go-spdx/v2/spdxexp" "github.com/github/go-spdx/v2/spdxexp"
@ -16,19 +17,28 @@ const (
Concluded Type = "concluded" Concluded Type = "concluded"
) )
func ParseExpression(expression string) (string, error) { func ParseExpression(expression string) (ex string, err error) {
// https://github.com/anchore/syft/issues/1837
// The current spdx library can panic when parsing some expressions
// This is a temporary fix to recover and patch until we can investigate and contribute
// a fix to the upstream github library
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("recovered from panic while parsing license expression at: \n%s", string(debug.Stack()))
}
}()
licenseID, exists := spdxlicense.ID(expression) licenseID, exists := spdxlicense.ID(expression)
if exists { if exists {
return licenseID, nil return licenseID, nil
} }
// If it doesn't exist initially in the SPDX list it might be a more complex expression // If it doesn't exist initially in the SPDX list it might be a more complex expression
// ignored variable is any invalid expressions // ignored variable is any invalid expressions
// TODO: contribute to spdxexp to expose deprecated license IDs // TODO: contribute to spdxexp to expose deprecated license IDs
// https://github.com/anchore/syft/issues/1814 // https://github.com/anchore/syft/issues/1814
valid, _ := spdxexp.ValidateLicenses([]string{expression}) valid, _ := spdxexp.ValidateLicenses([]string{expression})
if !valid { if !valid {
return "", fmt.Errorf("failed to validate spdx expression: %s", expression) return "", fmt.Errorf("invalid SPDX expression: %s", expression)
} }
return expression, nil return expression, nil

View File

@ -62,7 +62,7 @@ func (l Licenses) Swap(i, j int) {
func NewLicense(value string) License { func NewLicense(value string) License {
spdxExpression, err := license.ParseExpression(value) spdxExpression, err := license.ParseExpression(value)
if err != nil { if err != nil {
log.Trace("unable to parse license expression: %w", err) log.Trace("unable to parse license expression for %q: %w", value, err)
} }
return License{ return License{