Skip to content

Commit

Permalink
🐛 parse malformed package.json field engines (#5236)
Browse files Browse the repository at this point in the history
Closes #5235

Signed-off-by: Salim Afiune Maya <afiune@mondoo.com>
  • Loading branch information
afiune authored Feb 18, 2025
1 parent fd97fb5 commit c01b7d2
Show file tree
Hide file tree
Showing 4 changed files with 45 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import (
"fmt"
"regexp"
"strings"

"github.com/rs/zerolog/log"
)

// packageJson allows parsing the package json file
Expand All @@ -24,14 +26,43 @@ type packageJson struct {
Dependencies map[string]string `jsonn:"dependencies"`
DevDependencies map[string]string `jsonn:"devDependencies"`
Repository packageJsonRepository `json:"repository"`
Engines map[string]string `jsonn:"engines"`
Engines enginesField `jsonn:"engines"`
CPU []string `json:"cpu"`
OS []string `json:"os"`

// evidence is a list of file paths where the package.json was found
evidence []string `json:"-"`
}

type enginesField map[string]string

func (p *enginesField) UnmarshalJSON(data []byte) error {
var raw interface{}
if err := json.Unmarshal(data, &raw); err != nil {
return err
}

// Default to an empty map
n := map[string]string{}

switch v := raw.(type) {
case map[string]interface{}:
for key, value := range v {
if strVal, ok := value.(string); ok {
n[key] = strVal
} else {
log.Warn().Msgf("invalid type for engines[%s]", key)
}
}
default:
log.Warn().Msgf("invalid engines field type: %T", v)
}

*p = n

return nil
}

type booleanField bool

func (p *booleanField) UnmarshalJSON(data []byte) error {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,13 @@ func TestPackageJson(t *testing.T) {
},
},
},
// https://github.com/mondoohq/cnquery/issues/5235
{
Fixture: "./testdata/engines-malformed-GH5235.json",
Expected: packageJson{
Engines: map[string]string{},
},
},
{
Fixture: "./testdata/homepage.json",
Expected: packageJson{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"engines": [
"node >= 0.8.0"
]
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@
"engines": {
"node": ">=0.10.3 <15"
}
}
}

0 comments on commit c01b7d2

Please sign in to comment.