-
Notifications
You must be signed in to change notification settings - Fork 103
Support PNPM Auto Fix #1296
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+434
−242
Merged
Support PNPM Auto Fix #1296
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
7affb71
init
orto17 09f3c8f
pnpm fix
orto17 75bc80f
pnpm fix
orto17 c76aa14
delete test files
orto17 de6b168
after code review
orto17 c8475e6
after code review
orto17 2472e00
static analysis
orto17 be77ca4
after cr
orto17 44e8e1a
test fix
orto17 8b0b7e6
test fix
orto17 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,21 +1,44 @@ | ||
| package packageupdaters | ||
|
|
||
| import ( | ||
| "errors" | ||
| "fmt" | ||
| "io/fs" | ||
| "os" | ||
| "os/exec" | ||
| "path/filepath" | ||
| "regexp" | ||
| "strings" | ||
| "time" | ||
|
|
||
| "github.com/jfrog/gofrog/datastructures" | ||
| "github.com/jfrog/jfrog-cli-security/utils/techutils" | ||
| "github.com/jfrog/jfrog-client-go/utils/log" | ||
| "github.com/tidwall/gjson" | ||
| "github.com/tidwall/sjson" | ||
| "golang.org/x/exp/slices" | ||
|
|
||
| "github.com/jfrog/frogbot/v2/utils" | ||
| ) | ||
|
|
||
| // Node | ||
| const ( | ||
| nodePackageJSONFileName = "package.json" | ||
| nodeModulesDirName = "node_modules" | ||
| nodeDependenciesSection = "dependencies" | ||
| nodeDevDependenciesSection = "devDependencies" | ||
| nodeOptionalDependenciesSection = "optionalDependencies" | ||
| nodeOverridesSection = "overrides" | ||
| nodePackageManagerInstallTimeout = 15 * time.Minute | ||
| ) | ||
|
|
||
| var nodePackageManifestSections = []string{ | ||
| nodeDependenciesSection, | ||
| nodeDevDependenciesSection, | ||
| nodeOptionalDependenciesSection, | ||
| nodeOverridesSection, | ||
| } | ||
|
|
||
| // PackageUpdater interface to hold operations on packages | ||
| type PackageUpdater interface { | ||
| UpdateDependency(details *utils.VulnerabilityDetails) error | ||
|
|
@@ -54,6 +77,124 @@ func GetCompatiblePackageUpdater(vulnDetails *utils.VulnerabilityDetails, detail | |
| // TODO can be deleted if not needed after refactoring all package updaters | ||
| type CommonPackageUpdater struct{} | ||
|
|
||
| // evidencePathLooksLikeNpmPackageCoordinate detects scanner evidence paths like "[email protected]/package.json" (not real paths). Pnpm filters these; npm does not. | ||
| func evidencePathLooksLikeNpmPackageCoordinate(evidenceFile string) bool { | ||
| dir := filepath.Dir(evidenceFile) | ||
| if dir == "." || dir == "" { | ||
| return false | ||
| } | ||
| for _, part := range strings.Split(filepath.ToSlash(dir), "/") { | ||
| if part == "" || part == "." { | ||
| continue | ||
| } | ||
| if strings.Contains(part, "@") && !strings.HasPrefix(part, "@") { | ||
| return true | ||
| } | ||
| } | ||
| return false | ||
| } | ||
|
|
||
| func (cph *CommonPackageUpdater) CollectVulnerabilityDescriptorPaths(vulnDetails *utils.VulnerabilityDetails, namesFilters []string, ignoreFilters []string) []string { | ||
| pathsSet := datastructures.MakeSet[string]() | ||
| for _, component := range vulnDetails.Components { | ||
| for _, evidence := range component.Evidences { | ||
| if evidence.File == "" || techutils.IsTechnologyDescriptor(evidence.File) == techutils.NoTech || slices.ContainsFunc(ignoreFilters, func(pattern string) bool { return strings.Contains(evidence.File, pattern) }) { | ||
| continue | ||
| } | ||
| if len(namesFilters) == 0 || slices.Contains(namesFilters, filepath.Base(evidence.File)) { | ||
| pathsSet.Add(evidence.File) | ||
| } | ||
| } | ||
| } | ||
| return pathsSet.ToSlice() | ||
| } | ||
|
|
||
| // BuildPackageDependencyLineRegex builds a regexp for matching a dependency line in a manifest. | ||
| func (cph *CommonPackageUpdater) BuildPackageDependencyLineRegex(impactedName, impactedVersion, dependencyLineFormat string) *regexp.Regexp { | ||
| regexpFitImpactedName := strings.ToLower(regexp.QuoteMeta(impactedName)) | ||
| regexpFitImpactedVersion := strings.ToLower(regexp.QuoteMeta(impactedVersion)) | ||
| regexpCompleteFormat := fmt.Sprintf(strings.ToLower(dependencyLineFormat), regexpFitImpactedName, regexpFitImpactedVersion) | ||
| return regexp.MustCompile(regexpCompleteFormat) | ||
| } | ||
|
|
||
| func escapeJsonPathKey(key string) string { | ||
| r := strings.NewReplacer(".", "\\.", "*", "\\*", "?", "\\?") | ||
| return r.Replace(key) | ||
| } | ||
|
|
||
| // GetFixedPackageJSONManifest returns manifest bytes with packageName set to newVersion in allowed sections. | ||
| func (cph *CommonPackageUpdater) GetFixedPackageJSONManifest(content []byte, packageName, newVersion, descriptorPath string) ([]byte, error) { | ||
| updated := false | ||
| escapedName := escapeJsonPathKey(packageName) | ||
|
|
||
| for _, section := range nodePackageManifestSections { | ||
| path := section + "." + escapedName | ||
| if gjson.GetBytes(content, path).Exists() { | ||
| var err error | ||
| content, err = sjson.SetBytes(content, path, newVersion) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("failed to set version for '%s' in section '%s': %w", packageName, section, err) | ||
| } | ||
| updated = true | ||
| } | ||
| } | ||
|
|
||
| if !updated { | ||
| return nil, fmt.Errorf("package '%s' not found in allowed sections [%s] in '%s'", packageName, strings.Join(nodePackageManifestSections, ", "), descriptorPath) | ||
| } | ||
| return content, nil | ||
| } | ||
|
|
||
| // UpdatePackageJSONDescriptor writes the fixed version for packageName to descriptorPath and returns original file bytes for rollback. | ||
| func (cph *CommonPackageUpdater) UpdatePackageJSONDescriptor(descriptorPath, packageName, newVersion string) ([]byte, error) { | ||
| //#nosec G304 -- descriptorPath comes from vulnerability evidence in the scanned repository. | ||
| descriptorContent, err := os.ReadFile(descriptorPath) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("failed to read file '%s': %w", descriptorPath, err) | ||
| } | ||
|
|
||
| backupContent := make([]byte, len(descriptorContent)) | ||
| copy(backupContent, descriptorContent) | ||
|
|
||
| updatedContent, err := cph.GetFixedPackageJSONManifest(descriptorContent, packageName, newVersion, descriptorPath) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("failed to update version in descriptor: %w", err) | ||
| } | ||
|
|
||
| //#nosec G306 G703 -- 0644 for checked-out source; path same trusted source as ReadFile above. | ||
| if err = os.WriteFile(descriptorPath, updatedContent, 0644); err != nil { | ||
| return nil, fmt.Errorf("failed to write updated descriptor '%s': %w", descriptorPath, err) | ||
| } | ||
| return backupContent, nil | ||
| } | ||
|
|
||
| func (cph *CommonPackageUpdater) withDescriptorWorkingDir(descriptorPath, originalWd string, fn func() error) (err error) { | ||
| descriptorDir := filepath.Dir(descriptorPath) | ||
| if err = os.Chdir(descriptorDir); err != nil { | ||
| return fmt.Errorf("failed to change directory to '%s': %w", descriptorDir, err) | ||
| } | ||
| defer func() { | ||
| if chErr := os.Chdir(originalWd); chErr != nil { | ||
| err = errors.Join(err, fmt.Errorf("failed to return to original directory: %w", chErr)) | ||
| } | ||
| }() | ||
| return fn() | ||
| } | ||
|
|
||
| func (cph *CommonPackageUpdater) buildEnvWithOverrides(overrides map[string]string) []string { | ||
| env := make([]string, 0, len(os.Environ())+len(overrides)) | ||
| for _, e := range os.Environ() { | ||
| key := strings.SplitN(e, "=", 2)[0] | ||
| if _, shouldOverride := overrides[key]; !shouldOverride { | ||
| env = append(env, e) | ||
| } | ||
| } | ||
| for key, value := range overrides { | ||
| env = append(env, fmt.Sprintf("%s=%s", key, value)) | ||
| } | ||
| return env | ||
| } | ||
|
|
||
| // UpdateDependency updates the impacted package to the fixed version | ||
| func (cph *CommonPackageUpdater) UpdateDependency(vulnDetails *utils.VulnerabilityDetails, installationCommand string, extraArgs ...string) (err error) { | ||
| // Lower the package name to avoid duplicates | ||
|
|
@@ -70,13 +211,31 @@ func runPackageMangerCommand(commandName string, techName string, commandArgs [] | |
| fullCommand := commandName + " " + strings.Join(commandArgs, " ") | ||
| log.Debug(fmt.Sprintf("Running '%s'", fullCommand)) | ||
| //#nosec G204 -- False positive - the subprocess only runs after the user's approval. | ||
| output, err := exec.Command(commandName, commandArgs...).CombinedOutput() | ||
| cmd := exec.Command(commandName, commandArgs...) | ||
| if commandName == "pnpm" { | ||
| cmd.Env = envWithCorepackIntegrityWorkaround(os.Environ()) | ||
| } | ||
| output, err := cmd.CombinedOutput() | ||
| if err != nil { | ||
| return fmt.Errorf("failed to update %s dependency: '%s' command failed: %s\n%s", techName, fullCommand, err.Error(), output) | ||
| } | ||
| return nil | ||
| } | ||
|
|
||
| // envWithCorepackIntegrityWorkaround sets COREPACK_INTEGRITY_KEYS=0 for older Node/Corepack (e.g. corepack#612). | ||
| // Also applied after buildEnvWithOverrides for pnpm lockfile regeneration so Corepack-invoked pnpm matches runPackageMangerCommand behavior. | ||
| func envWithCorepackIntegrityWorkaround(base []string) []string { | ||
| const key = "COREPACK_INTEGRITY_KEYS" | ||
| prefix := key + "=" | ||
| out := make([]string, 0, len(base)+1) | ||
| for _, e := range base { | ||
| if !strings.HasPrefix(e, prefix) { | ||
| out = append(out, e) | ||
| } | ||
| } | ||
| return append(out, prefix+"0") | ||
| } | ||
|
|
||
| // Returns the updated package and version as it should be run in the update command: | ||
| // If the package manager expects a single string (example: <packName>@<version>) it returns []string{<packName>@<version>} | ||
| // If the command args suppose to be seperated by spaces (example: <packName> -v <version>) it returns []string{<packName>, "-v", <version>} | ||
|
|
@@ -129,23 +288,11 @@ func (cph *CommonPackageUpdater) GetAllDescriptorFilesFullPaths(descriptorFilesS | |
| } | ||
|
|
||
| func BuildPackageWithVersionRegex(impactedName, impactedVersion, dependencyLineFormat string) *regexp.Regexp { | ||
| regexpFitImpactedName := strings.ToLower(regexp.QuoteMeta(impactedName)) | ||
| regexpFitImpactedVersion := strings.ToLower(regexp.QuoteMeta(impactedVersion)) | ||
| regexpCompleteFormat := fmt.Sprintf(strings.ToLower(dependencyLineFormat), regexpFitImpactedName, regexpFitImpactedVersion) | ||
| return regexp.MustCompile(regexpCompleteFormat) | ||
| var c CommonPackageUpdater | ||
| return c.BuildPackageDependencyLineRegex(impactedName, impactedVersion, dependencyLineFormat) | ||
| } | ||
|
|
||
| func GetVulnerabilityLocations(vulnDetails *utils.VulnerabilityDetails, namesFilters []string, ignoreFilters []string) []string { | ||
| pathsSet := datastructures.MakeSet[string]() | ||
| for _, component := range vulnDetails.Components { | ||
| for _, evidence := range component.Evidences { | ||
| if evidence.File == "" || techutils.IsTechnologyDescriptor(evidence.File) == techutils.NoTech || slices.ContainsFunc(ignoreFilters, func(pattern string) bool { return strings.Contains(evidence.File, pattern) }) { | ||
| continue | ||
| } | ||
| if len(namesFilters) == 0 || slices.Contains(namesFilters, filepath.Base(evidence.File)) { | ||
| pathsSet.Add(evidence.File) | ||
| } | ||
| } | ||
| } | ||
| return pathsSet.ToSlice() | ||
| var c CommonPackageUpdater | ||
| return c.CollectVulnerabilityDescriptorPaths(vulnDetails, namesFilters, ignoreFilters) | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.