From 65f55e9fac31ed50cebc3be2fd528ef5f04e9b63 Mon Sep 17 00:00:00 2001 From: bpatra3 Date: Thu, 12 Nov 2026 06:43:31 +0000 Subject: [PATCH 1/3] feat: add support for Mix and Pub package managers - Implemented Mix package manager with sanitization for mix.lock files. - Added tests for Mix sanitization functionality. - Introduced Pub package manager with sanitization for pubspec.lock and pubspec.yaml files. - Added tests for Pub sanitization functionality. - Enhanced utility functions for YAML and TOML parsing. - Updated the main package manager registration to include Mix and Pub. - Refactored existing sanitization logic to improve code reuse and maintainability. Signed-off-by: bpatra3 --- internal/sanitize/pm/bazel/install_json.go | 83 ++++++++ .../sanitize/pm/bazel/install_json_test.go | 132 +++++++++++++ internal/sanitize/pm/bazel/pm.go | 30 +++ internal/sanitize/pm/bazel/pm_test.go | 16 ++ internal/sanitize/pm/bundler/gemfile_lock.go | 111 +++++++++++ .../sanitize/pm/bundler/gemfile_lock_test.go | 91 +++++++++ internal/sanitize/pm/bundler/pm.go | 30 +++ internal/sanitize/pm/bundler/pm_test.go | 16 ++ internal/sanitize/pm/cargo/cargo_lock.go | 55 ++++++ internal/sanitize/pm/cargo/cargo_lock_test.go | 84 ++++++++ internal/sanitize/pm/cargo/pm.go | 29 +++ internal/sanitize/pm/cargo/pm_test.go | 16 ++ internal/sanitize/pm/cocoapods/pm.go | 29 +++ internal/sanitize/pm/cocoapods/pm_test.go | 16 ++ .../sanitize/pm/cocoapods/podfile_lock.go | 98 ++++++++++ .../pm/cocoapods/podfile_lock_test.go | 95 +++++++++ internal/sanitize/pm/godep/gopkg_lock.go | 39 ++++ internal/sanitize/pm/godep/gopkg_lock_test.go | 62 ++++++ internal/sanitize/pm/godep/pm.go | 29 +++ internal/sanitize/pm/godep/pm_test.go | 16 ++ internal/sanitize/pm/mix/mix_lock.go | 66 +++++++ internal/sanitize/pm/mix/mix_lock_test.go | 55 ++++++ internal/sanitize/pm/mix/pm.go | 29 +++ internal/sanitize/pm/mix/pm_test.go | 16 ++ internal/sanitize/pm/pm.go | 16 ++ internal/sanitize/pm/pm_test.go | 2 +- internal/sanitize/pm/pnpm/pnpm_lock.go | 67 ++----- internal/sanitize/pm/pub/pm.go | 31 +++ internal/sanitize/pm/pub/pm_test.go | 17 ++ internal/sanitize/pm/pub/pubspec_lock.go | 49 +++++ internal/sanitize/pm/pub/pubspec_test.go | 184 ++++++++++++++++++ internal/sanitize/pm/pub/pubspec_yaml.go | 54 +++++ .../sanitize/pm/swift/package_resolved.go | 83 ++++++++ .../pm/swift/package_resolved_test.go | 104 ++++++++++ internal/sanitize/pm/swift/pm.go | 32 +++ internal/sanitize/pm/swift/pm_test.go | 16 ++ internal/sanitize/pm/util/context.go | 10 +- internal/sanitize/pm/util/mask.go | 6 + internal/sanitize/pm/util/toml.go | 16 ++ internal/sanitize/pm/util/yaml_nodes.go | 54 +++++ internal/sanitize/sanitize.go | 22 ++- internal/sanitize/sanitize_test.go | 28 ++- 42 files changed, 1971 insertions(+), 63 deletions(-) create mode 100644 internal/sanitize/pm/bazel/install_json.go create mode 100644 internal/sanitize/pm/bazel/install_json_test.go create mode 100644 internal/sanitize/pm/bazel/pm.go create mode 100644 internal/sanitize/pm/bazel/pm_test.go create mode 100644 internal/sanitize/pm/bundler/gemfile_lock.go create mode 100644 internal/sanitize/pm/bundler/gemfile_lock_test.go create mode 100644 internal/sanitize/pm/bundler/pm.go create mode 100644 internal/sanitize/pm/bundler/pm_test.go create mode 100644 internal/sanitize/pm/cargo/cargo_lock.go create mode 100644 internal/sanitize/pm/cargo/cargo_lock_test.go create mode 100644 internal/sanitize/pm/cargo/pm.go create mode 100644 internal/sanitize/pm/cargo/pm_test.go create mode 100644 internal/sanitize/pm/cocoapods/pm.go create mode 100644 internal/sanitize/pm/cocoapods/pm_test.go create mode 100644 internal/sanitize/pm/cocoapods/podfile_lock.go create mode 100644 internal/sanitize/pm/cocoapods/podfile_lock_test.go create mode 100644 internal/sanitize/pm/godep/gopkg_lock.go create mode 100644 internal/sanitize/pm/godep/gopkg_lock_test.go create mode 100644 internal/sanitize/pm/godep/pm.go create mode 100644 internal/sanitize/pm/godep/pm_test.go create mode 100644 internal/sanitize/pm/mix/mix_lock.go create mode 100644 internal/sanitize/pm/mix/mix_lock_test.go create mode 100644 internal/sanitize/pm/mix/pm.go create mode 100644 internal/sanitize/pm/mix/pm_test.go create mode 100644 internal/sanitize/pm/pub/pm.go create mode 100644 internal/sanitize/pm/pub/pm_test.go create mode 100644 internal/sanitize/pm/pub/pubspec_lock.go create mode 100644 internal/sanitize/pm/pub/pubspec_test.go create mode 100644 internal/sanitize/pm/pub/pubspec_yaml.go create mode 100644 internal/sanitize/pm/swift/package_resolved.go create mode 100644 internal/sanitize/pm/swift/package_resolved_test.go create mode 100644 internal/sanitize/pm/swift/pm.go create mode 100644 internal/sanitize/pm/swift/pm_test.go create mode 100644 internal/sanitize/pm/util/toml.go create mode 100644 internal/sanitize/pm/util/yaml_nodes.go diff --git a/internal/sanitize/pm/bazel/install_json.go b/internal/sanitize/pm/bazel/install_json.go new file mode 100644 index 00000000..16b2d55b --- /dev/null +++ b/internal/sanitize/pm/bazel/install_json.go @@ -0,0 +1,83 @@ +package bazel + +import "github.com/debricked/cli/internal/sanitize/pm/util" + +// sanitizeInstallJSON keeps each entry's coord and its edges: directDependencies, or +// dependencies if there are no direct ones, because that is what the backend reads. URLs, mirror +// URLs, file paths and hashes are removed: the URLs can hold private hosts and credentials. +// +// The backend needs dependency_tree, so the newer format without it fails here rather than being +// uploaded and giving no packages. +func sanitizeInstallJSON(content []byte, _ *util.FileContext) ([]byte, error) { + install, err := util.ParseJSONObject(content) + if err != nil { + return nil, util.ErrInvalidFormat + } + tree, isObject := install.Values["dependency_tree"].(*util.OrderedObject) + if !isObject { + return nil, util.ErrInvalidFormat + } + entries, isList := tree.Values["dependencies"].([]any) + if !isList { + return nil, util.ErrInvalidFormat + } + + sanitizedEntries := make([]any, 0, len(entries)) + for _, item := range entries { + entry, isObject := item.(*util.OrderedObject) + if !isObject { + return nil, util.ErrInvalidFormat + } + sanitizedEntry, err := sanitizeEntry(entry) + if err != nil { + return nil, err + } + sanitizedEntries = append(sanitizedEntries, sanitizedEntry) + } + + sanitizedTree := util.NewOrderedObject() + sanitizedTree.Set("dependencies", sanitizedEntries) + sanitized := util.NewOrderedObject() + sanitized.Set("dependency_tree", sanitizedTree) + + return util.EncodeJSON(sanitized) +} + +func sanitizeEntry(entry *util.OrderedObject) (*util.OrderedObject, error) { + coord, isString := entry.Values["coord"].(string) + if !isString || coord == "" { + return nil, util.ErrInvalidFormat + } + sanitized := util.NewOrderedObject() + sanitized.Set("coord", coord) + + for _, key := range []string{"directDependencies", "dependencies"} { + value, present := entry.Values[key] + if !present { + continue + } + coords, err := coordList(value) + if err != nil { + return nil, err + } + sanitized.Set(key, coords) + + break + } + + return sanitized, nil +} + +func coordList(value any) ([]any, error) { + list, isList := value.([]any) + if !isList { + return nil, util.ErrInvalidFormat + } + for _, item := range list { + if _, isString := item.(string); !isString { + return nil, util.ErrInvalidFormat + } + } + + return list, nil +} diff --git a/internal/sanitize/pm/bazel/install_json_test.go b/internal/sanitize/pm/bazel/install_json_test.go new file mode 100644 index 00000000..78dfa66a --- /dev/null +++ b/internal/sanitize/pm/bazel/install_json_test.go @@ -0,0 +1,132 @@ +package bazel + +import ( + "testing" + + "github.com/debricked/cli/internal/sanitize/pm/util" + "github.com/stretchr/testify/assert" +) + +// #nosec G101 -- fake credentials, the test checks they are removed +const installJSONBefore = `{ + "dependency_tree": { + "__AUTOGENERATED_FILE_DO_NOT_MODIFY_THIS_FILE_MANUALLY": 1234, + "__INPUT_ARTIFACTS_HASH": 5678, + "conflict_resolution": {}, + "dependencies": [ + { + "coord": "com.acme:auth-client:2.1.0", + "dependencies": [ + "com.google.guava:guava:32.0.0-jre", + "com.google.code.findbugs:jsr305:3.0.2" + ], + "directDependencies": [ + "com.google.guava:guava:32.0.0-jre" + ], + "file": "v1/https/artifactory.acme.internal/libs/com/acme/auth-client-2.1.0.jar", + "mirror_urls": [ + "https://ci-user:s3cret@artifactory.acme.internal/libs/com/acme/auth-client-2.1.0.jar" + ], + "sha256": "aaaa", + "url": "https://ci-user:s3cret@artifactory.acme.internal/libs/com/acme/auth-client-2.1.0.jar" + }, + { + "coord": "com.google.guava:guava:32.0.0-jre", + "dependencies": [ + "com.google.code.findbugs:jsr305:3.0.2" + ], + "directDependencies": [ + "com.google.code.findbugs:jsr305:3.0.2" + ], + "file": "v1/https/repo1.maven.org/guava.jar", + "sha256": "bbbb", + "url": "https://repo1.maven.org/maven2/guava.jar" + }, + { + "coord": "com.google.code.findbugs:jsr305:3.0.2", + "dependencies": [], + "directDependencies": [], + "file": "v1/https/repo1.maven.org/jsr305.jar", + "sha256": "cccc", + "url": "https://repo1.maven.org/maven2/jsr305.jar" + } + ], + "version": "0.1.0" + } +}` + +const installJSONAfter = `{ + "dependency_tree": { + "dependencies": [ + { + "coord": "com.acme:auth-client:2.1.0", + "directDependencies": [ + "com.google.guava:guava:32.0.0-jre" + ] + }, + { + "coord": "com.google.guava:guava:32.0.0-jre", + "directDependencies": [ + "com.google.code.findbugs:jsr305:3.0.2" + ] + }, + { + "coord": "com.google.code.findbugs:jsr305:3.0.2", + "directDependencies": [] + } + ] + } +} +` + +func TestSanitizeInstallJSON(t *testing.T) { + sanitized, err := sanitizeInstallJSON([]byte(installJSONBefore), nil) + + assert.NoError(t, err) + assert.Equal(t, installJSONAfter, string(sanitized)) + assert.NotContains(t, string(sanitized), "acme.internal") +} + +func TestSanitizeInstallJSONUsesDependenciesWhenThereAreNoDirectOnes(t *testing.T) { + before := `{"dependency_tree": {"dependencies": [ + {"coord": "a:b:1", "dependencies": ["c:d:2"], "url": "https://ci:s3cret@repo.acme.internal/b.jar"}, + {"coord": "c:d:2"} + ]}}` + + sanitized, err := sanitizeInstallJSON([]byte(before), nil) + + assert.NoError(t, err) + assert.Equal(t, `{ + "dependency_tree": { + "dependencies": [ + { + "coord": "a:b:1", + "dependencies": [ + "c:d:2" + ] + }, + { + "coord": "c:d:2" + } + ] + } +} +`, string(sanitized)) +} + +func TestSanitizeInstallJSONInvalid(t *testing.T) { + for _, content := range []string{ + ``, + `[]`, + `{"version": "2", "artifacts": {}}`, + `{"dependency_tree": []}`, + `{"dependency_tree": {"dependencies": {}}}`, + `{"dependency_tree": {"dependencies": ["a:b:1"]}}`, + `{"dependency_tree": {"dependencies": [{"url": "https://repo/b.jar"}]}}`, + `{"dependency_tree": {"dependencies": [{"coord": "a:b:1", "directDependencies": "c:d:2"}]}}`, + `{"dependency_tree": {"dependencies": [{"coord": "a:b:1", "directDependencies": [{"coord": "c:d:2"}]}]}}`, + } { + _, err := sanitizeInstallJSON([]byte(content), nil) + assert.ErrorIs(t, err, util.ErrInvalidFormat, content) + } +} diff --git a/internal/sanitize/pm/bazel/pm.go b/internal/sanitize/pm/bazel/pm.go new file mode 100644 index 00000000..5fd13c79 --- /dev/null +++ b/internal/sanitize/pm/bazel/pm.go @@ -0,0 +1,30 @@ +package bazel + +import "github.com/debricked/cli/internal/sanitize/pm/util" + +const Name = "bazel" + +type Pm struct { + name string +} + +func NewPm() Pm { + return Pm{ + name: Name, + } +} + +func (pm Pm) Name() string { + return pm.name +} + +func (Pm) LockFiles() map[string]util.FileSanitizer { + return map[string]util.FileSanitizer{ + // rules_jvm_external names the file after the repository, such as maven_install.json. + "*_install.json": sanitizeInstallJSON, + } +} + +func (Pm) Manifests() map[string]util.FileSanitizer { + return map[string]util.FileSanitizer{} +} diff --git a/internal/sanitize/pm/bazel/pm_test.go b/internal/sanitize/pm/bazel/pm_test.go new file mode 100644 index 00000000..8e43ad72 --- /dev/null +++ b/internal/sanitize/pm/bazel/pm_test.go @@ -0,0 +1,16 @@ +package bazel + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestNewPm(t *testing.T) { + pm := NewPm() + + assert.Equal(t, Name, pm.Name()) + assert.Len(t, pm.LockFiles(), 1) + assert.Contains(t, pm.LockFiles(), "*_install.json") + assert.Empty(t, pm.Manifests()) +} diff --git a/internal/sanitize/pm/bundler/gemfile_lock.go b/internal/sanitize/pm/bundler/gemfile_lock.go new file mode 100644 index 00000000..1073966c --- /dev/null +++ b/internal/sanitize/pm/bundler/gemfile_lock.go @@ -0,0 +1,111 @@ +package bundler + +import ( + "regexp" + "strings" + + "github.com/debricked/cli/internal/sanitize/pm/util" +) + +const ( + gemSection = "GEM" + gitSection = "GIT" + specsLine = " specs:" + specIndent = " " +) + +var ( + // gemSectionRegex matches section headers such as GEM, PLATFORMS and RUBY VERSION. + gemSectionRegex = regexp.MustCompile(`^[A-Z][A-Z ]*$`) + // gemSpecRegex matches a package line, ` name (version)`. The version can name a platform. + gemSpecRegex = regexp.MustCompile(`^ {4}[^\s()]+ \([^\s()]+\)$`) +) + +// sanitizeGemfileLock keeps the package lines of GEM blocks and the first package line of each +// GIT block, the only lines the backend reads. remote:, revision: and branch: lines are removed, +// because they can hold credentials and branch names. PATH blocks hold local paths and the backend +// ignores them, so they are removed with every other section. Blocks are separated by a blank +// line, which is how the backend splits them. +func sanitizeGemfileLock(content []byte, _ *util.FileContext) ([]byte, error) { + sanitizer := &gemfileLockSanitizer{} + for _, line := range util.SplitLines(content) { + if err := sanitizer.processLine(line); err != nil { + return nil, err + } + } + sanitizer.endSection() + if sanitizer.section == "" { + return nil, util.ErrInvalidFormat + } + + return []byte(strings.Join(sanitizer.blocks, "\n")), nil +} + +type gemfileLockSanitizer struct { + blocks []string + block *gemBlock + section string + inSpecs bool +} + +func (s *gemfileLockSanitizer) processLine(line string) error { + switch { + case strings.TrimSpace(line) == "": + return nil + case line[0] != ' ': + return s.startSection(line) + case s.section == "": + return util.ErrInvalidFormat + case s.block == nil: + return nil + case line == specsLine: + s.inSpecs = true + + return nil + case s.inSpecs && strings.HasPrefix(line, specIndent) && line[len(specIndent)] != ' ': + return s.addSpec(line) + default: + return nil + } +} + +func (s *gemfileLockSanitizer) startSection(line string) error { + if !gemSectionRegex.MatchString(line) { + return util.ErrInvalidFormat + } + s.endSection() + s.section, s.inSpecs = line, false + if line == gemSection || line == gitSection { + s.block = &gemBlock{header: line} + } + + return nil +} + +// addSpec keeps every package of a GEM block, and only the first of a GIT block. +func (s *gemfileLockSanitizer) addSpec(line string) error { + if !gemSpecRegex.MatchString(line) { + return util.ErrInvalidFormat + } + if s.section == gemSection || len(s.block.specs) == 0 { + s.block.specs = append(s.block.specs, line) + } + + return nil +} + +func (s *gemfileLockSanitizer) endSection() { + if s.block != nil && len(s.block.specs) > 0 { + s.blocks = append(s.blocks, s.block.String()) + } + s.block = nil +} + +type gemBlock struct { + header string + specs []string +} + +func (b *gemBlock) String() string { + return b.header + "\n" + specsLine + "\n" + strings.Join(b.specs, "\n") + "\n" +} diff --git a/internal/sanitize/pm/bundler/gemfile_lock_test.go b/internal/sanitize/pm/bundler/gemfile_lock_test.go new file mode 100644 index 00000000..b060b0e2 --- /dev/null +++ b/internal/sanitize/pm/bundler/gemfile_lock_test.go @@ -0,0 +1,91 @@ +package bundler + +import ( + "strings" + "testing" + + "github.com/debricked/cli/internal/sanitize/pm/util" + "github.com/stretchr/testify/assert" +) + +// #nosec G101 -- fake credentials, the test checks they are removed +const gemfileLockBefore = `GIT + remote: git@git.acme.internal:platform/auth-gem.git + revision: 9f3c1ab + branch: feature/PROJ-123-new-login + specs: + acme-auth (2.1.0) + rack (>= 2.0) + acme-auth-extra (2.1.0) + +PATH + remote: ../shared-utils + specs: + acme-shared-utils (1.0.0) + +GEM + remote: https://ci-user:s3cret@gems.acme.internal/ + specs: + acme-logger (1.4.2) + rack (3.0.8) + +GEM + remote: https://rubygems.org/ + specs: + nokogiri (1.16.2-x86_64-linux) + rails (7.1.3) + rack (>= 2.2.4) + +PLATFORMS + x86_64-linux + +DEPENDENCIES + acme-auth! + acme-logger + acme-shared-utils! + rails + +BUNDLED WITH + 2.5.6 +` + +const gemfileLockAfter = `GIT + specs: + acme-auth (2.1.0) + +GEM + specs: + acme-logger (1.4.2) + rack (3.0.8) + +GEM + specs: + nokogiri (1.16.2-x86_64-linux) + rails (7.1.3) +` + +func TestSanitizeGemfileLock(t *testing.T) { + sanitized, err := sanitizeGemfileLock([]byte(gemfileLockBefore), nil) + + assert.NoError(t, err) + assert.Equal(t, gemfileLockAfter, string(sanitized)) +} + +func TestSanitizeGemfileLockCRLF(t *testing.T) { + sanitized, err := sanitizeGemfileLock([]byte(strings.ReplaceAll(gemfileLockBefore, "\n", "\r\n")), nil) + + assert.NoError(t, err) + assert.Equal(t, gemfileLockAfter, string(sanitized)) +} + +func TestSanitizeGemfileLockInvalid(t *testing.T) { + for _, content := range []string{ + "", + " specs:\n rack (3.0.8)\n", + "gem 'rails'\n", + "GEM\n specs:\n rack 3.0.8\n", + } { + _, err := sanitizeGemfileLock([]byte(content), nil) + assert.ErrorIs(t, err, util.ErrInvalidFormat, content) + } +} diff --git a/internal/sanitize/pm/bundler/pm.go b/internal/sanitize/pm/bundler/pm.go new file mode 100644 index 00000000..517c190c --- /dev/null +++ b/internal/sanitize/pm/bundler/pm.go @@ -0,0 +1,30 @@ +package bundler + +import "github.com/debricked/cli/internal/sanitize/pm/util" + +const Name = "bundler" + +type Pm struct { + name string +} + +func NewPm() Pm { + return Pm{ + name: Name, + } +} + +func (pm Pm) Name() string { + return pm.name +} + +func (Pm) LockFiles() map[string]util.FileSanitizer { + return map[string]util.FileSanitizer{ + // Bundler also names lock files after their Gemfile, such as gems.Gemfile.lock. + "*Gemfile.lock": sanitizeGemfileLock, + } +} + +func (Pm) Manifests() map[string]util.FileSanitizer { + return map[string]util.FileSanitizer{} +} diff --git a/internal/sanitize/pm/bundler/pm_test.go b/internal/sanitize/pm/bundler/pm_test.go new file mode 100644 index 00000000..b7f21aed --- /dev/null +++ b/internal/sanitize/pm/bundler/pm_test.go @@ -0,0 +1,16 @@ +package bundler + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestNewPm(t *testing.T) { + pm := NewPm() + + assert.Equal(t, Name, pm.Name()) + assert.Len(t, pm.LockFiles(), 1) + assert.Contains(t, pm.LockFiles(), "*Gemfile.lock") + assert.Empty(t, pm.Manifests()) +} diff --git a/internal/sanitize/pm/cargo/cargo_lock.go b/internal/sanitize/pm/cargo/cargo_lock.go new file mode 100644 index 00000000..f5746c4c --- /dev/null +++ b/internal/sanitize/pm/cargo/cargo_lock.go @@ -0,0 +1,55 @@ +package cargo + +import ( + "strings" + + "github.com/debricked/cli/internal/sanitize/pm/util" + "github.com/pelletier/go-toml/v2" +) + +const ( + maskedGitSource = "git+redacted" + // localCrateVersion replaces the version of the customer's own crates, which are renamed. + localCrateVersion = "0.0.0" +) + +type cargoLock struct { + Packages []struct { + Name string `toml:"name"` + Version string `toml:"version"` + Source string `toml:"source"` + } `toml:"package"` +} + +// sanitizeCargoLock keeps the name and version of each package. The backend only reads whether a +// source starts with "git", so a git source is replaced and other sources are removed. A package +// with no source is the customer's own crate or a path dependency, so it is renamed. +// +// The backend reads the lines after each name without checking where the file ends, so every +// block, including the last, ends with a blank line. +func sanitizeCargoLock(content []byte, context *util.FileContext) ([]byte, error) { + var lock cargoLock + if err := toml.Unmarshal(content, &lock); err != nil || len(lock.Packages) == 0 { + return nil, util.ErrInvalidFormat + } + + var output strings.Builder + for _, crate := range lock.Packages { + if crate.Name == "" { + return nil, util.ErrInvalidFormat + } + name, version := crate.Name, crate.Version + if crate.Source == "" { + name, version = context.ProjectPlaceholder(crate.Name), localCrateVersion + } + output.WriteString("[[package]]\n") + output.WriteString("name = " + util.QuoteTOML(name) + "\n") + output.WriteString("version = " + util.QuoteTOML(version) + "\n") + if strings.HasPrefix(crate.Source, "git") { + output.WriteString("source = " + util.QuoteTOML(maskedGitSource) + "\n") + } + output.WriteString("\n") + } + + return []byte(output.String()), nil +} diff --git a/internal/sanitize/pm/cargo/cargo_lock_test.go b/internal/sanitize/pm/cargo/cargo_lock_test.go new file mode 100644 index 00000000..92e7d7c6 --- /dev/null +++ b/internal/sanitize/pm/cargo/cargo_lock_test.go @@ -0,0 +1,84 @@ +package cargo + +import ( + "testing" + + "github.com/debricked/cli/internal/sanitize/pm/testdata" + "github.com/debricked/cli/internal/sanitize/pm/util" + "github.com/stretchr/testify/assert" +) + +const cargoLockBefore = `# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "acme-auth" +version = "2.1.0" +source = "git+ssh://git@git.acme.internal/platform/auth.git?tag=v2.1.0#9f3c1ab" + +[[package]] +name = "acme-logger" +version = "1.4.2" +source = "registry+https://artifactory.acme.internal/api/cargo/index" +checksum = "aaaa" + +[[package]] +name = "payments-portal" +version = "3.4.1" +dependencies = [ + "acme-auth", + "acme-logger", + "serde", +] + +[[package]] +name = "serde" +version = "1.0.197" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbbb" +` + +const cargoLockAfter = `[[package]] +name = "acme-auth" +version = "2.1.0" +source = "git+redacted" + +[[package]] +name = "acme-logger" +version = "1.4.2" + +[[package]] +name = "debricked-redacted-project-1" +version = "0.0.0" + +[[package]] +name = "serde" +version = "1.0.197" + +` + +func TestSanitizeCargoLock(t *testing.T) { + context, all := testdata.NewContext("Cargo.lock") + + sanitized, err := sanitizeCargoLock([]byte(cargoLockBefore), context) + + assert.NoError(t, err) + assert.Equal(t, cargoLockAfter, string(sanitized)) + assert.Equal(t, []util.MapEntry{ + {Placeholder: "debricked-redacted-project-1", Name: "payments-portal", Path: "Cargo.lock"}, + }, all.Entries()) +} + +func TestSanitizeCargoLockInvalid(t *testing.T) { + for _, content := range []string{ + "", + "version = 3\n", + "not toml at all [[\n", + "[[package]]\nversion = \"1.0.0\"\n", + } { + context, _ := testdata.NewContext("Cargo.lock") + _, err := sanitizeCargoLock([]byte(content), context) + assert.ErrorIs(t, err, util.ErrInvalidFormat, content) + } +} diff --git a/internal/sanitize/pm/cargo/pm.go b/internal/sanitize/pm/cargo/pm.go new file mode 100644 index 00000000..e30b2f17 --- /dev/null +++ b/internal/sanitize/pm/cargo/pm.go @@ -0,0 +1,29 @@ +package cargo + +import "github.com/debricked/cli/internal/sanitize/pm/util" + +const Name = "cargo" + +type Pm struct { + name string +} + +func NewPm() Pm { + return Pm{ + name: Name, + } +} + +func (pm Pm) Name() string { + return pm.name +} + +func (Pm) LockFiles() map[string]util.FileSanitizer { + return map[string]util.FileSanitizer{ + "Cargo.lock": sanitizeCargoLock, + } +} + +func (Pm) Manifests() map[string]util.FileSanitizer { + return map[string]util.FileSanitizer{} +} diff --git a/internal/sanitize/pm/cargo/pm_test.go b/internal/sanitize/pm/cargo/pm_test.go new file mode 100644 index 00000000..59c7047b --- /dev/null +++ b/internal/sanitize/pm/cargo/pm_test.go @@ -0,0 +1,16 @@ +package cargo + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestNewPm(t *testing.T) { + pm := NewPm() + + assert.Equal(t, Name, pm.Name()) + assert.Len(t, pm.LockFiles(), 1) + assert.Contains(t, pm.LockFiles(), "Cargo.lock") + assert.Empty(t, pm.Manifests()) +} diff --git a/internal/sanitize/pm/cocoapods/pm.go b/internal/sanitize/pm/cocoapods/pm.go new file mode 100644 index 00000000..47cd77ae --- /dev/null +++ b/internal/sanitize/pm/cocoapods/pm.go @@ -0,0 +1,29 @@ +package cocoapods + +import "github.com/debricked/cli/internal/sanitize/pm/util" + +const Name = "cocoapods" + +type Pm struct { + name string +} + +func NewPm() Pm { + return Pm{ + name: Name, + } +} + +func (pm Pm) Name() string { + return pm.name +} + +func (Pm) LockFiles() map[string]util.FileSanitizer { + return map[string]util.FileSanitizer{ + "Podfile.lock": sanitizePodfileLock, + } +} + +func (Pm) Manifests() map[string]util.FileSanitizer { + return map[string]util.FileSanitizer{} +} diff --git a/internal/sanitize/pm/cocoapods/pm_test.go b/internal/sanitize/pm/cocoapods/pm_test.go new file mode 100644 index 00000000..66a436eb --- /dev/null +++ b/internal/sanitize/pm/cocoapods/pm_test.go @@ -0,0 +1,16 @@ +package cocoapods + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestNewPm(t *testing.T) { + pm := NewPm() + + assert.Equal(t, Name, pm.Name()) + assert.Len(t, pm.LockFiles(), 1) + assert.Contains(t, pm.LockFiles(), "Podfile.lock") + assert.Empty(t, pm.Manifests()) +} diff --git a/internal/sanitize/pm/cocoapods/podfile_lock.go b/internal/sanitize/pm/cocoapods/podfile_lock.go new file mode 100644 index 00000000..cbeb432e --- /dev/null +++ b/internal/sanitize/pm/cocoapods/podfile_lock.go @@ -0,0 +1,98 @@ +package cocoapods + +import ( + "regexp" + "strings" + + "github.com/debricked/cli/internal/sanitize/pm/util" +) + +const ( + podsSection = "PODS:" + externalSourcesSection = "EXTERNAL SOURCES:" +) + +var ( + // podSectionRegex matches section lines such as PODS: and PODFILE CHECKSUM: cccc. + podSectionRegex = regexp.MustCompile(`^[A-Z][A-Z ]*:`) + // podRegex matches ` - Name (version)`, quoted or not, with the colon that starts a pod's + // own dependency list removed first. + podRegex = regexp.MustCompile(`^ - (?:"[^"\s()]+ \([^"()]+\)"|[^"\s()]+ \([^"()]+\))$`) + // externalSourceRegex matches ` Name:`, the line that names a pod from a git repository or + // a local path. + externalSourceRegex = regexp.MustCompile(`^ (?:"[^"]+"|[^"\s]+):$`) +) + +// sanitizePodfileLock keeps the PODS lines and the names under EXTERNAL SOURCES, which decide the +// pods that have no version. Each pod's dependencies, its git URL, path, branch and commit, and +// every other section are removed. Each section ends with a blank line, because the backend finds +// a section by the blank line after it. +func sanitizePodfileLock(content []byte, _ *util.FileContext) ([]byte, error) { + sanitizer := &podfileLockSanitizer{sections: map[string][]string{}} + for _, line := range util.SplitLines(content) { + if err := sanitizer.processLine(line); err != nil { + return nil, err + } + } + if _, found := sanitizer.sections[podsSection]; !found { + return nil, util.ErrInvalidFormat + } + + var output strings.Builder + for _, name := range []string{podsSection, externalSourcesSection} { + lines, found := sanitizer.sections[name] + if !found { + continue + } + output.WriteString(name + "\n") + for _, line := range lines { + output.WriteString(line + "\n") + } + output.WriteString("\n") + } + + return []byte(output.String()), nil +} + +type podfileLockSanitizer struct { + sections map[string][]string + section string +} + +func (s *podfileLockSanitizer) processLine(line string) error { + switch { + case strings.TrimSpace(line) == "": + return nil + case line[0] != ' ': + return s.startSection(line) + case s.section == "": + return util.ErrInvalidFormat + case s.section == podsSection && strings.HasPrefix(line, " - "): + return s.keep(strings.TrimSuffix(line, ":"), podRegex) + case s.section == externalSourcesSection && strings.HasPrefix(line, " ") && line[2] != ' ': + return s.keep(line, externalSourceRegex) + default: + return nil + } +} + +func (s *podfileLockSanitizer) startSection(line string) error { + if !podSectionRegex.MatchString(line) { + return util.ErrInvalidFormat + } + s.section = line + if line == podsSection || line == externalSourcesSection { + s.sections[line] = []string{} + } + + return nil +} + +func (s *podfileLockSanitizer) keep(line string, allowed *regexp.Regexp) error { + if !allowed.MatchString(line) { + return util.ErrInvalidFormat + } + s.sections[s.section] = append(s.sections[s.section], line) + + return nil +} diff --git a/internal/sanitize/pm/cocoapods/podfile_lock_test.go b/internal/sanitize/pm/cocoapods/podfile_lock_test.go new file mode 100644 index 00000000..3ea61d8b --- /dev/null +++ b/internal/sanitize/pm/cocoapods/podfile_lock_test.go @@ -0,0 +1,95 @@ +package cocoapods + +import ( + "testing" + + "github.com/debricked/cli/internal/sanitize/pm/util" + "github.com/stretchr/testify/assert" +) + +const podfileLockBefore = `PODS: + - AcmeAuth (2.1.0): + - Alamofire (~> 5.0) + - AcmeLogger (1.4.2) + - Alamofire (5.8.1) + - Firebase/Core (10.20.0): + - Firebase/CoreOnly + - Firebase/CoreOnly (10.20.0) + - "GoogleUtilities/Environment (7.12.0)": + - PromisesObjC (< 3.0, >= 1.2) + +DEPENDENCIES: + - AcmeAuth (from ` + "`git@git.acme.internal:ios/auth.git`" + `, branch ` + "`feature/PROJ-123`" + `) + - AcmeLogger (from ` + "`../AcmeLogger`" + `) + - Alamofire + - Firebase/Core + +SPEC REPOS: + "https://cdn.cocoapods.org/": + - Alamofire + "https://git.acme.internal/ios/specs.git": + - Firebase + +EXTERNAL SOURCES: + AcmeAuth: + :branch: feature/PROJ-123 + :git: "git@git.acme.internal:ios/auth.git" + AcmeLogger: + :path: "../AcmeLogger" + +CHECKOUT OPTIONS: + AcmeAuth: + :commit: 9f3c1ab + :git: "git@git.acme.internal:ios/auth.git" + +SPEC CHECKSUMS: + AcmeAuth: aaaa + Alamofire: bbbb + +PODFILE CHECKSUM: cccc + +COCOAPODS: 1.15.2 +` + +const podfileLockAfter = `PODS: + - AcmeAuth (2.1.0) + - AcmeLogger (1.4.2) + - Alamofire (5.8.1) + - Firebase/Core (10.20.0) + - Firebase/CoreOnly (10.20.0) + - "GoogleUtilities/Environment (7.12.0)" + +EXTERNAL SOURCES: + AcmeAuth: + AcmeLogger: + +` + +func TestSanitizePodfileLock(t *testing.T) { + sanitized, err := sanitizePodfileLock([]byte(podfileLockBefore), nil) + + assert.NoError(t, err) + assert.Equal(t, podfileLockAfter, string(sanitized)) + assert.NotContains(t, string(sanitized), "acme.internal") +} + +func TestSanitizePodfileLockWithoutExternalSources(t *testing.T) { + sanitized, err := sanitizePodfileLock([]byte("PODS:\n - Alamofire (5.8.1)\n\nCOCOAPODS: 1.15.2\n"), nil) + + assert.NoError(t, err) + assert.Equal(t, "PODS:\n - Alamofire (5.8.1)\n\n", string(sanitized)) +} + +func TestSanitizePodfileLockInvalid(t *testing.T) { + for _, content := range []string{ + "", + "COCOAPODS: 1.15.2\n", + " - Alamofire (5.8.1)\n", + "pods:\n - Alamofire (5.8.1)\n", + "PODS:\n - Alamofire\n", + "PODS:\n - Alamofire (5.8.1)\nEXTERNAL SOURCES:\n AcmeAuth: {git: x}\n", + } { + _, err := sanitizePodfileLock([]byte(content), nil) + assert.ErrorIs(t, err, util.ErrInvalidFormat, content) + } +} diff --git a/internal/sanitize/pm/godep/gopkg_lock.go b/internal/sanitize/pm/godep/gopkg_lock.go new file mode 100644 index 00000000..8e4ce54a --- /dev/null +++ b/internal/sanitize/pm/godep/gopkg_lock.go @@ -0,0 +1,39 @@ +package godep + +import ( + "strings" + + "github.com/debricked/cli/internal/sanitize/pm/util" + "github.com/pelletier/go-toml/v2" +) + +type gopkgLock struct { + Projects []struct { + Name string `toml:"name"` + Version string `toml:"version"` + } `toml:"projects"` +} + +// sanitizeGopkgLock keeps the name and version of each project. A name can contain a private +// host, but it is what identifies the dependency, so it is kept. Branches, revisions, sources, +// import paths and [solve-meta], which lists the project's own imports, are removed. +func sanitizeGopkgLock(content []byte, _ *util.FileContext) ([]byte, error) { + var lock gopkgLock + if err := toml.Unmarshal(content, &lock); err != nil || len(lock.Projects) == 0 { + return nil, util.ErrInvalidFormat + } + + blocks := make([]string, 0, len(lock.Projects)) + for _, project := range lock.Projects { + if project.Name == "" { + return nil, util.ErrInvalidFormat + } + block := "[[projects]]\n name = " + util.QuoteTOML(project.Name) + "\n" + if project.Version != "" { + block += " version = " + util.QuoteTOML(project.Version) + "\n" + } + blocks = append(blocks, block) + } + + return []byte(strings.Join(blocks, "\n")), nil +} diff --git a/internal/sanitize/pm/godep/gopkg_lock_test.go b/internal/sanitize/pm/godep/gopkg_lock_test.go new file mode 100644 index 00000000..be392162 --- /dev/null +++ b/internal/sanitize/pm/godep/gopkg_lock_test.go @@ -0,0 +1,62 @@ +package godep + +import ( + "testing" + + "github.com/debricked/cli/internal/sanitize/pm/util" + "github.com/stretchr/testify/assert" +) + +const gopkgLockBefore = `# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. + +[[projects]] + branch = "feature/PROJ-123" + digest = "1:aaaa" + name = "git.acme.internal/platform/authclient" + packages = ["internal/secrets", "."] + pruneopts = "UT" + revision = "9f3c1ab" + source = "ssh://git@git.acme.internal/platform/authclient.git" + +[[projects]] + digest = "1:bbbb" + name = "github.com/pkg/errors" + packages = ["."] + pruneopts = "UT" + revision = "cccc" + version = "v0.9.1" + +[solve-meta] + analyzer-name = "dep" + analyzer-version = 1 + input-imports = ["git.acme.internal/platform/authclient/internal/secrets"] + solver-name = "gps-cdcl" + solver-version = 1 +` + +const gopkgLockAfter = `[[projects]] + name = "git.acme.internal/platform/authclient" + +[[projects]] + name = "github.com/pkg/errors" + version = "v0.9.1" +` + +func TestSanitizeGopkgLock(t *testing.T) { + sanitized, err := sanitizeGopkgLock([]byte(gopkgLockBefore), nil) + + assert.NoError(t, err) + assert.Equal(t, gopkgLockAfter, string(sanitized)) +} + +func TestSanitizeGopkgLockInvalid(t *testing.T) { + for _, content := range []string{ + "", + "[solve-meta]\n solver-name = \"gps-cdcl\"\n", + "[[projects]\n", + "[[projects]]\n version = \"v1.0.0\"\n", + } { + _, err := sanitizeGopkgLock([]byte(content), nil) + assert.ErrorIs(t, err, util.ErrInvalidFormat, content) + } +} diff --git a/internal/sanitize/pm/godep/pm.go b/internal/sanitize/pm/godep/pm.go new file mode 100644 index 00000000..b0d767c6 --- /dev/null +++ b/internal/sanitize/pm/godep/pm.go @@ -0,0 +1,29 @@ +package godep + +import "github.com/debricked/cli/internal/sanitize/pm/util" + +const Name = "godep" + +type Pm struct { + name string +} + +func NewPm() Pm { + return Pm{ + name: Name, + } +} + +func (pm Pm) Name() string { + return pm.name +} + +func (Pm) LockFiles() map[string]util.FileSanitizer { + return map[string]util.FileSanitizer{ + "Gopkg.lock": sanitizeGopkgLock, + } +} + +func (Pm) Manifests() map[string]util.FileSanitizer { + return map[string]util.FileSanitizer{} +} diff --git a/internal/sanitize/pm/godep/pm_test.go b/internal/sanitize/pm/godep/pm_test.go new file mode 100644 index 00000000..f7800683 --- /dev/null +++ b/internal/sanitize/pm/godep/pm_test.go @@ -0,0 +1,16 @@ +package godep + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestNewPm(t *testing.T) { + pm := NewPm() + + assert.Equal(t, Name, pm.Name()) + assert.Len(t, pm.LockFiles(), 1) + assert.Contains(t, pm.LockFiles(), "Gopkg.lock") + assert.Empty(t, pm.Manifests()) +} diff --git a/internal/sanitize/pm/mix/mix_lock.go b/internal/sanitize/pm/mix/mix_lock.go new file mode 100644 index 00000000..01765c87 --- /dev/null +++ b/internal/sanitize/pm/mix/mix_lock.go @@ -0,0 +1,66 @@ +package mix + +import ( + "regexp" + "strings" + + "github.com/debricked/cli/internal/sanitize/pm/util" +) + +const ( + mixOpen = "%{" + mixClose = "}" +) + +var ( + mixEntryRegex = regexp.MustCompile(`^ "[^"]+": \{`) + mixHexRegex = regexp.MustCompile(`^ ("[^"]+"): \{:hex, (:\w+), ("[^"\s]+")[,}]`) + mixGitRegex = regexp.MustCompile(`^ ("[^"]+"): \{:git[,}]`) +) + +// sanitizeMixLock writes one line per package, as the backend reads them with a regex: name, +// product and version for Hex packages, and the name alone for git packages, which have no +// version. Git URLs, commits, branches, hashes and repository names such as hexpm:acme_org are +// removed. Entries of other kinds are removed too, because the backend doesn't read them. +func sanitizeMixLock(content []byte, _ *util.FileContext) ([]byte, error) { + var lines []string + for _, line := range util.SplitLines(content) { + if strings.TrimSpace(line) != "" { + lines = append(lines, line) + } + } + if len(lines) < 2 || lines[0] != mixOpen || lines[len(lines)-1] != mixClose { + return nil, util.ErrInvalidFormat + } + + var output strings.Builder + output.WriteString(mixOpen + "\n") + for _, line := range lines[1 : len(lines)-1] { + entry, err := sanitizeMixEntry(line) + if err != nil { + return nil, err + } + output.WriteString(entry) + } + output.WriteString(mixClose + "\n") + + return []byte(output.String()), nil +} + +// sanitizeMixEntry returns the sanitized line for one entry, or "" for an entry of another kind. +func sanitizeMixEntry(line string) (string, error) { + if !mixEntryRegex.MatchString(line) { + return "", util.ErrInvalidFormat + } + if hex := mixHexRegex.FindStringSubmatch(line); hex != nil { + return " " + hex[1] + ": {:hex, " + hex[2] + ", " + hex[3] + "},\n", nil + } + if strings.Contains(line, "{:hex") { + return "", util.ErrInvalidFormat + } + if git := mixGitRegex.FindStringSubmatch(line); git != nil { + return " " + git[1] + ": {:git},\n", nil + } + + return "", nil +} diff --git a/internal/sanitize/pm/mix/mix_lock_test.go b/internal/sanitize/pm/mix/mix_lock_test.go new file mode 100644 index 00000000..b8ccac5b --- /dev/null +++ b/internal/sanitize/pm/mix/mix_lock_test.go @@ -0,0 +1,55 @@ +package mix + +import ( + "testing" + + "github.com/debricked/cli/internal/sanitize/pm/util" + "github.com/stretchr/testify/assert" +) + +const mixLockBefore = `%{ + "acme_auth": {:git, "git@git.acme.internal:platform/acme_auth.git", "9f3c1ab", [branch: "feature/PROJ-123"]}, + "acme_logger": {:hex, :acme_logger, "1.4.2", "aaaa", [:mix], [], "hexpm:acme_org", "bbbb"}, + "plug": {:hex, :plug, "1.15.3", "cccc", [:mix], [{:plug_crypto, "~> 2.0", [hex: :plug_crypto, repo: "hexpm", optional: false]}], "hexpm", "dddd"}, + "plug_crypto": {:hex, :plug_crypto, "2.0.0", "eeee", [:mix], [], "hexpm", "ffff"}, +} +` + +const mixLockAfter = `%{ + "acme_auth": {:git}, + "acme_logger": {:hex, :acme_logger, "1.4.2"}, + "plug": {:hex, :plug, "1.15.3"}, + "plug_crypto": {:hex, :plug_crypto, "2.0.0"}, +} +` + +func TestSanitizeMixLock(t *testing.T) { + sanitized, err := sanitizeMixLock([]byte(mixLockBefore), nil) + + assert.NoError(t, err) + assert.Equal(t, mixLockAfter, string(sanitized)) + assert.NotContains(t, string(sanitized), "acme_org") +} + +func TestSanitizeMixLockDropsEntriesOfOtherKinds(t *testing.T) { + before := "%{\n \"local\": {:path, \"../local\"},\n \"plug\": {:hex, :plug, \"1.15.3\"},\n}\n" + + sanitized, err := sanitizeMixLock([]byte(before), nil) + + assert.NoError(t, err) + assert.Equal(t, "%{\n \"plug\": {:hex, :plug, \"1.15.3\"},\n}\n", string(sanitized)) +} + +func TestSanitizeMixLockInvalid(t *testing.T) { + for _, content := range []string{ + "", + "%{\n", + "{\n}\n", + "%{\n\"plug\": {:hex, :plug, \"1.15.3\"},\n}\n", + "%{\n \"plug\": {:hex, \"1.15.3\"},\n}\n", + "%{\n plug: 1.15.3\n}\n", + } { + _, err := sanitizeMixLock([]byte(content), nil) + assert.ErrorIs(t, err, util.ErrInvalidFormat, content) + } +} diff --git a/internal/sanitize/pm/mix/pm.go b/internal/sanitize/pm/mix/pm.go new file mode 100644 index 00000000..ef84b591 --- /dev/null +++ b/internal/sanitize/pm/mix/pm.go @@ -0,0 +1,29 @@ +package mix + +import "github.com/debricked/cli/internal/sanitize/pm/util" + +const Name = "mix" + +type Pm struct { + name string +} + +func NewPm() Pm { + return Pm{ + name: Name, + } +} + +func (pm Pm) Name() string { + return pm.name +} + +func (Pm) LockFiles() map[string]util.FileSanitizer { + return map[string]util.FileSanitizer{ + "mix.lock": sanitizeMixLock, + } +} + +func (Pm) Manifests() map[string]util.FileSanitizer { + return map[string]util.FileSanitizer{} +} diff --git a/internal/sanitize/pm/mix/pm_test.go b/internal/sanitize/pm/mix/pm_test.go new file mode 100644 index 00000000..9a8924cb --- /dev/null +++ b/internal/sanitize/pm/mix/pm_test.go @@ -0,0 +1,16 @@ +package mix + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestNewPm(t *testing.T) { + pm := NewPm() + + assert.Equal(t, Name, pm.Name()) + assert.Len(t, pm.LockFiles(), 1) + assert.Contains(t, pm.LockFiles(), "mix.lock") + assert.Empty(t, pm.Manifests()) +} diff --git a/internal/sanitize/pm/pm.go b/internal/sanitize/pm/pm.go index eef6a4ef..ac708bdf 100644 --- a/internal/sanitize/pm/pm.go +++ b/internal/sanitize/pm/pm.go @@ -3,11 +3,19 @@ package pm import ( + "github.com/debricked/cli/internal/sanitize/pm/bazel" + "github.com/debricked/cli/internal/sanitize/pm/bundler" + "github.com/debricked/cli/internal/sanitize/pm/cargo" + "github.com/debricked/cli/internal/sanitize/pm/cocoapods" "github.com/debricked/cli/internal/sanitize/pm/composer" + "github.com/debricked/cli/internal/sanitize/pm/godep" + "github.com/debricked/cli/internal/sanitize/pm/mix" "github.com/debricked/cli/internal/sanitize/pm/npm" "github.com/debricked/cli/internal/sanitize/pm/nuget" "github.com/debricked/cli/internal/sanitize/pm/pnpm" + "github.com/debricked/cli/internal/sanitize/pm/pub" "github.com/debricked/cli/internal/sanitize/pm/python" + "github.com/debricked/cli/internal/sanitize/pm/swift" "github.com/debricked/cli/internal/sanitize/pm/util" "github.com/debricked/cli/internal/sanitize/pm/yarn" ) @@ -28,5 +36,13 @@ func Pms() []IPm { composer.NewPm(), nuget.NewPm(), python.NewPm(), + cargo.NewPm(), + bundler.NewPm(), + cocoapods.NewPm(), + swift.NewPm(), + pub.NewPm(), + mix.NewPm(), + godep.NewPm(), + bazel.NewPm(), } } diff --git a/internal/sanitize/pm/pm_test.go b/internal/sanitize/pm/pm_test.go index d8ae3abe..6f885fb3 100644 --- a/internal/sanitize/pm/pm_test.go +++ b/internal/sanitize/pm/pm_test.go @@ -12,7 +12,7 @@ func TestPms(t *testing.T) { names = append(names, pm.Name()) } - assert.Equal(t, []string{"npm", "yarn", "pnpm", "composer", "nuget", "python"}, names) + assert.Equal(t, []string{"npm", "yarn", "pnpm", "composer", "nuget", "python", "cargo", "bundler", "cocoapods", "swift", "pub", "mix", "godep", "bazel"}, names) } func TestEachFileNameIsHandledByOnePm(t *testing.T) { diff --git a/internal/sanitize/pm/pnpm/pnpm_lock.go b/internal/sanitize/pm/pnpm/pnpm_lock.go index 9e902eb1..e64265fb 100644 --- a/internal/sanitize/pm/pnpm/pnpm_lock.go +++ b/internal/sanitize/pm/pnpm/pnpm_lock.go @@ -37,7 +37,7 @@ type pnpmLockSanitizer struct { } func sanitizePnpmLock(content []byte, context *util.FileContext) ([]byte, error) { - root, err := parsePnpmLock(content) + root, err := util.ParseYAMLMapping(content) if err != nil { return nil, err } @@ -46,7 +46,7 @@ func sanitizePnpmLock(content []byte, context *util.FileContext) ([]byte, error) // Package keys get their placeholders first, so references to them can be replaced wherever // they appear. - if packages := yamlValue(root, "packages"); packages != nil && packages.Kind == yaml.MappingNode { + if packages := util.YAMLValue(root, "packages"); packages != nil && packages.Kind == yaml.MappingNode { if err = sanitizer.registerKeys(packages); err != nil { return nil, util.ErrInvalidFormat } @@ -60,24 +60,11 @@ func sanitizePnpmLock(content []byte, context *util.FileContext) ([]byte, error) return util.EncodeYAML(sanitized), nil } -func parsePnpmLock(content []byte) (*yaml.Node, error) { - var document yaml.Node - if err := yaml.Unmarshal(content, &document); err != nil || len(document.Content) != 1 { - return nil, util.ErrInvalidFormat - } - root := document.Content[0] - if root.Kind != yaml.MappingNode { - return nil, util.ErrInvalidFormat - } - - return root, nil -} - // sanitizeRoot fails if no known section is left, because then the file isn't a pnpm lock file. func (s *pnpmLockSanitizer) sanitizeRoot(root *yaml.Node) (*util.OrderedObject, error) { sanitized := util.NewOrderedObject() var err error - forEachYAMLPair(root, func(key string, value *yaml.Node) { + util.ForEachYAMLPair(root, func(key string, value *yaml.Node) { if err != nil { return } @@ -142,7 +129,7 @@ func pnpmLockfileVersion(value *yaml.Node) any { } func (s *pnpmLockSanitizer) sanitizeImporters(importers *yaml.Node) (*util.OrderedObject, error) { - if isYAMLNull(importers) { + if util.IsYAMLNull(importers) { return nil, errEmptySection } if importers.Kind != yaml.MappingNode { @@ -151,7 +138,7 @@ func (s *pnpmLockSanitizer) sanitizeImporters(importers *yaml.Node) (*util.Order sanitized := util.NewOrderedObject() count := 0 - forEachYAMLPair(importers, func(path string, importer *yaml.Node) { + util.ForEachYAMLPair(importers, func(path string, importer *yaml.Node) { key := path if path != pnpmRootImporterKey { count++ @@ -167,7 +154,7 @@ func (s *pnpmLockSanitizer) sanitizeImporters(importers *yaml.Node) (*util.Order // sanitizeImporter keeps names only: the values often hold internal URLs and aren't read. func sanitizeImporter(importer *yaml.Node) *util.OrderedObject { sanitized := util.NewOrderedObject() - forEachYAMLPair(importer, func(listName string, list *yaml.Node) { + util.ForEachYAMLPair(importer, func(listName string, list *yaml.Node) { if !util.IsPackageJSONDependencyList(listName) { return } @@ -179,7 +166,7 @@ func sanitizeImporter(importer *yaml.Node) *util.OrderedObject { func sanitizeNames(list *yaml.Node) *util.OrderedObject { names := util.NewOrderedObject() - forEachYAMLPair(list, func(name string, _ *yaml.Node) { + util.ForEachYAMLPair(list, func(name string, _ *yaml.Node) { names.Set(name, util.NewOrderedObject()) }) @@ -202,7 +189,7 @@ var ( ) func (s *pnpmLockSanitizer) sanitizeEntries(entries *yaml.Node, allowed pnpmAllowList) (*util.OrderedObject, error) { - if isYAMLNull(entries) { + if util.IsYAMLNull(entries) { return nil, errEmptySection } if entries.Kind != yaml.MappingNode { @@ -211,7 +198,7 @@ func (s *pnpmLockSanitizer) sanitizeEntries(entries *yaml.Node, allowed pnpmAllo sanitized := util.NewOrderedObject() var err error - forEachYAMLPair(entries, func(key string, entry *yaml.Node) { + util.ForEachYAMLPair(entries, func(key string, entry *yaml.Node) { if err != nil { return } @@ -238,12 +225,12 @@ func (s *pnpmLockSanitizer) sanitizeEntries(entries *yaml.Node, allowed pnpmAllo func (s *pnpmLockSanitizer) sanitizeEntry(entry *yaml.Node, allowed pnpmAllowList) (*util.OrderedObject, error) { sanitized := util.NewOrderedObject() var err error - forEachYAMLPair(entry, func(key string, value *yaml.Node) { + util.ForEachYAMLPair(entry, func(key string, value *yaml.Node) { if err != nil { return } switch { - case allowed.scalars[key] && value.Kind == yaml.ScalarNode && !isYAMLNull(value): + case allowed.scalars[key] && value.Kind == yaml.ScalarNode && !util.IsYAMLNull(value): if key == "version" { sanitized.Set(key, util.MaskValue(value.Value)) } else { @@ -263,8 +250,8 @@ func (s *pnpmLockSanitizer) sanitizeEntry(entry *yaml.Node, allowed pnpmAllowLis func (s *pnpmLockSanitizer) sanitizeDependencyList(list *yaml.Node) (*util.OrderedObject, error) { sanitized := util.NewOrderedObject() var err error - forEachYAMLPair(list, func(name string, value *yaml.Node) { - if err != nil || value.Kind != yaml.ScalarNode || isYAMLNull(value) { + util.ForEachYAMLPair(list, func(name string, value *yaml.Node) { + if err != nil || value.Kind != yaml.ScalarNode || util.IsYAMLNull(value) { return } var masked string @@ -278,7 +265,7 @@ func (s *pnpmLockSanitizer) sanitizeDependencyList(list *yaml.Node) (*util.Order func (s *pnpmLockSanitizer) registerKeys(packages *yaml.Node) error { var err error - forEachYAMLPair(packages, func(key string, _ *yaml.Node) { + util.ForEachYAMLPair(packages, func(key string, _ *yaml.Node) { if err == nil { _, err = s.maskKey(key) } @@ -416,29 +403,3 @@ func splitPnpmPeers(key string) (string, string) { return key, "" } - -func forEachYAMLPair(mapping *yaml.Node, visit func(key string, value *yaml.Node)) { - if mapping.Kind != yaml.MappingNode { - return - } - for index := 0; index+1 < len(mapping.Content); index += 2 { - if mapping.Content[index].Kind == yaml.ScalarNode { - visit(mapping.Content[index].Value, mapping.Content[index+1]) - } - } -} - -func yamlValue(mapping *yaml.Node, key string) *yaml.Node { - var found *yaml.Node - forEachYAMLPair(mapping, func(candidate string, value *yaml.Node) { - if candidate == key { - found = value - } - }) - - return found -} - -func isYAMLNull(node *yaml.Node) bool { - return node.Kind == yaml.ScalarNode && node.Tag == "!!null" -} diff --git a/internal/sanitize/pm/pub/pm.go b/internal/sanitize/pm/pub/pm.go new file mode 100644 index 00000000..ff9eee41 --- /dev/null +++ b/internal/sanitize/pm/pub/pm.go @@ -0,0 +1,31 @@ +package pub + +import "github.com/debricked/cli/internal/sanitize/pm/util" + +const Name = "pub" + +type Pm struct { + name string +} + +func NewPm() Pm { + return Pm{ + name: Name, + } +} + +func (pm Pm) Name() string { + return pm.name +} + +func (Pm) LockFiles() map[string]util.FileSanitizer { + return map[string]util.FileSanitizer{ + "pubspec.lock": sanitizePubspecLock, + } +} + +func (Pm) Manifests() map[string]util.FileSanitizer { + return map[string]util.FileSanitizer{ + "pubspec.yaml": sanitizePubspecYAML, + } +} diff --git a/internal/sanitize/pm/pub/pm_test.go b/internal/sanitize/pm/pub/pm_test.go new file mode 100644 index 00000000..76d32d33 --- /dev/null +++ b/internal/sanitize/pm/pub/pm_test.go @@ -0,0 +1,17 @@ +package pub + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestNewPm(t *testing.T) { + pm := NewPm() + + assert.Equal(t, Name, pm.Name()) + assert.Len(t, pm.LockFiles(), 1) + assert.Contains(t, pm.LockFiles(), "pubspec.lock") + assert.Len(t, pm.Manifests(), 1) + assert.Contains(t, pm.Manifests(), "pubspec.yaml") +} diff --git a/internal/sanitize/pm/pub/pubspec_lock.go b/internal/sanitize/pm/pub/pubspec_lock.go new file mode 100644 index 00000000..dc76ca40 --- /dev/null +++ b/internal/sanitize/pm/pub/pubspec_lock.go @@ -0,0 +1,49 @@ +package pub + +import ( + "github.com/debricked/cli/internal/sanitize/pm/util" + "gopkg.in/yaml.v3" +) + +// pubspecLockFields are the fields of a package that the backend reads. description and source +// are removed: they hold git URLs, local paths and private hosts. +var pubspecLockFields = []string{"dependency", "version"} + +// sanitizePubspecLock keeps the name, dependency type and version of each package. +func sanitizePubspecLock(content []byte, _ *util.FileContext) ([]byte, error) { + root, err := util.ParseYAMLMapping(content) + if err != nil { + return nil, err + } + packages := util.YAMLValue(root, "packages") + if packages == nil || packages.Kind != yaml.MappingNode { + return nil, util.ErrInvalidFormat + } + + sanitizedPackages := util.NewOrderedObject() + util.ForEachYAMLPair(packages, func(name string, entry *yaml.Node) { + if err != nil { + return + } + if entry.Kind != yaml.MappingNode { + err = util.ErrInvalidFormat + + return + } + sanitizedEntry := util.NewOrderedObject() + for _, field := range pubspecLockFields { + if value, isString := util.YAMLString(util.YAMLValue(entry, field)); isString { + sanitizedEntry.Set(field, value) + } + } + sanitizedPackages.Set(name, sanitizedEntry) + }) + if err != nil { + return nil, err + } + + sanitized := util.NewOrderedObject() + sanitized.Set("packages", sanitizedPackages) + + return util.EncodeYAML(sanitized), nil +} diff --git a/internal/sanitize/pm/pub/pubspec_test.go b/internal/sanitize/pm/pub/pubspec_test.go new file mode 100644 index 00000000..52eb685b --- /dev/null +++ b/internal/sanitize/pm/pub/pubspec_test.go @@ -0,0 +1,184 @@ +package pub + +import ( + "testing" + + "github.com/debricked/cli/internal/sanitize/pm/util" + "github.com/stretchr/testify/assert" +) + +const pubspecLockBefore = `# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + acme_auth: + dependency: "direct main" + description: + path: "." + ref: "feature/PROJ-123" + resolved-ref: "9f3c1ab" + url: "git@git.acme.internal:mobile/acme_auth.git" + source: git + version: "2.1.0" + acme_utils: + dependency: "direct main" + description: + path: "../acme_utils" + relative: true + source: path + version: "1.0.0" + async: + dependency: transitive + description: + name: async + sha256: aaaa + url: "https://pub.dev" + source: hosted + version: "2.11.0" + http: + dependency: "direct overridden" + description: + name: http + sha256: bbbb + url: "https://pub.acme.internal" + source: hosted + version: "1.2.0" + lints: + dependency: "direct dev" + description: + name: lints + sha256: cccc + url: "https://pub.dev" + source: hosted + version: "3.0.0" + mockito: + dependency: "direct overridden" + description: + name: mockito + sha256: dddd + url: "https://pub.dev" + source: hosted + version: "5.4.4" +sdks: + dart: ">=3.2.0 <4.0.0" +` + +const pubspecLockAfter = `packages: + acme_auth: + dependency: 'direct main' + version: 2.1.0 + acme_utils: + dependency: 'direct main' + version: 1.0.0 + async: + dependency: transitive + version: 2.11.0 + http: + dependency: 'direct overridden' + version: 1.2.0 + lints: + dependency: 'direct dev' + version: 3.0.0 + mockito: + dependency: 'direct overridden' + version: 5.4.4 +` + +const pubspecYAMLBefore = `name: payments_portal +description: Internal card payments portal +publish_to: "https://pub.acme.internal" +version: 3.4.1 +environment: + sdk: ">=3.2.0 <4.0.0" +dependencies: + flutter: + sdk: flutter + acme_auth: + git: + url: git@git.acme.internal:mobile/acme_auth.git + ref: feature/PROJ-123 + acme_utils: + path: ../acme_utils + acme_hosted: + hosted: https://pub.acme.internal + version: ^2.0.0 + http: ^1.0.0 + plain: +dev_dependencies: + lints: ^3.0.0 + mockito: ^5.4.0 +dependency_overrides: + http: 1.2.0 + mockito: 5.4.4 +flutter: + assets: + - assets/secret-config.json +` + +// Constraints such as ^1.0.0 are quoted, which YAML reads as the same string. +const pubspecYAMLAfter = `dependencies: + flutter: any + acme_auth: any + acme_utils: any + acme_hosted: '^2.0.0' + http: '^1.0.0' + plain: any +dev_dependencies: + lints: '^3.0.0' + mockito: '^5.4.0' +dependency_overrides: + http: 1.2.0 + mockito: 5.4.4 +` + +func TestSanitizePubspecLock(t *testing.T) { + sanitized, err := sanitizePubspecLock([]byte(pubspecLockBefore), nil) + + assert.NoError(t, err) + assert.Equal(t, pubspecLockAfter, string(sanitized)) +} + +func TestSanitizePubspecLockWithNoPackages(t *testing.T) { + sanitized, err := sanitizePubspecLock([]byte("packages: {}\nsdks:\n dart: \">=3.2.0 <4.0.0\"\n"), nil) + + assert.NoError(t, err) + assert.Equal(t, "packages: {}\n", string(sanitized)) +} + +func TestSanitizePubspecLockInvalid(t *testing.T) { + for _, content := range []string{ + "", + "just text", + "sdks:\n dart: any\n", + "packages:\n - async\n", + "packages:\n async: 2.11.0\n", + } { + _, err := sanitizePubspecLock([]byte(content), nil) + assert.ErrorIs(t, err, util.ErrInvalidFormat, content) + } +} + +func TestSanitizePubspecYAML(t *testing.T) { + sanitized, err := sanitizePubspecYAML([]byte(pubspecYAMLBefore), nil) + + assert.NoError(t, err) + assert.Equal(t, pubspecYAMLAfter, string(sanitized)) + assert.NotContains(t, string(sanitized), "acme.internal") +} + +func TestSanitizePubspecYAMLWithNoDependencies(t *testing.T) { + sanitized, err := sanitizePubspecYAML([]byte("name: payments_portal\ndev_dependencies:\n"), nil) + + assert.NoError(t, err) + assert.Equal(t, "dependencies: {}\n", string(sanitized)) +} + +func TestSanitizePubspecYAMLInvalid(t *testing.T) { + for _, content := range []string{ + "", + "- a list", + "dependencies:\n - http\n", + } { + _, err := sanitizePubspecYAML([]byte(content), nil) + assert.ErrorIs(t, err, util.ErrInvalidFormat, content) + } +} diff --git a/internal/sanitize/pm/pub/pubspec_yaml.go b/internal/sanitize/pm/pub/pubspec_yaml.go new file mode 100644 index 00000000..d1e1281a --- /dev/null +++ b/internal/sanitize/pm/pub/pubspec_yaml.go @@ -0,0 +1,54 @@ +package pub + +import ( + "github.com/debricked/cli/internal/sanitize/pm/util" + "gopkg.in/yaml.v3" +) + +// anyVersion replaces a dependency whose source is a git repository, a path or a private host. +const anyVersion = "any" + +// pubspecDependencyLists decide each package's scope. The lock file alone isn't enough: a dev +// dependency that is also overridden is "direct overridden" there, and would count as production. +var pubspecDependencyLists = []string{"dependencies", "dev_dependencies", "dependency_overrides"} + +// sanitizePubspecYAML keeps only the dependency lists. A plain version constraint is kept, a +// table keeps only its version, and anything else becomes "any". +func sanitizePubspecYAML(content []byte, _ *util.FileContext) ([]byte, error) { + root, err := util.ParseYAMLMapping(content) + if err != nil { + return nil, err + } + + sanitized := util.NewOrderedObject() + for _, listName := range pubspecDependencyLists { + list := util.YAMLValue(root, listName) + if list == nil || util.IsYAMLNull(list) { + continue + } + if list.Kind != yaml.MappingNode { + return nil, util.ErrInvalidFormat + } + sanitizedList := util.NewOrderedObject() + util.ForEachYAMLPair(list, func(name string, value *yaml.Node) { + sanitizedList.Set(name, versionConstraint(value)) + }) + sanitized.Set(listName, sanitizedList) + } + if len(sanitized.Keys) == 0 { + sanitized.Set("dependencies", util.NewOrderedObject()) + } + + return util.EncodeYAML(sanitized), nil +} + +func versionConstraint(value *yaml.Node) string { + if value.Kind == yaml.MappingNode { + value = util.YAMLValue(value, "version") + } + if version, isString := util.YAMLString(value); isString && util.IsPlainVersion(version) { + return version + } + + return anyVersion +} diff --git a/internal/sanitize/pm/swift/package_resolved.go b/internal/sanitize/pm/swift/package_resolved.go new file mode 100644 index 00000000..41aab0cb --- /dev/null +++ b/internal/sanitize/pm/swift/package_resolved.go @@ -0,0 +1,83 @@ +package swift + +import ( + "strings" + + "github.com/debricked/cli/internal/sanitize/pm/util" +) + +// maskedLocationPrefix replaces the host and path of a location. The backend only reads the +// last part of a location, and only when a pin has no identity. +const maskedLocationPrefix = "https://redacted.invalid/" + +// sanitizePackageResolved keeps the name and version of each pin. The name is the identity, or +// the last part of the location if there is no identity. The version is state.version, or +// state.revision if there is no version. Branches, locations and hashes are removed. +// +// The backend only reads top-level pins, so a version 1 file, which nests them under "object", +// fails here rather than being uploaded and giving no packages. +func sanitizePackageResolved(content []byte, _ *util.FileContext) ([]byte, error) { + resolved, err := util.ParseJSONObject(content) + if err != nil { + return nil, util.ErrInvalidFormat + } + pins, isList := resolved.Values["pins"].([]any) + if !isList { + return nil, util.ErrInvalidFormat + } + + sanitizedPins := make([]any, 0, len(pins)) + for _, item := range pins { + pin, isObject := item.(*util.OrderedObject) + if !isObject { + return nil, util.ErrInvalidFormat + } + sanitizedPin, err := sanitizePin(pin) + if err != nil { + return nil, err + } + sanitizedPins = append(sanitizedPins, sanitizedPin) + } + + sanitized := util.NewOrderedObject() + sanitized.Set("pins", sanitizedPins) + + return util.EncodeJSON(sanitized) +} + +func sanitizePin(pin *util.OrderedObject) (*util.OrderedObject, error) { + sanitized := util.NewOrderedObject() + if identity := stringValue(pin, "identity"); identity != "" { + sanitized.Set("identity", identity) + } else if name := lastPathPart(stringValue(pin, "location")); name != "" { + sanitized.Set("location", maskedLocationPrefix+name) + } else { + return nil, util.ErrInvalidFormat + } + + sanitizedState := util.NewOrderedObject() + if state, isObject := pin.Values["state"].(*util.OrderedObject); isObject { + if version := stringValue(state, "version"); version != "" { + sanitizedState.Set("version", version) + } else if revision := stringValue(state, "revision"); revision != "" { + sanitizedState.Set("revision", revision) + } + } + sanitized.Set("state", sanitizedState) + + return sanitized, nil +} + +// stringValue returns "" for a missing value or one that isn't a string, such as a null version. +func stringValue(object *util.OrderedObject, key string) string { + value, _ := object.Values[key].(string) + + return value +} + +// lastPathPart works for URLs and for scp-style git locations such as git@host:org/repo.git. +func lastPathPart(location string) string { + location = strings.TrimRight(location, "/") + + return location[strings.LastIndexAny(location, "/:")+1:] +} diff --git a/internal/sanitize/pm/swift/package_resolved_test.go b/internal/sanitize/pm/swift/package_resolved_test.go new file mode 100644 index 00000000..97db1c7f --- /dev/null +++ b/internal/sanitize/pm/swift/package_resolved_test.go @@ -0,0 +1,104 @@ +package swift + +import ( + "testing" + + "github.com/debricked/cli/internal/sanitize/pm/util" + "github.com/stretchr/testify/assert" +) + +const packageResolvedBefore = `{ + "originHash": "aaaa", + "pins": [ + { + "identity": "acme-auth", + "kind": "remoteSourceControl", + "location": "git@git.acme.internal:ios/acme-auth.git", + "state": { + "branch": "feature/PROJ-123-new-login", + "revision": "9f3c1ab" + } + }, + { + "identity": "swift-log", + "kind": "remoteSourceControl", + "location": "https://github.com/apple/swift-log.git", + "state": { + "revision": "bbbb", + "version": "1.5.4" + } + } + ], + "version": 2 +}` + +const packageResolvedAfter = `{ + "pins": [ + { + "identity": "acme-auth", + "state": { + "revision": "9f3c1ab" + } + }, + { + "identity": "swift-log", + "state": { + "version": "1.5.4" + } + } + ] +} +` + +func TestSanitizePackageResolved(t *testing.T) { + sanitized, err := sanitizePackageResolved([]byte(packageResolvedBefore), nil) + + assert.NoError(t, err) + assert.Equal(t, packageResolvedAfter, string(sanitized)) +} + +func TestSanitizePackageResolvedWithoutIdentityKeepsOnlyTheLastPartOfTheLocation(t *testing.T) { + before := `{"pins": [ + {"location": "git@git.acme.internal:ios/acme-auth.git", "state": {"branch": "main", "version": null, "revision": "9f3c1ab"}}, + {"location": "https://github.com/apple/swift-log/", "state": {}}, + {"identity": "no-state"} + ]}` + + sanitized, err := sanitizePackageResolved([]byte(before), nil) + + assert.NoError(t, err) + assert.Equal(t, `{ + "pins": [ + { + "location": "https://redacted.invalid/acme-auth.git", + "state": { + "revision": "9f3c1ab" + } + }, + { + "location": "https://redacted.invalid/swift-log", + "state": {} + }, + { + "identity": "no-state", + "state": {} + } + ] +} +`, string(sanitized)) +} + +func TestSanitizePackageResolvedInvalid(t *testing.T) { + for _, content := range []string{ + ``, + `[]`, + `{"object": {"pins": []}, "version": 1}`, + `{"pins": {}}`, + `{"pins": ["acme-auth"]}`, + `{"pins": [{"kind": "remoteSourceControl"}]}`, + `{"pins": [{"location": "/"}]}`, + } { + _, err := sanitizePackageResolved([]byte(content), nil) + assert.ErrorIs(t, err, util.ErrInvalidFormat, content) + } +} diff --git a/internal/sanitize/pm/swift/pm.go b/internal/sanitize/pm/swift/pm.go new file mode 100644 index 00000000..d0d06a52 --- /dev/null +++ b/internal/sanitize/pm/swift/pm.go @@ -0,0 +1,32 @@ +package swift + +import "github.com/debricked/cli/internal/sanitize/pm/util" + +const Name = "swift" + +type Pm struct { + name string +} + +func NewPm() Pm { + return Pm{ + name: Name, + } +} + +func (pm Pm) Name() string { + return pm.name +} + +func (Pm) LockFiles() map[string]util.FileSanitizer { + return map[string]util.FileSanitizer{ + "Package.resolved": sanitizePackageResolved, + } +} + +func (Pm) Manifests() map[string]util.FileSanitizer { + return map[string]util.FileSanitizer{ + // Package.swift is source code, so it is never copied. The backend only uses it to set + // the scope to production, which doesn't change the result. + } +} diff --git a/internal/sanitize/pm/swift/pm_test.go b/internal/sanitize/pm/swift/pm_test.go new file mode 100644 index 00000000..5e3891ca --- /dev/null +++ b/internal/sanitize/pm/swift/pm_test.go @@ -0,0 +1,16 @@ +package swift + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestNewPm(t *testing.T) { + pm := NewPm() + + assert.Equal(t, Name, pm.Name()) + assert.Len(t, pm.LockFiles(), 1) + assert.Contains(t, pm.LockFiles(), "Package.resolved") + assert.Empty(t, pm.Manifests()) +} diff --git a/internal/sanitize/pm/util/context.go b/internal/sanitize/pm/util/context.go index 2d6115aa..7fef6c64 100644 --- a/internal/sanitize/pm/util/context.go +++ b/internal/sanitize/pm/util/context.go @@ -1,6 +1,9 @@ package util -import "errors" +import ( + "errors" + "strings" +) // ErrInvalidFormat has a fixed message on purpose. Underlying parser errors can quote file // contents, and those must not reach the output. @@ -36,3 +39,8 @@ func (c *FileContext) PathPlaceholder(format, name string) string { func (c *FileContext) RecordPlaceholder(placeholder, name string) { c.scope.all.add(placeholder, name, c.path) } + +// SplitLines splits a text file into lines, with Windows line endings removed. +func SplitLines(content []byte) []string { + return strings.Split(strings.ReplaceAll(string(content), "\r\n", "\n"), "\n") +} diff --git a/internal/sanitize/pm/util/mask.go b/internal/sanitize/pm/util/mask.go index 62ff67aa..47a41b51 100644 --- a/internal/sanitize/pm/util/mask.go +++ b/internal/sanitize/pm/util/mask.go @@ -40,6 +40,12 @@ var localProtocols = []string{"file:", "link:", "portal:", "exec:"} var gitPrefixes = []string{"git+", "git://", "ssh://", "git@", "github:", "gitlab:", "bitbucket:", "gist:"} +// IsPlainVersion reports whether value is a version, a version range or a dist-tag, with nothing +// that could name a host or a path. +func IsPlainVersion(value string) bool { + return plainVersionRegex.MatchString(value) +} + // MaskValue replaces any private source in a dependency value with a placeholder that the // backend classifies the same way as the original. The function is pure, so a value gets the same // placeholder in a lock file and in its manifest. diff --git a/internal/sanitize/pm/util/toml.go b/internal/sanitize/pm/util/toml.go new file mode 100644 index 00000000..23ae8feb --- /dev/null +++ b/internal/sanitize/pm/util/toml.go @@ -0,0 +1,16 @@ +package util + +import ( + "bytes" + "encoding/json" +) + +// QuoteTOML returns value as a TOML basic string. TOML and JSON strings use the same escapes. +func QuoteTOML(value string) string { + var quoted bytes.Buffer + encoder := json.NewEncoder("ed) + encoder.SetEscapeHTML(false) + _ = encoder.Encode(value) // a string always encodes + + return string(bytes.TrimRight(quoted.Bytes(), "\n")) +} diff --git a/internal/sanitize/pm/util/yaml_nodes.go b/internal/sanitize/pm/util/yaml_nodes.go new file mode 100644 index 00000000..4b080b46 --- /dev/null +++ b/internal/sanitize/pm/util/yaml_nodes.go @@ -0,0 +1,54 @@ +package util + +import "gopkg.in/yaml.v3" + +// ParseYAMLMapping returns the top-level mapping of a YAML document with exactly one document. +func ParseYAMLMapping(content []byte) (*yaml.Node, error) { + var document yaml.Node + if err := yaml.Unmarshal(content, &document); err != nil || len(document.Content) != 1 { + return nil, ErrInvalidFormat + } + root := document.Content[0] + if root.Kind != yaml.MappingNode { + return nil, ErrInvalidFormat + } + + return root, nil +} + +// ForEachYAMLPair visits the pairs of a mapping that have a scalar key, in order. +func ForEachYAMLPair(mapping *yaml.Node, visit func(key string, value *yaml.Node)) { + if mapping.Kind != yaml.MappingNode { + return + } + for index := 0; index+1 < len(mapping.Content); index += 2 { + if mapping.Content[index].Kind == yaml.ScalarNode { + visit(mapping.Content[index].Value, mapping.Content[index+1]) + } + } +} + +// YAMLValue returns the value of the last pair with the given key, or nil. +func YAMLValue(mapping *yaml.Node, key string) *yaml.Node { + var found *yaml.Node + ForEachYAMLPair(mapping, func(candidate string, value *yaml.Node) { + if candidate == key { + found = value + } + }) + + return found +} + +func IsYAMLNull(node *yaml.Node) bool { + return node.Kind == yaml.ScalarNode && node.Tag == "!!null" +} + +// YAMLString returns the value of a non-null scalar. +func YAMLString(node *yaml.Node) (string, bool) { + if node == nil || node.Kind != yaml.ScalarNode || IsYAMLNull(node) { + return "", false + } + + return node.Value, true +} diff --git a/internal/sanitize/sanitize.go b/internal/sanitize/sanitize.go index 00498a1b..5e7544c5 100644 --- a/internal/sanitize/sanitize.go +++ b/internal/sanitize/sanitize.go @@ -43,6 +43,22 @@ func sanitizersByFileName(pms []pm.IPm) (map[string]util.FileSanitizer, map[stri return lockFiles, manifests } +// sanitizerFor finds the sanitizer for a file by its name. A name can also be a pattern, such as +// "*_install.json", for file types whose names vary. +func sanitizerFor(sanitizers map[string]util.FileSanitizer, path string) util.FileSanitizer { + name := filepath.Base(path) + if sanitizer, found := sanitizers[name]; found { + return sanitizer + } + for pattern, sanitizer := range sanitizers { + if matched, _ := filepath.Match(pattern, name); matched { + return sanitizer + } + } + + return nil +} + type Options struct { RootPath string Exclusions []string @@ -156,14 +172,14 @@ func (r *run) processGroup(group file.Group) { sanitizedLockFiles := []string{} for _, lockFile := range group.LockFiles { - if output := r.processFile(lockFile, lockFileSanitizers[filepath.Base(lockFile)], scope); output != "" { + if output := r.processFile(lockFile, sanitizerFor(lockFileSanitizers, lockFile), scope); output != "" { sanitizedLockFiles = append(sanitizedLockFiles, output) } } sanitizedManifest := "" if group.HasFile() { - sanitizer := manifestSanitizers[filepath.Base(group.ManifestFile)] + sanitizer := sanitizerFor(manifestSanitizers, group.ManifestFile) if sanitizer != nil && scope == nil { r.skip(group.ManifestFile, reasonNoLockFile) } else { @@ -179,7 +195,7 @@ func (r *run) processGroup(group file.Group) { // newScopeIfHandled returns nil for a group with no lock file that sanitize can handle. func (r *run) newScopeIfHandled(group file.Group) *util.ProjectScope { for _, lockFile := range group.LockFiles { - if lockFileSanitizers[filepath.Base(lockFile)] != nil { + if sanitizerFor(lockFileSanitizers, lockFile) != nil { r.projectCount++ return util.NewProjectScope(&r.placeholders, r.projectCount) diff --git a/internal/sanitize/sanitize_test.go b/internal/sanitize/sanitize_test.go index 07152e8e..8074fb3e 100644 --- a/internal/sanitize/sanitize_test.go +++ b/internal/sanitize/sanitize_test.go @@ -104,7 +104,7 @@ func TestSanitizeSkipsAndReportsUnhandledFiles(t *testing.T) { fingerprints := writeFixture(t, root, "debricked.fingerprints.txt", "s3cret") callGraph := writeFixture(t, root, "debricked-call-graph.java", "s3cret") pom := writeFixture(t, root, "pom.xml", "") - cargo := writeFixture(t, root, "Cargo.lock", "s3cret") + unknownLock := writeFixture(t, root, "unknown-format.lock", "s3cret") result := sanitizeGroups( t, @@ -112,14 +112,14 @@ func TestSanitizeSkipsAndReportsUnhandledFiles(t *testing.T) { file.NewGroup("", nil, []string{fingerprints}), file.NewGroup(callGraph, nil, []string{}), file.NewGroup(pom, nil, []string{}), - file.NewGroup("", nil, []string{cargo}), + file.NewGroup("", nil, []string{unknownLock}), ) var skipped []string for _, issue := range result.Skipped { skipped = append(skipped, issue.Path) } - assert.ElementsMatch(t, []string{fingerprints, callGraph, pom, cargo}, skipped) + assert.ElementsMatch(t, []string{fingerprints, callGraph, pom, unknownLock}, skipped) assert.Empty(t, result.Sanitized) entries, err := os.ReadDir(result.OutputDir) @@ -258,7 +258,7 @@ func TestSanitizeSkipsManifestWithoutSupportedLockFile(t *testing.T) { root := t.TempDir() alone := writeFixture(t, root, "alone/package.json", fixtures.PackageJSONBefore) withUnsupported := writeFixture(t, root, "other/package.json", fixtures.PackageJSONBefore) - unsupportedLock := writeFixture(t, root, "other/Cargo.lock", "version = 3\n") + unsupportedLock := writeFixture(t, root, "other/unknown-format.lock", "s3cret\n") result := sanitizeGroups( t, @@ -270,7 +270,7 @@ func TestSanitizeSkipsManifestWithoutSupportedLockFile(t *testing.T) { assert.Empty(t, result.Sanitized) assert.Len(t, result.Skipped, 3) assert.NoFileExists(t, filepath.Join(result.OutputDir, "alone/package.json")) - assert.NoFileExists(t, filepath.Join(result.OutputDir, "other/Cargo.lock")) + assert.NoFileExists(t, filepath.Join(result.OutputDir, "other/unknown-format.lock")) } func TestSanitizeDoesNotCopyPythonManifests(t *testing.T) { @@ -625,3 +625,21 @@ func TestSanitizeGivesNuGetProjectsOfDifferentProjectsDifferentPlaceholders(t *t assert.Contains(t, readOutput(t, result, "second/packages.lock.json"), `"debricked-redacted-project-2"`) assert.Len(t, readMap(t, result).Placeholders, 2) } + +func TestSanitizerForMatchesFileNamePatterns(t *testing.T) { + cases := map[string]bool{ + "Cargo.lock": true, + "sub/maven_install.json": true, + "rules_jvm_install.json": true, + "gems.Gemfile.lock": true, + "Gemfile.lock": true, + "install.json": false, + "Package.swift": false, + "Cargo.toml": false, + "maven_install.json.backup": false, + "debricked.fingerprints.txt": false, + } + for path, handled := range cases { + assert.Equal(t, handled, sanitizerFor(lockFileSanitizers, path) != nil, path) + } +} From 362301767c7c19eef91ac1d0d16cce41ea315daf Mon Sep 17 00:00:00 2001 From: bpatra3 Date: Fri, 13 Nov 2026 08:14:56 +0000 Subject: [PATCH 2/3] Add tests for sanitizing Yarn lock files and remove unused pubspec files - Implement tests to ensure project descriptors in Yarn lock files are sanitized correctly, preserving project names and handling various dependency scenarios. - Add tests to verify that redacted locators are maintained and that headers for the same package are kept distinct. - Remove outdated pubspec.deps.json and pubspec.lock files from the test data. - Introduce a new empty Package.resolved file for Swift package resolution. Signed-off-by: bpatra3 --- internal/resolution/pm/swift/Package.resolved | 6 + internal/sanitize/pm/yarn/yarn_lock.go | 96 +- internal/sanitize/pm/yarn/yarn_lock_test.go | 92 ++ test/resolve/testdata/pub/pubspec.deps.json | 818 ------------------ test/resolve/testdata/pub/pubspec.lock | 397 --------- 5 files changed, 177 insertions(+), 1232 deletions(-) create mode 100644 internal/resolution/pm/swift/Package.resolved delete mode 100644 test/resolve/testdata/pub/pubspec.deps.json delete mode 100644 test/resolve/testdata/pub/pubspec.lock diff --git a/internal/resolution/pm/swift/Package.resolved b/internal/resolution/pm/swift/Package.resolved new file mode 100644 index 00000000..257ff0bb --- /dev/null +++ b/internal/resolution/pm/swift/Package.resolved @@ -0,0 +1,6 @@ +{ + "pins" : [ + + ], + "version" : 2 +} diff --git a/internal/sanitize/pm/yarn/yarn_lock.go b/internal/sanitize/pm/yarn/yarn_lock.go index 412e0b08..689b7aa6 100644 --- a/internal/sanitize/pm/yarn/yarn_lock.go +++ b/internal/sanitize/pm/yarn/yarn_lock.go @@ -2,6 +2,7 @@ package yarn import ( "bytes" + "net/url" "regexp" "strings" @@ -11,6 +12,9 @@ import ( const ( yarnMetadataHeader = "__metadata:" yarnProjectSpec = "workspace:." + yarnWorkspacePrefix = "workspace:" + yarnBindingsMarker = "::" + yarnLocatorBinding = "locator" yarnSpecSeparator = ", " yarnKeyIndent = 2 yarnDependencyLevel = 4 @@ -24,14 +28,21 @@ var yarnEntryRegex = regexp.MustCompile(`^("[^"]+"|[^\s:"]+)(:?\s+)(.*)$`) type yarnLockSanitizer struct { context *util.FileContext projectNames map[string]bool - output bytes.Buffer - inBlock bool - inMetadata bool - inDependency bool + // projectDescriptors holds every `name@range` in the header of a project's own block. A + // registry package can have the project's name, so a name alone doesn't identify the project. + projectDescriptors map[string]bool + output bytes.Buffer + inBlock bool + inMetadata bool + inDependency bool } func sanitizeYarnLock(content []byte, context *util.FileContext) ([]byte, error) { - sanitizer := &yarnLockSanitizer{context: context, projectNames: map[string]bool{}} + sanitizer := &yarnLockSanitizer{ + context: context, + projectNames: map[string]bool{}, + projectDescriptors: map[string]bool{}, + } lines := strings.Split(strings.ReplaceAll(string(content), "\r\n", "\n"), "\n") if err := sanitizer.findProjectNames(lines); err != nil { @@ -53,14 +64,36 @@ func (s *yarnLockSanitizer) findProjectNames(lines []string) error { if !isYarnHeader(line) || line == yarnMetadataHeader { continue } - for _, spec := range strings.Split(strings.TrimSuffix(line, ":"), yarnSpecSeparator) { - name, version, valid := splitYarnSpec(strings.Trim(spec, `"`)) - if !valid { - return util.ErrInvalidFormat - } - if version == yarnProjectSpec { - s.projectNames[name] = true - } + if err := s.findProjectDescriptors(line); err != nil { + return err + } + } + + return nil +} + +// findProjectDescriptors records the specs of a header that has a `@workspace:.` spec. All +// specs of that name in the header resolve to the project, such as `@workspace:*`. +func (s *yarnLockSanitizer) findProjectDescriptors(line string) error { + specs := strings.Split(strings.TrimSuffix(line, ":"), yarnSpecSeparator) + projectName := "" + for _, spec := range specs { + name, version, valid := splitYarnSpec(strings.Trim(spec, `"`)) + if !valid { + return util.ErrInvalidFormat + } + if version == yarnProjectSpec { + projectName = name + } + } + if projectName == "" { + return nil + } + s.projectNames[projectName] = true + for _, spec := range specs { + unquoted := strings.Trim(spec, `"`) + if name, _, _ := splitYarnSpec(unquoted); name == projectName { + s.projectDescriptors[unquoted] = true } } @@ -139,7 +172,30 @@ func (s *yarnLockSanitizer) maskHeaderSpec(spec string) (string, error) { return "", util.ErrInvalidFormat } - return leading + s.projectName(name) + "@" + util.MaskValue(version) + trailing, nil + return leading + s.projectName(name, version) + "@" + s.maskHeaderVersion(version) + trailing, nil +} + +// maskHeaderVersion keeps Berry's `::locator=` suffix, in redacted form. Berry adds it to local +// dependencies such as portal: and link:, and the dependency lists refer to them without it. The +// backend needs that difference to give the same result as the original, and the suffix keeps +// the headers of the same path from different workspaces apart once the paths are masked. +func (s *yarnLockSanitizer) maskHeaderVersion(version string) string { + rangePart, bindings, found := strings.Cut(version, yarnBindingsMarker) + if !found { + return util.MaskValue(version) + } + parsed, err := url.ParseQuery(bindings) + locator := parsed.Get(yarnLocatorBinding) + if err != nil || locator == "" { + return util.MaskValue(version) + } + name, locatorRange, valid := splitYarnSpec(locator) + if !valid { + return util.MaskValue(version) + } + masked := s.projectName(name, locatorRange) + "@" + util.MaskValue(locatorRange) + + return util.MaskValue(rangePart) + yarnBindingsMarker + yarnLocatorBinding + "=" + url.QueryEscape(masked) } // splitYarnSpec splits at the first '@' after the start, so scoped names and values that contain @@ -191,14 +247,20 @@ func (s *yarnLockSanitizer) processDependency(entry string) error { key, separator, value := match[1], match[2], match[3] name := strings.Trim(key, `"`) - renamed := strings.Replace(key, name, s.projectName(name), 1) + renamed := strings.Replace(key, name, s.projectName(name, strings.Trim(value, `"`)), 1) s.writeLine(" " + renamed + separator + maskQuoted(value)) return nil } -func (s *yarnLockSanitizer) projectName(name string) string { - if s.projectNames[name] { +// projectName renames only a descriptor that refers to the project. A package from a registry keeps +// its name even when the project has the same name, such as a tool that formats itself with a +// published copy of itself. +func (s *yarnLockSanitizer) projectName(name, version string) string { + if !s.projectNames[name] { + return name + } + if s.projectDescriptors[name+"@"+version] || strings.HasPrefix(version, yarnWorkspacePrefix) { return s.context.ProjectPlaceholder(name) } diff --git a/internal/sanitize/pm/yarn/yarn_lock_test.go b/internal/sanitize/pm/yarn/yarn_lock_test.go index 73eb9338..8cc681b4 100644 --- a/internal/sanitize/pm/yarn/yarn_lock_test.go +++ b/internal/sanitize/pm/yarn/yarn_lock_test.go @@ -1,6 +1,7 @@ package yarn import ( + "strings" "testing" "github.com/stretchr/testify/assert" @@ -26,6 +27,97 @@ func TestSanitizeYarnLock(t *testing.T) { } } +// A registry package with the project's name must keep its name, or the backend can't identify it. +func TestSanitizeYarnLockRenamesOnlyTheProjectDescriptors(t *testing.T) { + const placeholder = "debricked-redacted-project-1" + cases := map[string]struct{ before, after string }{ + "npm dependency with the project's name": { + before: "\"lodash@npm:4.17.20\":\n version: 4.17.20\n\n" + + "\"lodash@workspace:.\":\n version: 0.0.0-use.local\n dependencies:\n lodash: \"npm:4.17.20\"\n", + after: "\"lodash@npm:4.17.20\":\n version: 4.17.20\n\n" + + "\"" + placeholder + "@workspace:.\":\n version: 0.0.0-use.local\n dependencies:\n lodash: \"npm:4.17.20\"\n", + }, + "transitive npm dependency with the project's name": { + before: "\"debug@npm:^4.0.0\":\n version: 4.3.4\n dependencies:\n ms: \"npm:2.1.2\"\n\n" + + "\"ms@npm:2.1.2\":\n version: 2.1.2\n\n" + + "\"ms@workspace:.\":\n version: 0.0.0-use.local\n dependencies:\n debug: \"npm:^4.0.0\"\n", + after: "\"debug@npm:^4.0.0\":\n version: 4.3.4\n dependencies:\n ms: \"npm:2.1.2\"\n\n" + + "\"ms@npm:2.1.2\":\n version: 2.1.2\n\n" + + "\"" + placeholder + "@workspace:.\":\n version: 0.0.0-use.local\n dependencies:\n debug: \"npm:^4.0.0\"\n", + }, + "scoped project next to an unscoped package": { + before: "\"@acme/lodash@workspace:.\":\n version: 0.0.0-use.local\n dependencies:\n lodash: \"npm:4.17.20\"\n\n" + + "\"lodash@npm:4.17.20\":\n version: 4.17.20\n", + after: "\"" + placeholder + "@workspace:.\":\n version: 0.0.0-use.local\n dependencies:\n lodash: \"npm:4.17.20\"\n\n" + + "\"lodash@npm:4.17.20\":\n version: 4.17.20\n", + }, + "other specs in the project's header": { + before: "\"app@npm:^1.0.0, app@workspace:.\":\n version: 0.0.0-use.local\n\n" + + "\"member@workspace:packages/member\":\n version: 0.0.0-use.local\n dependencies:\n app: \"npm:^1.0.0\"\n", + after: "\"" + placeholder + "@npm:^1.0.0, " + placeholder + "@workspace:.\":\n version: 0.0.0-use.local\n\n" + + "\"member@workspace:redacted\":\n version: 0.0.0-use.local\n dependencies:\n " + placeholder + ": \"npm:^1.0.0\"\n", + }, + } + for name, c := range cases { + t.Run(name, func(t *testing.T) { + sanitized, err := sanitizeYarnLock([]byte(c.before), newTestContext("yarn.lock")) + + assert.NoError(t, err) + assert.Equal(t, c.after, string(sanitized)) + }) + } +} + +func TestSanitizeYarnLockKeepsARedactedLocator(t *testing.T) { + const rootLocator = "::locator=debricked-redacted-project-1%40workspace%3A." + cases := map[string]struct{ before, after string }{ + "portal from the root": { + before: "\"app@workspace:.\":\n version: 0.0.0-use.local\n dependencies:\n shared: \"portal:../shared-utils\"\n\n" + + "\"shared@portal:../shared-utils::locator=app%40workspace%3A.\":\n version: 0.0.0-use.local\n", + after: "\"debricked-redacted-project-1@workspace:.\":\n version: 0.0.0-use.local\n dependencies:\n shared: \"file:./redacted\"\n\n" + + "\"shared@file:./redacted" + rootLocator + "\":\n version: 0.0.0-use.local\n", + }, + "link from a workspace member": { + before: "\"shared@link:../shared::locator=%40acme%2Fbench%40workspace%3Abenchmark\":\n version: 0.0.0-use.local\n", + after: "\"shared@file:./redacted::locator=%40acme%2Fbench%40workspace%3Aredacted\":\n version: 0.0.0-use.local\n", + }, + "bindings without a locator": { + before: "\"shared@exec:./gen.js::hash=abc\":\n version: 1.0.0\n", + after: "\"shared@file:./redacted\":\n version: 1.0.0\n", + }, + } + for name, c := range cases { + t.Run(name, func(t *testing.T) { + sanitized, err := sanitizeYarnLock([]byte(c.before), newTestContext("yarn.lock")) + + assert.NoError(t, err) + assert.Equal(t, c.after, string(sanitized)) + }) + } +} + +// Masking turns different paths into the same placeholder, so without the locator two blocks +// would get the same header, and the backend never finishes processing the file. +func TestSanitizeYarnLockKeepsHeadersOfTheSamePackageApart(t *testing.T) { + content := "\"babel@workspace:.\":\n version: 0.0.0-use.local\n\n" + + "\"utils@link:../scripts/utils::locator=%40babel%2Fbench%40workspace%3Abenchmark\":\n version: 0.0.0-use.local\n\n" + + "\"utils@link:./scripts/utils::locator=babel%40workspace%3A.\":\n version: 0.0.0-use.local\n" + + sanitized, err := sanitizeYarnLock([]byte(content), newTestContext("yarn.lock")) + + assert.NoError(t, err) + headers := map[string]bool{} + for _, line := range strings.Split(string(sanitized), "\n") { + if strings.HasPrefix(line, "\"") { + assert.False(t, headers[line], "duplicate header %s", line) + headers[line] = true + } + } + assert.Len(t, headers, 3) + assert.NotContains(t, string(sanitized), "locator=babel") + assert.NotContains(t, string(sanitized), "scripts") +} + func TestSanitizeYarnLockRemovesInlineCommentLines(t *testing.T) { content := "# top\nfoo@^1.0.0:\n # indented s3cret comment\n version \"1.0.0\"\n" diff --git a/test/resolve/testdata/pub/pubspec.deps.json b/test/resolve/testdata/pub/pubspec.deps.json deleted file mode 100644 index 3e77eedd..00000000 --- a/test/resolve/testdata/pub/pubspec.deps.json +++ /dev/null @@ -1,818 +0,0 @@ -{ - "root": "my_dart_app", - "packages": [ - { - "name": "my_dart_app", - "version": "1.0.0", - "kind": "root", - "source": "root", - "dependencies": [ - "http", - "collection", - "path", - "test", - "lints" - ], - "directDependencies": [ - "http", - "collection", - "path" - ], - "devDependencies": [ - "test", - "lints" - ] - }, - { - "name": "lints", - "version": "3.0.0", - "kind": "dev", - "source": "hosted", - "dependencies": [], - "directDependencies": [] - }, - { - "name": "test", - "version": "1.31.1", - "kind": "dev", - "source": "hosted", - "dependencies": [ - "analyzer", - "async", - "boolean_selector", - "collection", - "coverage", - "http_multi_server", - "io", - "matcher", - "node_preamble", - "package_config", - "path", - "pool", - "shelf", - "shelf_packages_handler", - "shelf_static", - "shelf_web_socket", - "source_span", - "stack_trace", - "stream_channel", - "test_api", - "test_core", - "typed_data", - "web_socket_channel", - "webkit_inspection_protocol", - "yaml" - ], - "directDependencies": [ - "analyzer", - "async", - "boolean_selector", - "collection", - "coverage", - "http_multi_server", - "io", - "matcher", - "node_preamble", - "package_config", - "path", - "pool", - "shelf", - "shelf_packages_handler", - "shelf_static", - "shelf_web_socket", - "source_span", - "stack_trace", - "stream_channel", - "test_api", - "test_core", - "typed_data", - "web_socket_channel", - "webkit_inspection_protocol", - "yaml" - ] - }, - { - "name": "yaml", - "version": "3.1.3", - "kind": "transitive", - "source": "hosted", - "dependencies": [ - "collection", - "source_span", - "string_scanner" - ], - "directDependencies": [ - "collection", - "source_span", - "string_scanner" - ] - }, - { - "name": "string_scanner", - "version": "1.4.1", - "kind": "transitive", - "source": "hosted", - "dependencies": [ - "source_span" - ], - "directDependencies": [ - "source_span" - ] - }, - { - "name": "source_span", - "version": "1.10.2", - "kind": "transitive", - "source": "hosted", - "dependencies": [ - "collection", - "path", - "term_glyph" - ], - "directDependencies": [ - "collection", - "path", - "term_glyph" - ] - }, - { - "name": "term_glyph", - "version": "1.2.2", - "kind": "transitive", - "source": "hosted", - "dependencies": [], - "directDependencies": [] - }, - { - "name": "path", - "version": "1.9.1", - "kind": "direct", - "source": "hosted", - "dependencies": [], - "directDependencies": [] - }, - { - "name": "collection", - "version": "1.19.1", - "kind": "direct", - "source": "hosted", - "dependencies": [], - "directDependencies": [] - }, - { - "name": "webkit_inspection_protocol", - "version": "1.2.1", - "kind": "transitive", - "source": "hosted", - "dependencies": [ - "logging" - ], - "directDependencies": [ - "logging" - ] - }, - { - "name": "logging", - "version": "1.3.0", - "kind": "transitive", - "source": "hosted", - "dependencies": [], - "directDependencies": [] - }, - { - "name": "web_socket_channel", - "version": "3.0.3", - "kind": "transitive", - "source": "hosted", - "dependencies": [ - "async", - "crypto", - "stream_channel", - "web", - "web_socket" - ], - "directDependencies": [ - "async", - "crypto", - "stream_channel", - "web", - "web_socket" - ] - }, - { - "name": "web_socket", - "version": "1.0.1", - "kind": "transitive", - "source": "hosted", - "dependencies": [ - "web" - ], - "directDependencies": [ - "web" - ] - }, - { - "name": "web", - "version": "1.1.1", - "kind": "transitive", - "source": "hosted", - "dependencies": [], - "directDependencies": [] - }, - { - "name": "stream_channel", - "version": "2.1.4", - "kind": "transitive", - "source": "hosted", - "dependencies": [ - "async" - ], - "directDependencies": [ - "async" - ] - }, - { - "name": "async", - "version": "2.13.1", - "kind": "transitive", - "source": "hosted", - "dependencies": [ - "collection", - "meta" - ], - "directDependencies": [ - "collection", - "meta" - ] - }, - { - "name": "meta", - "version": "1.18.3", - "kind": "transitive", - "source": "hosted", - "dependencies": [], - "directDependencies": [] - }, - { - "name": "crypto", - "version": "3.0.7", - "kind": "transitive", - "source": "hosted", - "dependencies": [ - "typed_data" - ], - "directDependencies": [ - "typed_data" - ] - }, - { - "name": "typed_data", - "version": "1.4.0", - "kind": "transitive", - "source": "hosted", - "dependencies": [ - "collection" - ], - "directDependencies": [ - "collection" - ] - }, - { - "name": "test_core", - "version": "0.6.18", - "kind": "transitive", - "source": "hosted", - "dependencies": [ - "analyzer", - "args", - "async", - "boolean_selector", - "collection", - "coverage", - "frontend_server_client", - "glob", - "io", - "meta", - "package_config", - "path", - "pool", - "source_map_stack_trace", - "source_maps", - "source_span", - "stack_trace", - "stream_channel", - "test_api", - "vm_service", - "yaml" - ], - "directDependencies": [ - "analyzer", - "args", - "async", - "boolean_selector", - "collection", - "coverage", - "frontend_server_client", - "glob", - "io", - "meta", - "package_config", - "path", - "pool", - "source_map_stack_trace", - "source_maps", - "source_span", - "stack_trace", - "stream_channel", - "test_api", - "vm_service", - "yaml" - ] - }, - { - "name": "vm_service", - "version": "15.2.0", - "kind": "transitive", - "source": "hosted", - "dependencies": [], - "directDependencies": [] - }, - { - "name": "test_api", - "version": "0.7.12", - "kind": "transitive", - "source": "hosted", - "dependencies": [ - "async", - "boolean_selector", - "collection", - "meta", - "source_span", - "stack_trace", - "stream_channel", - "string_scanner", - "term_glyph" - ], - "directDependencies": [ - "async", - "boolean_selector", - "collection", - "meta", - "source_span", - "stack_trace", - "stream_channel", - "string_scanner", - "term_glyph" - ] - }, - { - "name": "stack_trace", - "version": "1.12.1", - "kind": "transitive", - "source": "hosted", - "dependencies": [ - "path" - ], - "directDependencies": [ - "path" - ] - }, - { - "name": "boolean_selector", - "version": "2.1.2", - "kind": "transitive", - "source": "hosted", - "dependencies": [ - "source_span", - "string_scanner" - ], - "directDependencies": [ - "source_span", - "string_scanner" - ] - }, - { - "name": "source_maps", - "version": "0.10.13", - "kind": "transitive", - "source": "hosted", - "dependencies": [ - "source_span" - ], - "directDependencies": [ - "source_span" - ] - }, - { - "name": "source_map_stack_trace", - "version": "2.1.2", - "kind": "transitive", - "source": "hosted", - "dependencies": [ - "path", - "source_maps", - "stack_trace" - ], - "directDependencies": [ - "path", - "source_maps", - "stack_trace" - ] - }, - { - "name": "pool", - "version": "1.5.2", - "kind": "transitive", - "source": "hosted", - "dependencies": [ - "async", - "stack_trace" - ], - "directDependencies": [ - "async", - "stack_trace" - ] - }, - { - "name": "package_config", - "version": "2.2.0", - "kind": "transitive", - "source": "hosted", - "dependencies": [ - "path" - ], - "directDependencies": [ - "path" - ] - }, - { - "name": "io", - "version": "1.0.5", - "kind": "transitive", - "source": "hosted", - "dependencies": [ - "meta", - "path", - "string_scanner" - ], - "directDependencies": [ - "meta", - "path", - "string_scanner" - ] - }, - { - "name": "glob", - "version": "2.1.3", - "kind": "transitive", - "source": "hosted", - "dependencies": [ - "async", - "collection", - "file", - "path", - "string_scanner" - ], - "directDependencies": [ - "async", - "collection", - "file", - "path", - "string_scanner" - ] - }, - { - "name": "file", - "version": "7.0.1", - "kind": "transitive", - "source": "hosted", - "dependencies": [ - "meta", - "path" - ], - "directDependencies": [ - "meta", - "path" - ] - }, - { - "name": "frontend_server_client", - "version": "4.0.0", - "kind": "transitive", - "source": "hosted", - "dependencies": [ - "async", - "path" - ], - "directDependencies": [ - "async", - "path" - ] - }, - { - "name": "coverage", - "version": "1.15.1", - "kind": "transitive", - "source": "hosted", - "dependencies": [ - "args", - "cli_config", - "glob", - "logging", - "meta", - "package_config", - "path", - "source_maps", - "stack_trace", - "vm_service", - "yaml" - ], - "directDependencies": [ - "args", - "cli_config", - "glob", - "logging", - "meta", - "package_config", - "path", - "source_maps", - "stack_trace", - "vm_service", - "yaml" - ] - }, - { - "name": "cli_config", - "version": "0.2.0", - "kind": "transitive", - "source": "hosted", - "dependencies": [ - "args", - "yaml" - ], - "directDependencies": [ - "args", - "yaml" - ] - }, - { - "name": "args", - "version": "2.7.0", - "kind": "transitive", - "source": "hosted", - "dependencies": [], - "directDependencies": [] - }, - { - "name": "analyzer", - "version": "13.3.0", - "kind": "transitive", - "source": "hosted", - "dependencies": [ - "_fe_analyzer_shared", - "collection", - "convert", - "crypto", - "glob", - "meta", - "package_config", - "path", - "pub_semver", - "source_span", - "watcher", - "yaml" - ], - "directDependencies": [ - "_fe_analyzer_shared", - "collection", - "convert", - "crypto", - "glob", - "meta", - "package_config", - "path", - "pub_semver", - "source_span", - "watcher", - "yaml" - ] - }, - { - "name": "watcher", - "version": "1.2.1", - "kind": "transitive", - "source": "hosted", - "dependencies": [ - "async", - "path" - ], - "directDependencies": [ - "async", - "path" - ] - }, - { - "name": "pub_semver", - "version": "2.2.0", - "kind": "transitive", - "source": "hosted", - "dependencies": [ - "collection" - ], - "directDependencies": [ - "collection" - ] - }, - { - "name": "convert", - "version": "3.1.2", - "kind": "transitive", - "source": "hosted", - "dependencies": [ - "typed_data" - ], - "directDependencies": [ - "typed_data" - ] - }, - { - "name": "_fe_analyzer_shared", - "version": "103.0.0", - "kind": "transitive", - "source": "hosted", - "dependencies": [ - "meta" - ], - "directDependencies": [ - "meta" - ] - }, - { - "name": "shelf_web_socket", - "version": "3.0.0", - "kind": "transitive", - "source": "hosted", - "dependencies": [ - "shelf", - "stream_channel", - "web_socket_channel" - ], - "directDependencies": [ - "shelf", - "stream_channel", - "web_socket_channel" - ] - }, - { - "name": "shelf", - "version": "1.4.2", - "kind": "transitive", - "source": "hosted", - "dependencies": [ - "async", - "collection", - "http_parser", - "path", - "stack_trace", - "stream_channel" - ], - "directDependencies": [ - "async", - "collection", - "http_parser", - "path", - "stack_trace", - "stream_channel" - ] - }, - { - "name": "http_parser", - "version": "4.1.2", - "kind": "transitive", - "source": "hosted", - "dependencies": [ - "collection", - "source_span", - "string_scanner", - "typed_data" - ], - "directDependencies": [ - "collection", - "source_span", - "string_scanner", - "typed_data" - ] - }, - { - "name": "shelf_static", - "version": "1.1.3", - "kind": "transitive", - "source": "hosted", - "dependencies": [ - "convert", - "http_parser", - "mime", - "path", - "shelf" - ], - "directDependencies": [ - "convert", - "http_parser", - "mime", - "path", - "shelf" - ] - }, - { - "name": "mime", - "version": "2.0.0", - "kind": "transitive", - "source": "hosted", - "dependencies": [], - "directDependencies": [] - }, - { - "name": "shelf_packages_handler", - "version": "3.0.2", - "kind": "transitive", - "source": "hosted", - "dependencies": [ - "path", - "shelf", - "shelf_static" - ], - "directDependencies": [ - "path", - "shelf", - "shelf_static" - ] - }, - { - "name": "node_preamble", - "version": "2.0.2", - "kind": "transitive", - "source": "hosted", - "dependencies": [], - "directDependencies": [] - }, - { - "name": "matcher", - "version": "0.12.20", - "kind": "transitive", - "source": "hosted", - "dependencies": [ - "async", - "meta", - "stack_trace", - "term_glyph", - "test_api" - ], - "directDependencies": [ - "async", - "meta", - "stack_trace", - "term_glyph", - "test_api" - ] - }, - { - "name": "http_multi_server", - "version": "3.2.2", - "kind": "transitive", - "source": "hosted", - "dependencies": [ - "async" - ], - "directDependencies": [ - "async" - ] - }, - { - "name": "http", - "version": "1.6.0", - "kind": "direct", - "source": "hosted", - "dependencies": [ - "async", - "http_parser", - "meta", - "web" - ], - "directDependencies": [ - "async", - "http_parser", - "meta", - "web" - ] - } - ], - "sdks": [ - { - "name": "Dart", - "version": "3.12.2" - } - ], - "executables": [ - "test" - ] -} diff --git a/test/resolve/testdata/pub/pubspec.lock b/test/resolve/testdata/pub/pubspec.lock deleted file mode 100644 index 3ba07bda..00000000 --- a/test/resolve/testdata/pub/pubspec.lock +++ /dev/null @@ -1,397 +0,0 @@ -# Generated by pub -# See https://dart.dev/tools/pub/glossary#lockfile -packages: - _fe_analyzer_shared: - dependency: transitive - description: - name: _fe_analyzer_shared - sha256: "1b0e6a07425a3e460666e88bf1c949ccc7bb0116ad562ce94a1eca60fe820725" - url: "https://pub.dev" - source: hosted - version: "103.0.0" - analyzer: - dependency: transitive - description: - name: analyzer - sha256: "61c04d0c1bfed555c681ea079519933f071a5a026578ff73c4ff0df2d3462e5e" - url: "https://pub.dev" - source: hosted - version: "13.3.0" - args: - dependency: transitive - description: - name: args - sha256: d0481093c50b1da8910eb0bb301626d4d8eb7284aa739614d2b394ee09e3ea04 - url: "https://pub.dev" - source: hosted - version: "2.7.0" - async: - dependency: transitive - description: - name: async - sha256: e2eb0491ba5ddb6177742d2da23904574082139b07c1e33b8503b9f46f3e1a37 - url: "https://pub.dev" - source: hosted - version: "2.13.1" - boolean_selector: - dependency: transitive - description: - name: boolean_selector - sha256: "8aab1771e1243a5063b8b0ff68042d67334e3feab9e95b9490f9a6ebf73b42ea" - url: "https://pub.dev" - source: hosted - version: "2.1.2" - cli_config: - dependency: transitive - description: - name: cli_config - sha256: ac20a183a07002b700f0c25e61b7ee46b23c309d76ab7b7640a028f18e4d99ec - url: "https://pub.dev" - source: hosted - version: "0.2.0" - collection: - dependency: "direct main" - description: - name: collection - sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76" - url: "https://pub.dev" - source: hosted - version: "1.19.1" - convert: - dependency: transitive - description: - name: convert - sha256: b30acd5944035672bc15c6b7a8b47d773e41e2f17de064350988c5d02adb1c68 - url: "https://pub.dev" - source: hosted - version: "3.1.2" - coverage: - dependency: transitive - description: - name: coverage - sha256: "956a3de0725ca232ad353565a8290d3357592bf4250f6f298a185e2d949c5d3d" - url: "https://pub.dev" - source: hosted - version: "1.15.1" - crypto: - dependency: transitive - description: - name: crypto - sha256: c8ea0233063ba03258fbcf2ca4d6dadfefe14f02fab57702265467a19f27fadf - url: "https://pub.dev" - source: hosted - version: "3.0.7" - file: - dependency: transitive - description: - name: file - sha256: a3b4f84adafef897088c160faf7dfffb7696046cb13ae90b508c2cbc95d3b8d4 - url: "https://pub.dev" - source: hosted - version: "7.0.1" - frontend_server_client: - dependency: transitive - description: - name: frontend_server_client - sha256: f64a0333a82f30b0cca061bc3d143813a486dc086b574bfb233b7c1372427694 - url: "https://pub.dev" - source: hosted - version: "4.0.0" - glob: - dependency: transitive - description: - name: glob - sha256: c3f1ee72c96f8f78935e18aa8cecced9ab132419e8625dc187e1c2408efc20de - url: "https://pub.dev" - source: hosted - version: "2.1.3" - http: - dependency: "direct main" - description: - name: http - sha256: "87721a4a50b19c7f1d49001e51409bddc46303966ce89a65af4f4e6004896412" - url: "https://pub.dev" - source: hosted - version: "1.6.0" - http_multi_server: - dependency: transitive - description: - name: http_multi_server - sha256: aa6199f908078bb1c5efb8d8638d4ae191aac11b311132c3ef48ce352fb52ef8 - url: "https://pub.dev" - source: hosted - version: "3.2.2" - http_parser: - dependency: transitive - description: - name: http_parser - sha256: "178d74305e7866013777bab2c3d8726205dc5a4dd935297175b19a23a2e66571" - url: "https://pub.dev" - source: hosted - version: "4.1.2" - io: - dependency: transitive - description: - name: io - sha256: dfd5a80599cf0165756e3181807ed3e77daf6dd4137caaad72d0b7931597650b - url: "https://pub.dev" - source: hosted - version: "1.0.5" - lints: - dependency: "direct dev" - description: - name: lints - sha256: cbf8d4b858bb0134ef3ef87841abdf8d63bfc255c266b7bf6b39daa1085c4290 - url: "https://pub.dev" - source: hosted - version: "3.0.0" - logging: - dependency: transitive - description: - name: logging - sha256: c8245ada5f1717ed44271ed1c26b8ce85ca3228fd2ffdb75468ab01979309d61 - url: "https://pub.dev" - source: hosted - version: "1.3.0" - matcher: - dependency: transitive - description: - name: matcher - sha256: "31bd099b47c10cd1aeb55146a2d46ce0277630ecef3f7dae54ad7873f36696cd" - url: "https://pub.dev" - source: hosted - version: "0.12.20" - meta: - dependency: transitive - description: - name: meta - sha256: c82594181e3312f3d0695fc95aaaf7758d75b8d4ae2bbecf223b9fd5109a059d - url: "https://pub.dev" - source: hosted - version: "1.18.3" - mime: - dependency: transitive - description: - name: mime - sha256: "41a20518f0cb1256669420fdba0cd90d21561e560ac240f26ef8322e45bb7ed6" - url: "https://pub.dev" - source: hosted - version: "2.0.0" - node_preamble: - dependency: transitive - description: - name: node_preamble - sha256: "6e7eac89047ab8a8d26cf16127b5ed26de65209847630400f9aefd7cd5c730db" - url: "https://pub.dev" - source: hosted - version: "2.0.2" - package_config: - dependency: transitive - description: - name: package_config - sha256: f096c55ebb7deb7e384101542bfba8c52696c1b56fca2eb62827989ef2353bbc - url: "https://pub.dev" - source: hosted - version: "2.2.0" - path: - dependency: "direct main" - description: - name: path - sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5" - url: "https://pub.dev" - source: hosted - version: "1.9.1" - pool: - dependency: transitive - description: - name: pool - sha256: "978783255c543aa3586a1b3c21f6e9d720eb315376a915872c61ef8b5c20177d" - url: "https://pub.dev" - source: hosted - version: "1.5.2" - pub_semver: - dependency: transitive - description: - name: pub_semver - sha256: "5bfcf68ca79ef689f8990d1160781b4bad40a3bd5e5218ad4076ddb7f4081585" - url: "https://pub.dev" - source: hosted - version: "2.2.0" - shelf: - dependency: transitive - description: - name: shelf - sha256: e7dd780a7ffb623c57850b33f43309312fc863fb6aa3d276a754bb299839ef12 - url: "https://pub.dev" - source: hosted - version: "1.4.2" - shelf_packages_handler: - dependency: transitive - description: - name: shelf_packages_handler - sha256: "89f967eca29607c933ba9571d838be31d67f53f6e4ee15147d5dc2934fee1b1e" - url: "https://pub.dev" - source: hosted - version: "3.0.2" - shelf_static: - dependency: transitive - description: - name: shelf_static - sha256: c87c3875f91262785dade62d135760c2c69cb217ac759485334c5857ad89f6e3 - url: "https://pub.dev" - source: hosted - version: "1.1.3" - shelf_web_socket: - dependency: transitive - description: - name: shelf_web_socket - sha256: "3632775c8e90d6c9712f883e633716432a27758216dfb61bd86a8321c0580925" - url: "https://pub.dev" - source: hosted - version: "3.0.0" - source_map_stack_trace: - dependency: transitive - description: - name: source_map_stack_trace - sha256: c0713a43e323c3302c2abe2a1cc89aa057a387101ebd280371d6a6c9fa68516b - url: "https://pub.dev" - source: hosted - version: "2.1.2" - source_maps: - dependency: transitive - description: - name: source_maps - sha256: "190222579a448b03896e0ca6eca5998fa810fda630c1d65e2f78b3f638f54812" - url: "https://pub.dev" - source: hosted - version: "0.10.13" - source_span: - dependency: transitive - description: - name: source_span - sha256: "56a02f1f4cd1a2d96303c0144c93bd6d909eea6bee6bf5a0e0b685edbd4c47ab" - url: "https://pub.dev" - source: hosted - version: "1.10.2" - stack_trace: - dependency: transitive - description: - name: stack_trace - sha256: "8b27215b45d22309b5cddda1aa2b19bdfec9df0e765f2de506401c071d38d1b1" - url: "https://pub.dev" - source: hosted - version: "1.12.1" - stream_channel: - dependency: transitive - description: - name: stream_channel - sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d" - url: "https://pub.dev" - source: hosted - version: "2.1.4" - string_scanner: - dependency: transitive - description: - name: string_scanner - sha256: "921cd31725b72fe181906c6a94d987c78e3b98c2e205b397ea399d4054872b43" - url: "https://pub.dev" - source: hosted - version: "1.4.1" - term_glyph: - dependency: transitive - description: - name: term_glyph - sha256: "7f554798625ea768a7518313e58f83891c7f5024f88e46e7182a4558850a4b8e" - url: "https://pub.dev" - source: hosted - version: "1.2.2" - test: - dependency: "direct dev" - description: - name: test - sha256: ca578dc12bb8b2f40b67b7d3bd2fac4f31c01a6ff7130a14e2597b919934507f - url: "https://pub.dev" - source: hosted - version: "1.31.1" - test_api: - dependency: transitive - description: - name: test_api - sha256: "2a122cbe059f8b610d3a5415f42e255b6c17b1f21eee1d960f31080237fb4f11" - url: "https://pub.dev" - source: hosted - version: "0.7.12" - test_core: - dependency: transitive - description: - name: test_core - sha256: d2e98ec12998368dc59ddd47ab709f2cd55acd6b66dc7db764455a44082f4bc5 - url: "https://pub.dev" - source: hosted - version: "0.6.18" - typed_data: - dependency: transitive - description: - name: typed_data - sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006 - url: "https://pub.dev" - source: hosted - version: "1.4.0" - vm_service: - dependency: transitive - description: - name: vm_service - sha256: "0016aef94fc66495ac78af5859181e3f3bf2026bd8eecc72b9565601e19ab360" - url: "https://pub.dev" - source: hosted - version: "15.2.0" - watcher: - dependency: transitive - description: - name: watcher - sha256: "1398c9f081a753f9226febe8900fce8f7d0a67163334e1c94a2438339d79d635" - url: "https://pub.dev" - source: hosted - version: "1.2.1" - web: - dependency: transitive - description: - name: web - sha256: "868d88a33d8a87b18ffc05f9f030ba328ffefba92d6c127917a2ba740f9cfe4a" - url: "https://pub.dev" - source: hosted - version: "1.1.1" - web_socket: - dependency: transitive - description: - name: web_socket - sha256: "34d64019aa8e36bf9842ac014bb5d2f5586ca73df5e4d9bf5c936975cae6982c" - url: "https://pub.dev" - source: hosted - version: "1.0.1" - web_socket_channel: - dependency: transitive - description: - name: web_socket_channel - sha256: d645757fb0f4773d602444000a8131ff5d48c9e47adfe9772652dd1a4f2d45c8 - url: "https://pub.dev" - source: hosted - version: "3.0.3" - webkit_inspection_protocol: - dependency: transitive - description: - name: webkit_inspection_protocol - sha256: "87d3f2333bb240704cd3f1c6b5b7acd8a10e7f0bc28c28dcf14e782014f4a572" - url: "https://pub.dev" - source: hosted - version: "1.2.1" - yaml: - dependency: transitive - description: - name: yaml - sha256: b9da305ac7c39faa3f030eccd175340f968459dae4af175130b3fc47e40d76ce - url: "https://pub.dev" - source: hosted - version: "3.1.3" -sdks: - dart: ">=3.11.0 <4.0.0" From 4e98467235fecffc24a5c34ef61b728a3b77f1eb Mon Sep 17 00:00:00 2001 From: bpatra3 Date: Mon, 16 Nov 2026 08:56:38 +0000 Subject: [PATCH 3/3] feat(sanitize): enhance sanitization logic and error handling for various file formats Signed-off-by: bpatra3 --- internal/cmd/sanitize/sanitize.go | 4 ++ internal/cmd/sanitize/sanitize_test.go | 7 +++ internal/sanitize/pm/bazel/install_json.go | 7 ++- .../sanitize/pm/bazel/install_json_test.go | 7 ++- internal/sanitize/pm/npm/package_json_test.go | 11 ++++ internal/sanitize/pm/pnpm/pnpm_lock.go | 49 ++++++++++++++- internal/sanitize/pm/pnpm/pnpm_lock_test.go | 61 +++++++++++++++++-- internal/sanitize/pm/util/context.go | 19 ++++++ internal/sanitize/pm/util/mask.go | 51 ++++++++++++++-- internal/sanitize/pm/util/mask_test.go | 14 ++++- internal/sanitize/pm/util/yaml_nodes.go | 39 +++++++++--- internal/sanitize/pm/util/yaml_nodes_test.go | 33 ++++++++++ internal/sanitize/pm/yarn/yarn_lock_test.go | 17 ++++++ internal/sanitize/sanitize.go | 36 ++++++++--- internal/sanitize/sanitize_test.go | 35 +++++++++++ 15 files changed, 359 insertions(+), 31 deletions(-) create mode 100644 internal/sanitize/pm/util/yaml_nodes_test.go diff --git a/internal/cmd/sanitize/sanitize.go b/internal/cmd/sanitize/sanitize.go index b154822d..73ad94c1 100644 --- a/internal/cmd/sanitize/sanitize.go +++ b/internal/cmd/sanitize/sanitize.go @@ -127,6 +127,10 @@ func Run(cmd *cobra.Command, sanitizer sanitize.ISanitizer, options sanitize.Opt // printGroups uses the output format of `debricked files find`. func printGroups(out io.Writer, groups []file.Group, asJson bool) error { if asJson { + if groups == nil { + // The same output as `debricked files find --json` when nothing is found. + groups = []file.Group{} + } encoded, err := json.Marshal(groups) if err != nil { return err diff --git a/internal/cmd/sanitize/sanitize_test.go b/internal/cmd/sanitize/sanitize_test.go index 1c16ac5c..63f25172 100644 --- a/internal/cmd/sanitize/sanitize_test.go +++ b/internal/cmd/sanitize/sanitize_test.go @@ -77,6 +77,13 @@ func TestRunEPrintsSanitizedFilesAsJson(t *testing.T) { ]`, out) } +func TestRunEPrintsAnEmptyJsonListWhenNothingWasSanitized(t *testing.T) { + out, _, err := execute(&sanitizerMock{}, "x", "--json") + + assert.NoError(t, err) + assert.Equal(t, "[]\n", out) +} + func TestRunEPrintsSummary(t *testing.T) { mock := &sanitizerMock{result: sanitize.Result{ OutputDir: "x/.debricked/sanitized", diff --git a/internal/sanitize/pm/bazel/install_json.go b/internal/sanitize/pm/bazel/install_json.go index 16b2d55b..400c8cf1 100644 --- a/internal/sanitize/pm/bazel/install_json.go +++ b/internal/sanitize/pm/bazel/install_json.go @@ -6,14 +6,17 @@ import "github.com/debricked/cli/internal/sanitize/pm/util" // dependencies if there are no direct ones, because that is what the backend reads. URLs, mirror // URLs, file paths and hashes are removed: the URLs can hold private hosts and credentials. // -// The backend needs dependency_tree, so the newer format without it fails here rather than being -// uploaded and giving no packages. +// The backend needs dependency_tree and finds no packages in the v2 format, which has "artifacts" +// instead. A v2 file is skipped with ErrUnsupportedVersion, so it is reported and never copied. func sanitizeInstallJSON(content []byte, _ *util.FileContext) ([]byte, error) { install, err := util.ParseJSONObject(content) if err != nil { return nil, util.ErrInvalidFormat } tree, isObject := install.Values["dependency_tree"].(*util.OrderedObject) + if _, isV2 := install.Values["artifacts"].(*util.OrderedObject); !isObject && isV2 { + return nil, util.ErrUnsupportedVersion + } if !isObject { return nil, util.ErrInvalidFormat } diff --git a/internal/sanitize/pm/bazel/install_json_test.go b/internal/sanitize/pm/bazel/install_json_test.go index 78dfa66a..dc9cac02 100644 --- a/internal/sanitize/pm/bazel/install_json_test.go +++ b/internal/sanitize/pm/bazel/install_json_test.go @@ -114,11 +114,16 @@ func TestSanitizeInstallJSONUsesDependenciesWhenThereAreNoDirectOnes(t *testing. `, string(sanitized)) } +func TestSanitizeInstallJSONSkipsVersion2(t *testing.T) { + _, err := sanitizeInstallJSON([]byte(`{"version": "2", "artifacts": {"a:b": {"version": "1"}}}`), nil) + + assert.ErrorIs(t, err, util.ErrUnsupportedVersion) +} + func TestSanitizeInstallJSONInvalid(t *testing.T) { for _, content := range []string{ ``, `[]`, - `{"version": "2", "artifacts": {}}`, `{"dependency_tree": []}`, `{"dependency_tree": {"dependencies": {}}}`, `{"dependency_tree": {"dependencies": ["a:b:1"]}}`, diff --git a/internal/sanitize/pm/npm/package_json_test.go b/internal/sanitize/pm/npm/package_json_test.go index 78e5fbac..47b6ff05 100644 --- a/internal/sanitize/pm/npm/package_json_test.go +++ b/internal/sanitize/pm/npm/package_json_test.go @@ -28,3 +28,14 @@ func newTestContext(path string) *util.FileContext { return context } + +// A yarn.lock dependency on the same patch gets the same value, see the yarn tests. +func TestSanitizePackageJSONKeepsThePatchedDescriptor(t *testing.T) { + content := `{"dependencies": {"interpret": "patch:interpret@npm%3A3.1.1#~/.yarn/patches/interpret-npm-3.1.1-715bac2bd7.patch"}}` + + sanitized, err := sanitizePackageJSON([]byte(content), newTestContext("package.json")) + + assert.NoError(t, err) + assert.Contains(t, string(sanitized), `"interpret": "patch:interpret@npm%3A3.1.1#redacted.patch"`) + assert.NotContains(t, string(sanitized), ".yarn/patches") +} diff --git a/internal/sanitize/pm/pnpm/pnpm_lock.go b/internal/sanitize/pm/pnpm/pnpm_lock.go index e64265fb..cba0e128 100644 --- a/internal/sanitize/pm/pnpm/pnpm_lock.go +++ b/internal/sanitize/pm/pnpm/pnpm_lock.go @@ -37,7 +37,7 @@ type pnpmLockSanitizer struct { } func sanitizePnpmLock(content []byte, context *util.FileContext) ([]byte, error) { - root, err := util.ParseYAMLMapping(content) + root, err := lockDocument(content) if err != nil { return nil, err } @@ -60,6 +60,53 @@ func sanitizePnpmLock(content []byte, context *util.FileContext) ([]byte, error) return util.EncodeYAML(sanitized), nil } +// pnpmEnvironmentKeys are the only keys of an importer in pnpm's environment document. pnpm 11 and +// later put that document, which lists pnpm itself, before the lock file document. +var pnpmEnvironmentKeys = map[string]bool{"configDependencies": true, "packageManagerDependencies": true} + +// lockDocument returns the one document of the file that is a lock file. The backend can't parse +// a file with several documents, so only that one is written to the copy. +func lockDocument(content []byte) (*yaml.Node, error) { + documents, err := util.ParseYAMLMappings(content) + if err != nil { + return nil, err + } + var lockDocuments []*yaml.Node + for _, document := range documents { + if !isEnvironmentDocument(document) { + lockDocuments = append(lockDocuments, document) + } + } + switch len(lockDocuments) { + case 1: + return lockDocuments[0], nil + case 0: + return nil, util.ErrNoLockDocument + default: + return nil, util.ErrInvalidFormat + } +} + +// isEnvironmentDocument reports whether every importer of a document lists only pnpm's own +// dependencies. +func isEnvironmentDocument(document *yaml.Node) bool { + importers := util.YAMLValue(document, "importers") + if importers == nil || importers.Kind != yaml.MappingNode || len(importers.Content) == 0 { + return false + } + environment := true + util.ForEachYAMLPair(importers, func(_ string, importer *yaml.Node) { + hasKeys := false + util.ForEachYAMLPair(importer, func(key string, _ *yaml.Node) { + hasKeys = true + environment = environment && pnpmEnvironmentKeys[key] + }) + environment = environment && hasKeys + }) + + return environment +} + // sanitizeRoot fails if no known section is left, because then the file isn't a pnpm lock file. func (s *pnpmLockSanitizer) sanitizeRoot(root *yaml.Node) (*util.OrderedObject, error) { sanitized := util.NewOrderedObject() diff --git a/internal/sanitize/pm/pnpm/pnpm_lock_test.go b/internal/sanitize/pm/pnpm/pnpm_lock_test.go index b8775b73..b9718a9c 100644 --- a/internal/sanitize/pm/pnpm/pnpm_lock_test.go +++ b/internal/sanitize/pm/pnpm/pnpm_lock_test.go @@ -441,12 +441,14 @@ func TestSanitizePnpmLockRecordsPathsInTheMap(t *testing.T) { func TestSanitizePnpmLockInvalid(t *testing.T) { invalid := map[string]string{ - "empty": "", - "not yaml": "a: b: c: [", - "not a mapping": "- a\n", - "unrelated yaml": "name: portal\n", - "packages is list": "packages:\n - a\n", - "unbalanced peers": "packages:\n 'a@1.0.0(b@1.0.0': {}\n", + "empty": "", + "not yaml": "a: b: c: [", + "not a mapping": "- a\n", + "unrelated yaml": "name: portal\n", + "packages is list": "packages:\n - a\n", + "unbalanced peers": "packages:\n 'a@1.0.0(b@1.0.0': {}\n", + "two lock documents": "---\n" + pnpmV9Before + "---\n" + pnpmV9Before, + "a document that is not a mapping": pnpmEnvironmentDocument + "---\n- a\n", } for name, content := range invalid { t.Run(name, func(t *testing.T) { @@ -461,3 +463,50 @@ func newTestContext(path string) *util.FileContext { return context } + +// pnpmEnvironmentDocument is the first document of a pnpm 11+ lock file. It lists pnpm itself. +const pnpmEnvironmentDocument = `--- +lockfileVersion: '9.0' + +importers: + + .: + configDependencies: {} + packageManagerDependencies: + pnpm: + specifier: 12.18.0 + version: 12.18.0 + +packages: + + pnpm@12.18.0: + resolution: {integrity: sha512-x} + hasBin: true + +snapshots: + + pnpm@12.18.0: {} +` + +func TestSanitizePnpmLockUsesTheLockFileDocument(t *testing.T) { + cases := map[string]string{ + "one document": pnpmV9Before, + "one document with a marker": "---\n" + pnpmV9Before, + "environment document before the lock": pnpmEnvironmentDocument + "---\n" + pnpmV9Before, + } + for name, content := range cases { + t.Run(name, func(t *testing.T) { + sanitized, err := sanitizePnpmLock([]byte(content), newTestContext("pnpm-lock.yaml")) + + assert.NoError(t, err) + assert.Equal(t, pnpmV9After, string(sanitized)) + }) + } +} + +func TestSanitizePnpmLockFailsWithOnlyTheEnvironmentDocument(t *testing.T) { + _, err := sanitizePnpmLock([]byte(pnpmEnvironmentDocument), newTestContext("pnpm-lock.yaml")) + + assert.ErrorIs(t, err, util.ErrNoLockDocument) + assert.Equal(t, util.ErrNoLockDocument.Error(), util.Reason(err)) +} diff --git a/internal/sanitize/pm/util/context.go b/internal/sanitize/pm/util/context.go index 7fef6c64..69fa2951 100644 --- a/internal/sanitize/pm/util/context.go +++ b/internal/sanitize/pm/util/context.go @@ -9,6 +9,25 @@ import ( // contents, and those must not reach the output. var ErrInvalidFormat = errors.New("content is not valid for this file type") +// ErrNoLockDocument is for a pnpm lock file that holds only pnpm's own environment document. +var ErrNoLockDocument = errors.New("the file has no lock file document, only pnpm's environment document") + +// ErrUnsupportedVersion is for a version of a file format that sanitize doesn't handle. The file +// is skipped rather than failed, and no copy of it is written. +var ErrUnsupportedVersion = errors.New("this version of the file format is not supported by sanitize") + +// Reason returns the message to report for an error from a FileSanitizer. Only these fixed +// messages can reach the output, never the text of an underlying error. +func Reason(err error) string { + for _, known := range []error{ErrNoLockDocument, ErrUnsupportedVersion} { + if errors.Is(err, known) { + return known.Error() + } + } + + return ErrInvalidFormat.Error() +} + // FileSanitizer returns the sanitized content of one file, or ErrInvalidFormat. type FileSanitizer func(content []byte, context *FileContext) ([]byte, error) diff --git a/internal/sanitize/pm/util/mask.go b/internal/sanitize/pm/util/mask.go index 47a41b51..e8834e16 100644 --- a/internal/sanitize/pm/util/mask.go +++ b/internal/sanitize/pm/util/mask.go @@ -19,6 +19,9 @@ const ( MaskedPatch = "patch:redacted" MaskedUnknown = "redacted" yarnBuiltinPatchToken = "optional!builtin" + patchProtocol = "patch:" + maskedPatchFileName = "redacted.patch" + maskedPatchSource = "redacted" ) var ( @@ -29,6 +32,8 @@ var ( gitShorthandRegex = regexp.MustCompile(`^[\w.\-]+/[\w.\-]+(?:#.*)?$`) wordOnlyRegex = regexp.MustCompile(`^\w+$`) patchLocatorRegex = regexp.MustCompile(`&?locator=[^&]*`) + // packageNameRegex matches an npm package name, scoped or not, and nothing shaped like a path. + packageNameRegex = regexp.MustCompile(`^(?:@[\w.\-]+/)?[\w.\-]+$`) ) var publicRegistryHosts = map[string]bool{ @@ -86,12 +91,13 @@ func MatchesUnsupportedProtocol(value string) bool { if isBarePath(value) { return false } - switch MaskValue(value) { + masked := MaskValue(value) + switch masked { case MaskedGitWord, MaskedGitWordNoUser, MaskedLocalDot, MaskedPatchFile: return true } - return false + return strings.HasPrefix(masked, patchProtocol) && strings.HasSuffix(masked, "#"+maskedPatchFileName) } func isPublicRegistryURL(value string) bool { @@ -116,11 +122,24 @@ func maskWorkspace(value string) string { return MaskedWorkspace } +// maskPatch keeps the descriptor of the patched package, `patch:@#`, and +// masks only the patch file. The backend reads the patched package from that descriptor, so +// without it the package and its dependencies change in the scan result. The range inside is +// masked by the same rules as any other value, so a private source can't stay just because a +// patch wraps it. func maskPatch(value string) string { - switch { - case strings.Contains(value, yarnBuiltinPatchToken): + if strings.Contains(value, yarnBuiltinPatchToken) { // Built-in patches hold no customer data, apart from a locator naming the project. return patchLocatorRegex.ReplaceAllString(value, "") + } + + descriptor, patchFile, found := strings.Cut(strings.TrimPrefix(value, patchProtocol), "#") + maskedDescriptor, valid := maskPatchedDescriptor(descriptor) + switch { + case found && valid && strings.Contains(patchFile, ".patch"): + return patchProtocol + maskedDescriptor + "#" + maskedPatchFileName + case found && valid: + return patchProtocol + maskedDescriptor + "#" + maskedPatchSource case strings.Contains(value, ".patch"): return MaskedPatchFile } @@ -128,6 +147,30 @@ func maskPatch(value string) string { return MaskedPatch } +// maskPatchedDescriptor takes the URL-encoded `@` of a patched package. A range that +// masking doesn't change keeps its original encoding. +func maskPatchedDescriptor(descriptor string) (string, bool) { + decoded, err := url.PathUnescape(descriptor) + if err != nil || len(decoded) < 2 { + return "", false + } + index := strings.Index(decoded[1:], "@") + if index < 0 { + return "", false + } + name, versionRange := decoded[:index+1], decoded[index+2:] + if !packageNameRegex.MatchString(name) { + return "", false + } + + masked := MaskValue(versionRange) + if masked == versionRange { + return descriptor, true + } + + return name + "@" + strings.NewReplacer(":", "%3A", "#", "%23").Replace(masked), true +} + func CutLocalProtocol(value string) (string, bool) { for _, protocol := range localProtocols { if rest, found := strings.CutPrefix(value, protocol); found { diff --git a/internal/sanitize/pm/util/mask_test.go b/internal/sanitize/pm/util/mask_test.go index ed0d85a6..14de610c 100644 --- a/internal/sanitize/pm/util/mask_test.go +++ b/internal/sanitize/pm/util/mask_test.go @@ -54,10 +54,19 @@ func TestMaskValue(t *testing.T) { {"workspace dot", "workspace:.", "workspace:."}, {"workspace path", "workspace:packages/shared-utils", MaskedWorkspace}, - {"patch file", "patch:foo@npm%3A1.0.0#./.yarn/patches/foo.patch", MaskedPatchFile}, + {"patch file", "patch:foo@npm%3A1.0.0#./.yarn/patches/foo.patch", "patch:foo@npm%3A1.0.0#redacted.patch"}, + {"patch file in the yarn home", "patch:@rollup/plugin-commonjs@npm%3A29.0.2#~/.yarn/patches/@rollup-plugin-commonjs-npm-29.0.2-18c3a497d8.patch", "patch:@rollup/plugin-commonjs@npm%3A29.0.2#redacted.patch"}, + {"patch of a caret range", "patch:foo@npm%3A^1.0.0#./foo.patch", "patch:foo@npm%3A^1.0.0#redacted.patch"}, + {"patch of a git source", "patch:foo@https%3A//github.com/acme/foo.git%23commit=abc#./foo.patch", "patch:foo@git+ssh%3A//redacted/redacted.git%23redacted#redacted.patch"}, + {"patch of a file source", "patch:foo@file%3A../vendor/foo#./foo.patch", "patch:foo@file%3A./redacted#redacted.patch"}, + {"patch of a private registry", "patch:foo@https%3A//npm.acme.internal/foo-1.0.0.tgz#./foo.patch", "patch:foo@https%3A//redacted.invalid/redacted.tgz#redacted.patch"}, + {"patch without a package name", "patch:../x@npm%3A1.0.0#./x.patch", MaskedPatchFile}, + {"patch with bad encoding", "patch:foo@npm%ZZ#./x.patch", MaskedPatchFile}, + {"patch without a range", "patch:foo#./x.patch", MaskedPatchFile}, + {"patch without a source", "patch:foo@npm%3A1.0.0", MaskedPatch}, {"yarn builtin patch", "patch:typescript@npm%3A5.0.0#optional!builtin", "patch:typescript@npm%3A5.0.0#optional!builtin"}, {"yarn builtin patch naming the project", "patch:x@npm%3A1#optional!builtin::version=1&hash=a&locator=%40acme%2Fportal%40workspace%3A.", "patch:x@npm%3A1#optional!builtin::version=1&hash=a"}, - {"other patch", "patch:foo@npm%3A1.0.0#./internal/fix", MaskedPatch}, + {"other patch", "patch:foo@npm%3A1.0.0#./internal/fix", "patch:foo@npm%3A1.0.0#redacted"}, {"unknown protocol", "svn://svn.acme.internal/repo", MaskedUnknown}, } @@ -73,6 +82,7 @@ func TestMatchesUnsupportedProtocol(t *testing.T) { assert.True(t, MatchesUnsupportedProtocol("git+ssh://git@git.acme.internal/platform/authclient.git#v1")) assert.True(t, MatchesUnsupportedProtocol("file:../x")) assert.True(t, MatchesUnsupportedProtocol("patch:foo#./x.patch")) + assert.True(t, MatchesUnsupportedProtocol("patch:foo@npm%3A1.0.0#./x.patch")) assert.False(t, MatchesUnsupportedProtocol("git+ssh://git@git.acme.internal/platform/auth-client.git#v1")) assert.False(t, MatchesUnsupportedProtocol("file:x")) diff --git a/internal/sanitize/pm/util/yaml_nodes.go b/internal/sanitize/pm/util/yaml_nodes.go index 4b080b46..891111eb 100644 --- a/internal/sanitize/pm/util/yaml_nodes.go +++ b/internal/sanitize/pm/util/yaml_nodes.go @@ -1,19 +1,44 @@ package util -import "gopkg.in/yaml.v3" +import ( + "bytes" + "errors" + "io" -// ParseYAMLMapping returns the top-level mapping of a YAML document with exactly one document. + "gopkg.in/yaml.v3" +) + +// ParseYAMLMapping returns the top-level mapping of a file with exactly one YAML document. A file +// with more documents fails, rather than having all but the first silently dropped. func ParseYAMLMapping(content []byte) (*yaml.Node, error) { - var document yaml.Node - if err := yaml.Unmarshal(content, &document); err != nil || len(document.Content) != 1 { + documents, err := ParseYAMLMappings(content) + if err != nil || len(documents) != 1 { return nil, ErrInvalidFormat } - root := document.Content[0] - if root.Kind != yaml.MappingNode { + + return documents[0], nil +} + +// ParseYAMLMappings returns the top-level mapping of each document in a file, in order. +func ParseYAMLMappings(content []byte) ([]*yaml.Node, error) { + decoder := yaml.NewDecoder(bytes.NewReader(content)) + var mappings []*yaml.Node + for { + var document yaml.Node + err := decoder.Decode(&document) + if errors.Is(err, io.EOF) { + break + } + if err != nil || len(document.Content) != 1 || document.Content[0].Kind != yaml.MappingNode { + return nil, ErrInvalidFormat + } + mappings = append(mappings, document.Content[0]) + } + if len(mappings) == 0 { return nil, ErrInvalidFormat } - return root, nil + return mappings, nil } // ForEachYAMLPair visits the pairs of a mapping that have a scalar key, in order. diff --git a/internal/sanitize/pm/util/yaml_nodes_test.go b/internal/sanitize/pm/util/yaml_nodes_test.go new file mode 100644 index 00000000..80968383 --- /dev/null +++ b/internal/sanitize/pm/util/yaml_nodes_test.go @@ -0,0 +1,33 @@ +package util + +import ( + "errors" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestParseYAMLMappingRejectsSeveralDocuments(t *testing.T) { + _, err := ParseYAMLMapping([]byte("a: 1\n---\nb: 2\n")) + + assert.ErrorIs(t, err, ErrInvalidFormat) +} + +func TestParseYAMLMappings(t *testing.T) { + documents, err := ParseYAMLMappings([]byte("---\na: 1\n---\nb: 2\n")) + + assert.NoError(t, err) + assert.Len(t, documents, 2) + assert.Equal(t, "b", documents[1].Content[0].Value) + + for _, invalid := range []string{"", "a: [", "a: 1\n---\n- b\n"} { + _, err = ParseYAMLMappings([]byte(invalid)) + assert.ErrorIs(t, err, ErrInvalidFormat, invalid) + } +} + +func TestReasonReportsOnlyFixedMessages(t *testing.T) { + assert.Equal(t, ErrNoLockDocument.Error(), Reason(ErrNoLockDocument)) + assert.Equal(t, ErrUnsupportedVersion.Error(), Reason(ErrUnsupportedVersion)) + assert.Equal(t, ErrInvalidFormat.Error(), Reason(errors.New("line 3: s3cret"))) +} diff --git a/internal/sanitize/pm/yarn/yarn_lock_test.go b/internal/sanitize/pm/yarn/yarn_lock_test.go index 8cc681b4..84d9b0e4 100644 --- a/internal/sanitize/pm/yarn/yarn_lock_test.go +++ b/internal/sanitize/pm/yarn/yarn_lock_test.go @@ -156,3 +156,20 @@ func newTestContext(path string) *util.FileContext { return context } + +func TestSanitizeYarnLockKeepsThePatchedDescriptor(t *testing.T) { + const patch = "patch:interpret@npm%3A3.1.1#~/.yarn/patches/interpret-npm-3.1.1-715bac2bd7.patch" + const masked = "patch:interpret@npm%3A3.1.1#redacted.patch" + content := "\"app@workspace:.\":\n version: 0.0.0-use.local\n dependencies:\n interpret: \"" + patch + "\"\n\n" + + "\"interpret@" + patch + ", interpret@patch:interpret@npm%3A^2.2.0#~/.yarn/patches/interpret-npm-3.1.1-715bac2bd7.patch\":\n" + + " version: 3.1.1\n\n" + + "\"fsevents@patch:fsevents@npm%3A^2.3.2#optional!builtin\":\n version: 2.3.3\n" + + sanitized, err := sanitizeYarnLock([]byte(content), newTestContext("yarn.lock")) + + assert.NoError(t, err) + assert.Equal(t, "\"debricked-redacted-project-1@workspace:.\":\n version: 0.0.0-use.local\n dependencies:\n interpret: \""+masked+"\"\n\n"+ + "\"interpret@"+masked+", interpret@patch:interpret@npm%3A^2.2.0#redacted.patch\":\n version: 3.1.1\n\n"+ + "\"fsevents@patch:fsevents@npm%3A^2.3.2#optional!builtin\":\n version: 2.3.3\n", string(sanitized)) + assert.Equal(t, masked, util.MaskValue(patch), "package.json gets the same value through MaskValue") +} diff --git a/internal/sanitize/sanitize.go b/internal/sanitize/sanitize.go index 5e7544c5..c4399de4 100644 --- a/internal/sanitize/sanitize.go +++ b/internal/sanitize/sanitize.go @@ -2,6 +2,7 @@ package sanitize import ( + "errors" "fmt" "io/fs" "maps" @@ -25,6 +26,7 @@ const ( reasonNotSupported = "format is not supported by sanitize" reasonNoLockFile = "manifest has no supported lock file to go with it" + reasonLockFailed = "its lock file could not be sanitized" ) // Lock files and manifests are kept apart because a manifest is only useful with a lock file next @@ -179,12 +181,7 @@ func (r *run) processGroup(group file.Group) { sanitizedManifest := "" if group.HasFile() { - sanitizer := sanitizerFor(manifestSanitizers, group.ManifestFile) - if sanitizer != nil && scope == nil { - r.skip(group.ManifestFile, reasonNoLockFile) - } else { - sanitizedManifest = r.processFile(group.ManifestFile, sanitizer, scope) - } + sanitizedManifest = r.processManifest(group.ManifestFile, scope, len(sanitizedLockFiles) > 0) } if len(sanitizedLockFiles) > 0 { @@ -192,6 +189,24 @@ func (r *run) processGroup(group file.Group) { } } +// processManifest copies a manifest only together with a lock file, because the backend can't use +// it alone. If its lock file failed, the whole project is left out of the copies. +func (r *run) processManifest(path string, scope *util.ProjectScope, hasLockFile bool) string { + sanitizer := sanitizerFor(manifestSanitizers, path) + switch { + case sanitizer == nil: + return r.processFile(path, nil, scope) + case scope == nil: + r.skip(path, reasonNoLockFile) + case !hasLockFile: + r.skip(path, reasonLockFailed) + default: + return r.processFile(path, sanitizer, scope) + } + + return "" +} + // newScopeIfHandled returns nil for a group with no lock file that sanitize can handle. func (r *run) newScopeIfHandled(group file.Group) *util.ProjectScope { for _, lockFile := range group.LockFiles { @@ -226,8 +241,13 @@ func (r *run) processFile(path string, sanitizer util.FileSanitizer, scope *util return "" } sanitized, err := sanitizer(content, util.NewFileContext(scope, relativePath)) - if err != nil { - r.fail(path, util.ErrInvalidFormat.Error()) + switch { + case errors.Is(err, util.ErrUnsupportedVersion): + r.skip(path, util.Reason(err)) + + return "" + case err != nil: + r.fail(path, util.Reason(err)) return "" } diff --git a/internal/sanitize/sanitize_test.go b/internal/sanitize/sanitize_test.go index 8074fb3e..9abf1912 100644 --- a/internal/sanitize/sanitize_test.go +++ b/internal/sanitize/sanitize_test.go @@ -355,6 +355,41 @@ func TestSanitizeNeverWritesAFileThatFailed(t *testing.T) { assert.FileExists(t, filepath.Join(result.OutputDir, "good/yarn.lock")) } +func TestSanitizeWritesNothingForAProjectWhoseLockFileFailed(t *testing.T) { + root := t.TempDir() + manifest := writeFixture(t, root, "web/package.json", fixtures.PackageJSONBefore) + lockFile := writeFixture(t, root, "web/package-lock.json", "{corrupt") + + result := sanitizeGroups(t, root, file.NewGroup(manifest, nil, []string{lockFile})) + + require.Len(t, result.Failed, 1) + assert.Equal(t, lockFile, result.Failed[0].Path) + assert.Equal(t, []FileIssue{{Path: manifest, Reason: reasonLockFailed}}, result.Skipped) + assert.Empty(t, result.Groups) + assert.NoDirExists(t, filepath.Join(result.OutputDir, "web")) +} + +func TestSanitizeSkipsAnUnsupportedVersionWithoutFailing(t *testing.T) { + root := t.TempDir() + v2 := writeFixture(t, root, "java/maven_install.json", `{"version": "2", "artifacts": {"a:b": {"version": "1"}}}`) + + result := sanitizeGroups(t, root, file.NewGroup("", nil, []string{v2})) + + assert.Empty(t, result.Failed) + assert.Equal(t, []FileIssue{{Path: v2, Reason: util.ErrUnsupportedVersion.Error()}}, result.Skipped) + assert.NoFileExists(t, filepath.Join(result.OutputDir, "java/maven_install.json")) +} + +func TestSanitizeReportsAPnpmLockFileWithOnlyTheEnvironmentDocument(t *testing.T) { + root := t.TempDir() + lockFile := writeFixture(t, root, "pnpm-lock.yaml", "lockfileVersion: '9.0'\nimporters:\n .:\n configDependencies: {}\n") + + result := sanitizeGroups(t, root, file.NewGroup("", nil, []string{lockFile})) + + assert.Equal(t, []FileIssue{{Path: lockFile, Reason: util.ErrNoLockDocument.Error()}}, result.Failed) + assert.NoFileExists(t, filepath.Join(result.OutputDir, "pnpm-lock.yaml")) +} + func TestSanitizeClearsOnlyTheOutputDirectory(t *testing.T) { root := t.TempDir() stale := writeFixture(t, root, ".debricked/sanitized/old/yarn.lock", "stale")