Files

347 lines
12 KiB
Go

package bun
import (
"context"
"encoding/json/jsontext"
"encoding/json/v2"
"fmt"
"io"
"slices"
"sort"
"strings"
"github.com/samber/lo"
"golang.org/x/xerrors"
"github.com/aquasecurity/go-version/pkg/semver"
"github.com/aquasecurity/trivy/pkg/dependency"
ftypes "github.com/aquasecurity/trivy/pkg/fanal/types"
"github.com/aquasecurity/trivy/pkg/log"
"github.com/aquasecurity/trivy/pkg/set"
xio "github.com/aquasecurity/trivy/pkg/x/io"
xjson "github.com/aquasecurity/trivy/pkg/x/json"
)
type LockFile struct {
Packages map[string]ParsedPackage `json:"packages"`
Workspaces map[string]Workspace `json:"workspaces"`
LockfileVersion int `json:"lockfileVersion"`
}
type Workspace struct {
Name string `json:"name"`
Version string `json:"version"`
Dependencies map[string]string `json:"dependencies"`
DevDependencies map[string]string `json:"devDependencies"`
OptionalDependencies map[string]string `json:"optionalDependencies"`
PeerDependencies map[string]string `json:"peerDependencies"`
}
type ParsedPackage struct {
Identifier string
Meta map[string]any
xjson.Location
}
type Parser struct {
logger *log.Logger
}
func NewParser() *Parser {
return &Parser{
logger: log.WithPrefix("bun"),
}
}
func (p *ParsedPackage) UnmarshalJSON(data []byte) error {
var raw []jsontext.Value
if err := json.Unmarshal(data, &raw); err != nil {
return fmt.Errorf("expected package format: %w", err)
}
if len(raw) < 1 {
return fmt.Errorf("invalid package entry: not enough elements: %s", string(data))
}
if err := json.Unmarshal(raw[0], &p.Identifier); err != nil {
return err
}
// When package contains only package field [pkg: string]
// cf. https://github.com/oven-sh/bun/blob/61e03a275885b9b48f7a28f6dfbbbe1156eedca6/packages/bun-types/bun.d.ts#L7751
if len(raw) == 1 {
return nil
}
// Meta can be 2 or 3 array elements
// [pkg: string, info: BunLockFilePackageInfo]
// [pkg: string, info: BunLockFilePackageInfo, bunTag: string]
// [pkg: string, info: Pick<BunLockFileBasePackageInfo, "bin" | "binDir">]
// [pkg: string, registry: string, info: BunLockFilePackageInfo, integrity: string]
// cf.https://github.com/oven-sh/bun/blob/61e03a275885b9b48f7a28f6dfbbbe1156eedca6/packages/bun-types/bun.d.ts#L7745-L7755
metaRaw := raw[1]
if len(raw) > 3 {
metaRaw = raw[2]
}
return json.Unmarshal(metaRaw, &p.Meta)
}
func (p *Parser) Parse(_ context.Context, r xio.ReadSeekerAt) ([]ftypes.Package, []ftypes.Dependency, error) {
var lockFile LockFile
data, err := io.ReadAll(r)
if err != nil {
return nil, nil, xerrors.Errorf("file read error: %w", err)
}
if err = xjson.UnmarshalJSONC(data, &lockFile); err != nil {
return nil, nil, xerrors.Errorf("JSON decode error: %w", err)
}
// pkgs and deps are keyed by the install path (the key in `packages`),
// e.g. "debug" or "send/debug" for a nested copy.
pkgs, depNames, wsPaths := p.parsePackages(lockFile)
deps := p.resolveDependencies(depNames, pkgs)
prodDirectDeps, devDirectDeps := resolveDirectDependencies(lockFile.Workspaces, wsPaths, pkgs)
for pkgPath, pkg := range pkgs {
// A workspace member stays a workspace even when another workspace depends on it.
if pkg.Relationship == ftypes.RelationshipWorkspace {
continue
}
if prodDirectDeps.Contains(pkgPath) || devDirectDeps.Contains(pkgPath) {
pkg.Relationship = ftypes.RelationshipDirect
pkgs[pkgPath] = pkg
}
}
for pkgPath := range prodDirectDeps.Iter() {
if pkgs[pkgPath].Relationship != ftypes.RelationshipDirect {
continue
}
walkProdPackages(pkgPath, pkgs, deps, set.New[string]())
}
pkgSlice, depSlice := mergePackages(pkgs, deps)
sort.Sort(ftypes.Packages(pkgSlice))
sort.Sort(ftypes.Dependencies(depSlice))
return pkgSlice, depSlice, nil
}
// parsePackages returns the packages and the names of their dependencies keyed by the install path,
// and the install paths of the workspaces keyed by the workspace directory (the key in `workspaces`).
func (p *Parser) parsePackages(lockFile LockFile) (map[string]ftypes.Package, map[string][]string, map[string]string) {
pkgs := make(map[string]ftypes.Package, len(lockFile.Packages))
depNames := make(map[string][]string)
// The root workspace has no entry in `packages`; its dependencies are installed at the top level.
wsPaths := map[string]string{"": ""}
for pkgPath, parsed := range lockFile.Packages {
// The map key is an install path, which for deduped/nested dependencies
// is "parent/child" (e.g. "glob/minimatch") rather than the package name.
// The name and version come from the identifier ("minimatch@9.0.5").
name, pkgVersion := splitIdentifier(parsed.Identifier)
if name == "" {
p.logger.Debug("Skip package with empty name", log.String("pkg_path", pkgPath))
continue
}
relationship := ftypes.RelationshipIndirect
// A workspace member is written as "<name>@workspace:<dir>",
// e.g. "a": ["a@workspace:packages/a"] for the workspace "packages/a".
if wsDir, ok := strings.CutPrefix(pkgVersion, "workspace:"); ok {
ws := lockFile.Workspaces[wsDir]
wsPaths[wsDir] = pkgPath
pkgVersion = ws.Version
relationship = ftypes.RelationshipWorkspace
// Since lockfileVersion 1 a workspace entry has no metadata, so its dependencies come from `workspaces`.
// Duplicates (e.g. a peer dependency that is also a dev dependency,
// or the dependencies in the metadata of lockfileVersion 0) are removed in mergePackages.
depNames[pkgPath] = slices.Concat(lo.Keys(ws.Dependencies), lo.Keys(ws.PeerDependencies),
lo.Keys(ws.OptionalDependencies), lo.Keys(ws.DevDependencies))
}
if pkgVersion != "" {
if _, err := semver.Parse(pkgVersion); err != nil {
p.logger.Debug("Skip non-semver package version", log.String("pkg_path", pkgPath),
log.String("version", pkgVersion), log.Err(err))
pkgVersion = ""
}
}
pkgs[pkgPath] = ftypes.Package{
ID: packageID(name, pkgVersion),
Name: name,
Version: pkgVersion,
Relationship: relationship,
Dev: lo.Ternary(relationship == ftypes.RelationshipWorkspace, false, true), // Workspaces are always prod deps. Other dependencies are handled later.
Locations: []ftypes.Location{ftypes.Location(parsed.Location)},
}
if depMap, ok := parsed.Meta["dependencies"].(map[string]any); ok && len(depMap) > 0 {
depNames[pkgPath] = append(depNames[pkgPath], lo.Keys(depMap)...)
}
}
return pkgs, depNames, wsPaths
}
// resolveDependencies resolves dependency names to install paths once all packages are collected,
// so that a nested copy is used instead of the hoisted one when it exists.
func (p *Parser) resolveDependencies(depNames map[string][]string, pkgs map[string]ftypes.Package) map[string][]string {
deps := make(map[string][]string, len(depNames))
for pkgPath, names := range depNames {
var dependsOn []string
for _, depName := range names {
depPath, ok := resolveDependency(pkgPath, depName, pkgs)
if !ok {
p.logger.Debug("Unable to resolve the dependency", log.String("pkg_path", pkgPath),
log.String("dependency", depName))
continue
}
dependsOn = append(dependsOn, depPath)
}
if len(dependsOn) > 0 {
sort.Strings(dependsOn)
deps[pkgPath] = dependsOn
}
}
return deps
}
// resolveDirectDependencies returns the install paths of the direct prod and dev dependencies of all workspaces.
// They are resolved from the install path of each workspace,
// e.g. "lodash" of the workspace "packages/a" installed at "a" resolves to "a/lodash" if it exists.
func resolveDirectDependencies(workspaces map[string]Workspace, wsPaths map[string]string,
pkgs map[string]ftypes.Package) (set.Set[string], set.Set[string]) {
prodDirectDeps := set.New[string]()
devDirectDeps := set.New[string]()
for wsDir, ws := range workspaces {
resolve := func(depNames map[string]string) []string {
var depPaths []string
for depName := range depNames {
if depPath, ok := resolveDependency(wsPaths[wsDir], depName, pkgs); ok {
depPaths = append(depPaths, depPath)
}
}
return depPaths
}
prodDirectDeps.Append(resolve(ws.Dependencies)...)
prodDirectDeps.Append(resolve(ws.PeerDependencies)...)
prodDirectDeps.Append(resolve(ws.OptionalDependencies)...)
devDirectDeps.Append(resolve(ws.DevDependencies)...)
}
return prodDirectDeps, devDirectDeps
}
// walkProdPackages marks all packages in the dependency tree of the given package as prod packages (Dev == false).
func walkProdPackages(pkgPath string, pkgs map[string]ftypes.Package, deps map[string][]string, visited set.Set[string]) {
if visited.Contains(pkgPath) {
return
}
// Disable Dev field for prod pkgs.
pkg := pkgs[pkgPath]
pkg.Dev = false
pkgs[pkgPath] = pkg
visited.Append(pkgPath)
// The dependencies of a workspace include its dev dependencies, so the walk stops at a workspace.
// Its prod dependencies are walked as direct dependencies.
if pkg.Relationship == ftypes.RelationshipWorkspace {
return
}
for _, dep := range deps[pkgPath] {
walkProdPackages(dep, pkgs, deps, visited)
}
}
// resolveDependency returns the install path of the dependency `depName` of the package at `pkgPath`.
// It follows the Node.js resolution: the nearest nested copy wins, then the top-level one.
// e.g. for pkgPath == "send/debug" and depName == "ms":
// - "send/debug/ms"
// - "send/ms"
// - "ms"
func resolveDependency(pkgPath, depName string, pkgs map[string]ftypes.Package) (string, bool) {
segments := splitPath(pkgPath)
for i := len(segments); i > 0; i-- {
parentPath := strings.Join(segments[:i], "/")
// bun writes an entry for every ancestor of a nested package,
// so there is nothing to look up above a missing one.
if _, ok := pkgs[parentPath]; !ok {
break
}
depPath := parentPath + "/" + depName
if _, ok := pkgs[depPath]; ok {
return depPath, true
}
}
if _, ok := pkgs[depName]; ok {
return depName, true
}
return "", false
}
// splitPath splits an install path into package names.
// A scoped name is a single segment, e.g. "glob/@isaacs/cliui" -> ["glob", "@isaacs/cliui"].
func splitPath(pkgPath string) []string {
var segments []string
parts := strings.Split(pkgPath, "/")
for i := 0; i < len(parts); i++ {
if strings.HasPrefix(parts[i], "@") && i+1 < len(parts) {
segments = append(segments, parts[i]+"/"+parts[i+1])
i++
continue
}
segments = append(segments, parts[i])
}
return segments
}
// mergePackages merges packages installed under several paths with the same ID
// (e.g. "express/debug" and "send/debug"), as the npm parser does.
func mergePackages(pkgs map[string]ftypes.Package, deps map[string][]string) ([]ftypes.Package, []ftypes.Dependency) {
merged := make(map[string]ftypes.Package, len(pkgs))
for _, pkg := range pkgs {
if savedPkg, ok := merged[pkg.ID]; ok {
savedPkg.Dev = savedPkg.Dev && pkg.Dev
if savedPkg.Relationship == ftypes.RelationshipIndirect && pkg.Relationship == ftypes.RelationshipDirect {
savedPkg.Relationship = ftypes.RelationshipDirect
}
savedPkg.Locations = append(savedPkg.Locations, pkg.Locations...)
sort.Sort(savedPkg.Locations)
pkg = savedPkg
}
merged[pkg.ID] = pkg
}
// Copies of a package may resolve their dependencies to different paths, so the dependencies of all copies are combined.
dependsOn := make(map[string][]string)
for pkgPath, depPaths := range deps {
pkgID := pkgs[pkgPath].ID
for _, depPath := range depPaths {
dependsOn[pkgID] = append(dependsOn[pkgID], pkgs[depPath].ID)
}
}
depSlice := lo.MapToSlice(dependsOn, func(id string, depIDs []string) ftypes.Dependency {
slices.Sort(depIDs)
return ftypes.Dependency{
ID: id,
DependsOn: slices.Compact(depIDs),
}
})
return lo.Values(merged), depSlice
}
// splitIdentifier splits a bun lockfile package identifier ("name@version")
// into its name and version. The version can itself contain "@" (e.g. the git
// dependency "adm-zip@git+ssh://git@github.com/..."), so it splits at the first
// "@" after an optional leading "@" of a scoped name ("@types/node@22.15.18").
func splitIdentifier(identifier string) (name, version string) {
rest, scoped := strings.CutPrefix(identifier, "@")
name, version, _ = strings.Cut(rest, "@")
if scoped {
name = "@" + name
}
return name, version
}
func packageID(name, version string) string {
return dependency.ID(ftypes.Bun, name, version)
}