From 373d9ecd1b0c462137093d11838d753ba3176f90 Mon Sep 17 00:00:00 2001 From: Gauri Yadav Date: Tue, 10 Nov 2026 08:49:39 +0530 Subject: [PATCH 1/2] XRAY-163629 - Ensuring server url in npmrc is same as set by jf c add before embedding any auth creds --- commands/curation/curationaudit.go | 41 ++++------ commands/curation/curationaudit_test.go | 76 +++++++++++++++++++ sca/bom/buildinfo/technologies/pnpm/pnpm.go | 57 +++++++++++++- .../buildinfo/technologies/pnpm/pnpm_test.go | 59 ++++++++++++++ 4 files changed, 204 insertions(+), 29 deletions(-) diff --git a/commands/curation/curationaudit.go b/commands/curation/curationaudit.go index b98505412..f1ad2600b 100644 --- a/commands/curation/curationaudit.go +++ b/commands/curation/curationaudit.go @@ -1905,30 +1905,28 @@ func validateRunNativeForTech(tech techutils.Technology, runNative bool) error { tech.String(), tech.String()) } -// setRepoFromNpmrc builds PackageManagerConfig by reading the npm registry URL from the -// native npm configuration (respecting .npmrc and Volta), then parsing the Artifactory -// base URL and repository name from it. -// Authentication is taken from the jfrog-cli.conf server entry (via ca.ServerDetails()) — -// the same credentials the user configured with 'jf c'. Only the Artifactory URL and -// repository name are sourced from .npmrc, so 'jf npm-config' is not required. +// setRepoFromNpmrc reads the registry URL from the native npm config (.npmrc/Volta); credentials come from the .npmrc token, else from 'jf c' only if the host matches. func (ca *CurationAuditCommand) setRepoFromNpmrc() error { registryConfig, err := npmtech.GetNativeNpmRegistryConfig() if err != nil { return fmt.Errorf("--run-native: failed to read Artifactory details from .npmrc: %w", err) } - // Use auth from the jfrog server config (jfrog-cli.conf) — it holds properly stored - // credentials. Only override the ArtifactoryUrl with what .npmrc reports so the - // Curation HEAD requests go to the right repository. - serverDetails, err := ca.ServerDetails() - if err != nil || serverDetails == nil { - // No server configured — fall back to whatever auth .npmrc provides. + // .npmrc is untrusted: use its own token, else reuse 'jf c' credentials only if the host matches (credentialFallbackServerDetails). + var serverDetails *config.ServerDetails + if registryConfig.AuthToken != "" { serverDetails = &config.ServerDetails{ ArtifactoryUrl: registryConfig.ArtifactoryUrl, AccessToken: registryConfig.AuthToken, } + } else if base, sdErr := ca.ServerDetails(); sdErr != nil || base == nil { + // No server configured and no token in .npmrc. + serverDetails = &config.ServerDetails{ArtifactoryUrl: registryConfig.ArtifactoryUrl} } else { - serverDetails.ArtifactoryUrl = registryConfig.ArtifactoryUrl + serverDetails, err = ca.credentialFallbackServerDetails("npm", ".npmrc", registryConfig.ArtifactoryUrl) + if err != nil { + return err + } } repoConfig := (&project.RepositoryConfig{}). @@ -1994,14 +1992,7 @@ func (ca *CurationAuditCommand) setRepoFromNuGetSource() error { return nil } -// setRepoFromNpmrcForPnpm reads Artifactory connection details from the project's .npmrc -// via the pnpm CLI. pnpm uses the same .npmrc format and registry protocol as npm, so the -// URL parsing logic is identical. This is always called for pnpm — there is no 'jf pnpm-config'. -// -// Auth priority: -// 1. Token from .npmrc — preferred, because it is scoped to the exact registry URL. -// 2. Token from 'jf c' server config — used as fallback when .npmrc carries no token -// (e.g. user relies on a jf-managed credential store). +// setRepoFromNpmrcForPnpm reads the registry URL from the project's .npmrc via pnpm (no 'jf pnpm-config' exists); credentials come from the .npmrc token, else from 'jf c' only if the host matches. func (ca *CurationAuditCommand) setRepoFromNpmrcForPnpm() error { registryConfig, err := pnpmtech.GetNativePnpmRegistryConfig() if err != nil { @@ -2021,11 +2012,11 @@ func (ca *CurationAuditCommand) setRepoFromNpmrcForPnpm() error { // No token in .npmrc — fall back to whatever 'jf c' has stored, overriding // only the Artifactory URL so requests go to the correct registry. log.Debug("pnpm: no token in .npmrc — using 'jf c' server credentials") - serverDetails, err = ca.ServerDetails() - if err != nil || serverDetails == nil { - return fmt.Errorf("pnpm: no auth token found in .npmrc and no 'jf c' server configured: %w", err) + // credentialFallbackServerDetails refuses a different scheme/host and copies instead of mutating the shared struct. + serverDetails, err = ca.credentialFallbackServerDetails("pnpm", ".npmrc", registryConfig.ArtifactoryUrl) + if err != nil { + return err } - serverDetails.ArtifactoryUrl = registryConfig.ArtifactoryUrl } repoConfig := (&project.RepositoryConfig{}). diff --git a/commands/curation/curationaudit_test.go b/commands/curation/curationaudit_test.go index 8809b99db..de30418bb 100644 --- a/commands/curation/curationaudit_test.go +++ b/commands/curation/curationaudit_test.go @@ -7599,3 +7599,79 @@ registry = "sparse+%s/api/cargo/cargo-test-repo/index/" } assert.Equal(t, expected, results) } + +// writeNpmrcProject creates a project dir whose .npmrc declares registryUrl (no token) and chdirs into it. +func writeNpmrcProject(t *testing.T, registryUrl string) { + t.Setenv("HOME", t.TempDir()) + projectDir := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(projectDir, "package.json"), []byte(`{"name":"npmrc-hostcheck-test","version":"1.0.0"}`), 0644)) + require.NoError(t, os.WriteFile(filepath.Join(projectDir, ".npmrc"), []byte("registry="+registryUrl+"\n"), 0644)) + prevWd, err := os.Getwd() + require.NoError(t, err) + require.NoError(t, os.Chdir(projectDir)) + t.Cleanup(func() { clienttestutils.ChangeDirAndAssert(t, prevWd) }) +} + +func newConfiguredServerCommand() *CurationAuditCommand { + ca := NewCurationAuditCommand() + ca.SetServerDetails(&config.ServerDetails{ + Url: "https://configured-server.example.com/", + ArtifactoryUrl: "https://configured-server.example.com/artifactory/", + AccessToken: "super-secret-token", + }) + return ca +} + +// TestSetRepoFromNpmrcRejectsHostMismatch: with --run-native, a tokenless .npmrc on another host must never get 'jf c' credentials. +func TestSetRepoFromNpmrcRejectsHostMismatch(t *testing.T) { + writeNpmrcProject(t, "https://attacker.example.com/artifactory/api/npm/npm-test-repo/") + ca := newConfiguredServerCommand() + + setErr := ca.setRepoFromNpmrc() + + require.Error(t, setErr) + assert.Contains(t, setErr.Error(), "does not match") + assert.Nil(t, ca.PackageManagerConfig, "credentials must not be attached to the mismatched host") + sd, err := ca.ServerDetails() + require.NoError(t, err) + assert.Equal(t, "https://configured-server.example.com/artifactory/", sd.ArtifactoryUrl, "shared ServerDetails must not be mutated") +} + +// TestSetRepoFromNpmrcAcceptsMatchingHost: the legitimate same-host case still falls back to the 'jf c' credentials. +func TestSetRepoFromNpmrcAcceptsMatchingHost(t *testing.T) { + writeNpmrcProject(t, "https://configured-server.example.com/artifactory/api/npm/npm-test-repo/") + ca := newConfiguredServerCommand() + + require.NoError(t, ca.setRepoFromNpmrc()) + require.NotNil(t, ca.PackageManagerConfig) + pmSd, sdErr := ca.PackageManagerConfig.ServerDetails() + require.NoError(t, sdErr) + assert.Equal(t, "super-secret-token", pmSd.AccessToken) +} + +// TestSetRepoFromNpmrcForPnpmRejectsHostMismatch: pnpm equivalent of the npm test above. +func TestSetRepoFromNpmrcForPnpmRejectsHostMismatch(t *testing.T) { + writeNpmrcProject(t, "https://attacker.example.com/artifactory/api/npm/pnpm-test-repo/") + ca := newConfiguredServerCommand() + + setErr := ca.setRepoFromNpmrcForPnpm() + + require.Error(t, setErr) + assert.Contains(t, setErr.Error(), "does not match") + assert.Nil(t, ca.PackageManagerConfig, "credentials must not be attached to the mismatched host") + sd, err := ca.ServerDetails() + require.NoError(t, err) + assert.Equal(t, "https://configured-server.example.com/artifactory/", sd.ArtifactoryUrl, "shared ServerDetails must not be mutated") +} + +// TestSetRepoFromNpmrcForPnpmAcceptsMatchingHost: same-host fallback to 'jf c' credentials keeps working. +func TestSetRepoFromNpmrcForPnpmAcceptsMatchingHost(t *testing.T) { + writeNpmrcProject(t, "https://configured-server.example.com/artifactory/api/npm/pnpm-test-repo/") + ca := newConfiguredServerCommand() + + require.NoError(t, ca.setRepoFromNpmrcForPnpm()) + require.NotNil(t, ca.PackageManagerConfig) + pmSd, sdErr := ca.PackageManagerConfig.ServerDetails() + require.NoError(t, sdErr) + assert.Equal(t, "super-secret-token", pmSd.AccessToken) +} diff --git a/sca/bom/buildinfo/technologies/pnpm/pnpm.go b/sca/bom/buildinfo/technologies/pnpm/pnpm.go index c62c4f4de..56b0dc33c 100644 --- a/sca/bom/buildinfo/technologies/pnpm/pnpm.go +++ b/sca/bom/buildinfo/technologies/pnpm/pnpm.go @@ -4,6 +4,8 @@ import ( "encoding/json" "errors" "fmt" + "net" + "net/url" "os" "os/exec" "path/filepath" @@ -115,6 +117,7 @@ func curationNoLockfileError(params technologies.BuildInfoBomGeneratorParams, wo if strings.Contains(resolveErr.Error(), pnpmCvsBlockedVersionMarker) && strings.Contains(resolveErr.Error(), pnpmCvsAffectedPackagesMarker) { return resolveErr // already names the exact blocked package(s); the probe below would only add noise } + skipProbe := false // only populated for pnpm on the success path (setRepoFromNpmrcForPnpm runs after GetTechDependencyTree returns), so resolve it ourselves here on this failure path. if params.DependenciesRepository == "" { if registryConfig, regErr := GetNativePnpmRegistryConfig(); regErr == nil { @@ -126,10 +129,16 @@ func curationNoLockfileError(params technologies.BuildInfoBomGeneratorParams, wo AccessToken: registryConfig.AuthToken, } } else if params.ServerDetails != nil { - // copy before mutating: params.ServerDetails may be the shared struct ca.ServerDetails() returns, and overwriting its URL in place would leak to other techs in a multi-tech audit. - copied := *params.ServerDetails - copied.ArtifactoryUrl = registryConfig.ArtifactoryUrl - params.ServerDetails = &copied + if !sameRegistryHost(params.ServerDetails.ArtifactoryUrl, registryConfig.ArtifactoryUrl) { + // .npmrc is untrusted project content: never send the 'jf c' credentials to a different scheme/host. + log.Warn(fmt.Sprintf("pnpm curation probe: the registry declared in .npmrc (%s) does not match the configured 'jf c' server (%s) — skipping the probe to avoid sending its credentials to a different host.", redactedRegistryUrl(registryConfig.ArtifactoryUrl), redactedRegistryUrl(params.ServerDetails.ArtifactoryUrl))) + skipProbe = true + } else { + // copy before mutating: params.ServerDetails may be the shared struct ca.ServerDetails() returns, and overwriting its URL in place would leak to other techs in a multi-tech audit. + copied := *params.ServerDetails + copied.ArtifactoryUrl = registryConfig.ArtifactoryUrl + params.ServerDetails = &copied + } } } else { log.Debug(fmt.Sprintf("pnpm curation probe: failed to read Artifactory repository from .npmrc: %s", regErr.Error())) @@ -139,6 +148,9 @@ func curationNoLockfileError(params technologies.BuildInfoBomGeneratorParams, wo if memberRel == "." { memberRel = "" } + if skipProbe { + return errorutils.CheckErrorf("'jf curation-audit' could not produce 'pnpm-lock.yaml' — 'pnpm install --lockfile-only' failed, and the direct dependencies were not probed because the registry declared in .npmrc does not match the configured 'jf c' server. Align the two (or select the matching server with --server-id) and re-run 'jf ca'. Underlying pnpm error: %s", resolveErr.Error()) + } probed, totalProbed := probeBlockedPnpmDirectDeps(params, workspaceRoot, memberRel) outputRef := string(outFormat.Table) if params.OutputFormat == outFormat.Json { @@ -157,6 +169,43 @@ func curationNoLockfileError(params technologies.BuildInfoBomGeneratorParams, wo len(probed), outputRef, outputRef, resolveErr.Error()) } +// sameRegistryHost reports whether both URLs share the same scheme and host:port (paths ignored, default ports normalized). +func sameRegistryHost(configuredUrl, discoveredUrl string) bool { + configured, err := url.Parse(configuredUrl) + if err != nil || configured.Host == "" { + return false + } + discovered, err := url.Parse(discoveredUrl) + if err != nil || discovered.Host == "" { + return false + } + return strings.EqualFold(configured.Scheme, discovered.Scheme) && strings.EqualFold(effectiveHostPort(configured), effectiveHostPort(discovered)) +} + +// effectiveHostPort returns host:port with the scheme's default port (80/443) filled in when absent. +func effectiveHostPort(u *url.URL) string { + port := u.Port() + if port == "" { + switch strings.ToLower(u.Scheme) { + case "https": + port = "443" + case "http": + port = "80" + } + } + return net.JoinHostPort(strings.ToLower(u.Hostname()), port) +} + +// redactedRegistryUrl drops any userinfo (including username-only tokens) so credentials are never logged. +func redactedRegistryUrl(raw string) string { + u, err := url.Parse(raw) + if err != nil { + return "" + } + u.User = nil + return u.String() +} + // probeBlockedPnpmDirectDeps delegates to the shared probe mechanism yarn's fallback also uses; workspaceMemberRel, when non-empty, scopes it to one workspace member. func probeBlockedPnpmDirectDeps(params technologies.BuildInfoBomGeneratorParams, curWd, workspaceMemberRel string) ([]npm.BlockedDirectDep, int) { declared := collectDeclaredPnpmDirectDeps(curWd, workspaceMemberRel) diff --git a/sca/bom/buildinfo/technologies/pnpm/pnpm_test.go b/sca/bom/buildinfo/technologies/pnpm/pnpm_test.go index e145c3f96..ad82265bc 100644 --- a/sca/bom/buildinfo/technologies/pnpm/pnpm_test.go +++ b/sca/bom/buildinfo/technologies/pnpm/pnpm_test.go @@ -5,16 +5,20 @@ import ( "errors" "fmt" "net/http" + "net/http/httptest" "os" + "os/exec" "path/filepath" "sort" "strings" + "sync/atomic" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" coreCommonTests "github.com/jfrog/jfrog-cli-core/v2/common/tests" + "github.com/jfrog/jfrog-cli-core/v2/utils/config" "github.com/jfrog/jfrog-cli-core/v2/utils/coreutils" "github.com/jfrog/jfrog-cli-core/v2/utils/tests" "github.com/jfrog/jfrog-client-go/utils/io/fileutils" @@ -878,3 +882,58 @@ func TestIsCurationInstallFailure(t *testing.T) { assert.Nil(t, installErr) }) } + +// Pins the fix: when .npmrc names a different host than the configured 'jf c' server (and has no token), the failed-lockfile probe must not send any request there. +func TestCurationNoLockfileErrorSkipsProbeOnHostMismatch(t *testing.T) { + if _, lookErr := exec.LookPath("pnpm"); lookErr != nil { + t.Skip("pnpm is not on PATH") + } + var requests int32 + attacker := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + atomic.AddInt32(&requests, 1) + w.WriteHeader(http.StatusForbidden) + })) + defer attacker.Close() + + t.Setenv("HOME", t.TempDir()) + for _, envKey := range []string{"NPM_CONFIG_REGISTRY", "npm_config_registry"} { + t.Setenv(envKey, "") + require.NoError(t, os.Unsetenv(envKey)) + } + workspaceRoot := t.TempDir() + require.NoError(t, os.WriteFile(filepath.Join(workspaceRoot, "package.json"), []byte(`{"name":"root","dependencies":{"lodash":"^4.0.0"}}`), 0o644)) + require.NoError(t, os.WriteFile(filepath.Join(workspaceRoot, ".npmrc"), []byte("registry="+attacker.URL+"/artifactory/api/npm/npm-repo/\n"), 0o644)) + prevWd, err := os.Getwd() + require.NoError(t, err) + require.NoError(t, os.Chdir(workspaceRoot)) + defer func() { require.NoError(t, os.Chdir(prevWd)) }() + + configured := &config.ServerDetails{ + ArtifactoryUrl: "https://configured-server.example.com/artifactory/", + AccessToken: "super-secret-token", + } + params := technologies.BuildInfoBomGeneratorParams{ServerDetails: configured} + resolveErr := errors.New("pnpm install failed") + + err = curationNoLockfileError(params, workspaceRoot, ".", resolveErr) + + require.Error(t, err) + assert.Contains(t, err.Error(), "were not probed because the registry declared in .npmrc does not match") + assert.Zero(t, atomic.LoadInt32(&requests), "no request (authenticated or not) may reach the host declared in .npmrc") + assert.Equal(t, "https://configured-server.example.com/artifactory/", configured.ArtifactoryUrl, "shared ServerDetails must not be mutated") +} + +func TestSameRegistryHost(t *testing.T) { + assert.True(t, sameRegistryHost("https://a.example.com/artifactory/", "https://A.example.com/artifactory/api/npm/r/")) + assert.False(t, sameRegistryHost("https://a.example.com/artifactory/", "http://a.example.com/artifactory/"), "scheme mismatch") + assert.False(t, sameRegistryHost("https://a.example.com/artifactory/", "https://b.example.com/artifactory/"), "host mismatch") + assert.False(t, sameRegistryHost("", "https://b.example.com/"), "empty configured URL") + assert.True(t, sameRegistryHost("https://a.example.com/artifactory/", "https://a.example.com:443/artifactory/api/npm/r/"), "default https port") + assert.True(t, sameRegistryHost("http://a.example.com:80/", "http://a.example.com/"), "default http port") + assert.False(t, sameRegistryHost("https://a.example.com/", "https://a.example.com:8443/"), "non-default port") +} + +func TestRedactedRegistryUrl(t *testing.T) { + assert.Equal(t, "https://a.example.com/artifactory/api/npm/r/", redactedRegistryUrl("https://secrettoken@a.example.com/artifactory/api/npm/r/")) + assert.Equal(t, "https://a.example.com/x", redactedRegistryUrl("https://user:pass@a.example.com/x")) +} From 584462b9a24958c7d8c86c717fac21b0e4b3f401 Mon Sep 17 00:00:00 2001 From: Gauri Yadav Date: Tue, 10 Nov 2026 11:36:38 +0530 Subject: [PATCH 2/2] XRAY-163629 - Check npmrc host matches jf c server before sending credentials --- commands/curation/curationaudit.go | 25 +-- commands/curation/curationaudit_test.go | 144 ++++++++++++------ sca/bom/buildinfo/technologies/pnpm/pnpm.go | 48 +----- .../buildinfo/technologies/pnpm/pnpm_test.go | 22 +-- utils/urls.go | 44 ++++++ utils/urls_test.go | 48 ++++++ 6 files changed, 202 insertions(+), 129 deletions(-) create mode 100644 utils/urls.go create mode 100644 utils/urls_test.go diff --git a/commands/curation/curationaudit.go b/commands/curation/curationaudit.go index f1ad2600b..37f040eb5 100644 --- a/commands/curation/curationaudit.go +++ b/commands/curation/curationaudit.go @@ -1933,7 +1933,7 @@ func (ca *CurationAuditCommand) setRepoFromNpmrc() error { SetTargetRepo(registryConfig.RepoName). SetServerDetails(serverDetails) ca.setPackageManagerConfig(repoConfig) - log.Info(fmt.Sprintf("--run-native: using Artifactory URL %q and repository %q from .npmrc", registryConfig.ArtifactoryUrl, registryConfig.RepoName)) + log.Info(fmt.Sprintf("--run-native: using Artifactory URL %q and repository %q from .npmrc", utils.RedactUrlUserinfo(registryConfig.ArtifactoryUrl), registryConfig.RepoName)) return nil } @@ -2023,7 +2023,7 @@ func (ca *CurationAuditCommand) setRepoFromNpmrcForPnpm() error { SetTargetRepo(registryConfig.RepoName). SetServerDetails(serverDetails) ca.setPackageManagerConfig(repoConfig) - log.Info(fmt.Sprintf("pnpm: using Artifactory URL %q and repository %q from .npmrc", registryConfig.ArtifactoryUrl, registryConfig.RepoName)) + log.Info(fmt.Sprintf("pnpm: using Artifactory URL %q and repository %q from .npmrc", utils.RedactUrlUserinfo(registryConfig.ArtifactoryUrl), registryConfig.RepoName)) return nil } @@ -2199,33 +2199,18 @@ func (ca *CurationAuditCommand) credentialFallbackServerDetails(tech, sourceDesc if sdErr != nil || base == nil { return nil, errorutils.CheckErrorf("%s: no 'jf c' server configured to source credentials for %s", tech, sourceDescription) } - if !sameArtifactoryHost(base.ArtifactoryUrl, discoveredArtifactoryUrl) { + if !utils.SameRegistryHost(base.ArtifactoryUrl, discoveredArtifactoryUrl) { return nil, errorutils.CheckErrorf( "%s: the Artifactory URL declared in %s (%s) does not match the configured 'jf c' "+ "server (%s) — refusing to send its credentials to a different host. "+ - "Align the two, or select the matching server with --server-id.", - tech, sourceDescription, discoveredArtifactoryUrl, base.ArtifactoryUrl) + "Align the two, or select the matching server with 'jf c use ' or JFROG_CLI_SERVER_ID.", + tech, sourceDescription, utils.RedactUrlUserinfo(discoveredArtifactoryUrl), utils.RedactUrlUserinfo(base.ArtifactoryUrl)) } copied := *base copied.ArtifactoryUrl = discoveredArtifactoryUrl return &copied, nil } -// sameArtifactoryHost reports whether configuredUrl and discoveredUrl share the same -// scheme and host[:port], ignoring path and trailing slashes. -func sameArtifactoryHost(configuredUrl, discoveredUrl string) bool { - configured, err := url.Parse(configuredUrl) - if err != nil || configured.Host == "" { - return false - } - discovered, err := url.Parse(discoveredUrl) - if err != nil || discovered.Host == "" { - return false - } - return strings.EqualFold(configured.Host, discovered.Host) && - strings.EqualFold(configured.Scheme, discovered.Scheme) -} - func (ca *CurationAuditCommand) getRepoParams(projectType project.ProjectType) (*project.RepositoryConfig, error) { configFilePath, exists, err := project.GetProjectConfFilePath(projectType) if err != nil { diff --git a/commands/curation/curationaudit_test.go b/commands/curation/curationaudit_test.go index de30418bb..cac0d2e31 100644 --- a/commands/curation/curationaudit_test.go +++ b/commands/curation/curationaudit_test.go @@ -7600,9 +7600,27 @@ registry = "sparse+%s/api/cargo/cargo-test-repo/index/" assert.Equal(t, expected, results) } +// skipIfPnpmUnusable skips on Windows (pnpm delegates 'config get registry' to npm via cmd.exe, unresolvable on the runner) or when pnpm is not on PATH. +func skipIfPnpmUnusable(t *testing.T) { + t.Helper() + if runtime.GOOS == "windows" { + t.Skip("pnpm config get registry delegates to npm via cmd.exe, which is not resolvable on the Windows runner") + } + if _, err := exec.LookPath("pnpm"); err != nil { + t.Skip("pnpm is not on PATH") + } +} + // writeNpmrcProject creates a project dir whose .npmrc declares registryUrl (no token) and chdirs into it. func writeNpmrcProject(t *testing.T, registryUrl string) { - t.Setenv("HOME", t.TempDir()) + t.Helper() + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + for _, envKey := range []string{"NPM_CONFIG_REGISTRY", "npm_config_registry"} { + t.Setenv(envKey, "") + require.NoError(t, os.Unsetenv(envKey)) + } projectDir := t.TempDir() require.NoError(t, os.WriteFile(filepath.Join(projectDir, "package.json"), []byte(`{"name":"npmrc-hostcheck-test","version":"1.0.0"}`), 0644)) require.NoError(t, os.WriteFile(filepath.Join(projectDir, ".npmrc"), []byte("registry="+registryUrl+"\n"), 0644)) @@ -7622,56 +7640,84 @@ func newConfiguredServerCommand() *CurationAuditCommand { return ca } -// TestSetRepoFromNpmrcRejectsHostMismatch: with --run-native, a tokenless .npmrc on another host must never get 'jf c' credentials. -func TestSetRepoFromNpmrcRejectsHostMismatch(t *testing.T) { - writeNpmrcProject(t, "https://attacker.example.com/artifactory/api/npm/npm-test-repo/") - ca := newConfiguredServerCommand() - - setErr := ca.setRepoFromNpmrc() - - require.Error(t, setErr) - assert.Contains(t, setErr.Error(), "does not match") - assert.Nil(t, ca.PackageManagerConfig, "credentials must not be attached to the mismatched host") - sd, err := ca.ServerDetails() - require.NoError(t, err) - assert.Equal(t, "https://configured-server.example.com/artifactory/", sd.ArtifactoryUrl, "shared ServerDetails must not be mutated") -} - -// TestSetRepoFromNpmrcAcceptsMatchingHost: the legitimate same-host case still falls back to the 'jf c' credentials. -func TestSetRepoFromNpmrcAcceptsMatchingHost(t *testing.T) { - writeNpmrcProject(t, "https://configured-server.example.com/artifactory/api/npm/npm-test-repo/") - ca := newConfiguredServerCommand() - - require.NoError(t, ca.setRepoFromNpmrc()) - require.NotNil(t, ca.PackageManagerConfig) - pmSd, sdErr := ca.PackageManagerConfig.ServerDetails() - require.NoError(t, sdErr) - assert.Equal(t, "super-secret-token", pmSd.AccessToken) -} - -// TestSetRepoFromNpmrcForPnpmRejectsHostMismatch: pnpm equivalent of the npm test above. -func TestSetRepoFromNpmrcForPnpmRejectsHostMismatch(t *testing.T) { - writeNpmrcProject(t, "https://attacker.example.com/artifactory/api/npm/pnpm-test-repo/") - ca := newConfiguredServerCommand() +// TestSetRepoFromNpmrcHostCheck: a tokenless .npmrc registry must get the 'jf c' credentials only when its scheme/host match the configured server. +func TestSetRepoFromNpmrcHostCheck(t *testing.T) { + const configuredArtifactoryUrl = "https://configured-server.example.com/artifactory/" + testCases := []struct { + name string + tech string + registryUrl string + expectedError string + }{ + {name: "npm: different host is rejected", tech: "npm", registryUrl: "https://attacker.example.com/artifactory/api/npm/npm-test-repo/", expectedError: "does not match"}, + {name: "npm: different scheme is rejected", tech: "npm", registryUrl: "http://configured-server.example.com/artifactory/api/npm/npm-test-repo/", expectedError: "does not match"}, + {name: "npm: matching host falls back to jf c credentials", tech: "npm", registryUrl: "https://configured-server.example.com/artifactory/api/npm/npm-test-repo/"}, + {name: "npm: explicit default port is the same host", tech: "npm", registryUrl: "https://configured-server.example.com:443/artifactory/api/npm/npm-test-repo/"}, + {name: "pnpm: different host is rejected", tech: "pnpm", registryUrl: "https://attacker.example.com/artifactory/api/npm/pnpm-test-repo/", expectedError: "does not match"}, + {name: "pnpm: different scheme is rejected", tech: "pnpm", registryUrl: "http://configured-server.example.com/artifactory/api/npm/pnpm-test-repo/", expectedError: "does not match"}, + {name: "pnpm: matching host falls back to jf c credentials", tech: "pnpm", registryUrl: "https://configured-server.example.com/artifactory/api/npm/pnpm-test-repo/"}, + {name: "pnpm: explicit default port is the same host", tech: "pnpm", registryUrl: "https://configured-server.example.com:443/artifactory/api/npm/pnpm-test-repo/"}, + } + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + if tc.tech == "pnpm" { + skipIfPnpmUnusable(t) + } + writeNpmrcProject(t, tc.registryUrl) + ca := newConfiguredServerCommand() - setErr := ca.setRepoFromNpmrcForPnpm() + var setErr error + if tc.tech == "pnpm" { + setErr = ca.setRepoFromNpmrcForPnpm() + } else { + setErr = ca.setRepoFromNpmrc() + } - require.Error(t, setErr) - assert.Contains(t, setErr.Error(), "does not match") - assert.Nil(t, ca.PackageManagerConfig, "credentials must not be attached to the mismatched host") - sd, err := ca.ServerDetails() - require.NoError(t, err) - assert.Equal(t, "https://configured-server.example.com/artifactory/", sd.ArtifactoryUrl, "shared ServerDetails must not be mutated") + sd, err := ca.ServerDetails() + require.NoError(t, err) + assert.Equal(t, configuredArtifactoryUrl, sd.ArtifactoryUrl, "shared ServerDetails must not be mutated") + if tc.expectedError != "" { + require.Error(t, setErr) + assert.Contains(t, setErr.Error(), tc.expectedError) + assert.Nil(t, ca.PackageManagerConfig, "credentials must not be attached to the mismatched host") + return + } + require.NoError(t, setErr) + require.NotNil(t, ca.PackageManagerConfig) + pmSd, sdErr := ca.PackageManagerConfig.ServerDetails() + require.NoError(t, sdErr) + assert.Equal(t, "super-secret-token", pmSd.AccessToken) + }) + } } -// TestSetRepoFromNpmrcForPnpmAcceptsMatchingHost: same-host fallback to 'jf c' credentials keeps working. -func TestSetRepoFromNpmrcForPnpmAcceptsMatchingHost(t *testing.T) { - writeNpmrcProject(t, "https://configured-server.example.com/artifactory/api/npm/pnpm-test-repo/") - ca := newConfiguredServerCommand() - - require.NoError(t, ca.setRepoFromNpmrcForPnpm()) - require.NotNil(t, ca.PackageManagerConfig) - pmSd, sdErr := ca.PackageManagerConfig.ServerDetails() - require.NoError(t, sdErr) - assert.Equal(t, "super-secret-token", pmSd.AccessToken) +// TestCredentialFallbackServerDetailsHostCheck covers the shared host guard's accept/reject decisions and that the mismatch error never leaks URL userinfo. +func TestCredentialFallbackServerDetailsHostCheck(t *testing.T) { + testCases := []struct { + name string + discoveredUrl string + expectedError bool + forbiddenInErr string + }{ + {name: "same host is accepted", discoveredUrl: "https://configured-server.example.com/artifactory/"}, + {name: "explicit default port is accepted", discoveredUrl: "https://configured-server.example.com:443/artifactory/"}, + {name: "different host is rejected", discoveredUrl: "https://attacker.example.com/artifactory/", expectedError: true}, + {name: "userinfo is redacted from the mismatch error", discoveredUrl: "https://s3cr3t-token@attacker.example.com/artifactory/", expectedError: true, forbiddenInErr: "s3cr3t-token"}, + } + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + ca := newConfiguredServerCommand() + serverDetails, err := ca.credentialFallbackServerDetails("npm", ".npmrc", tc.discoveredUrl) + if !tc.expectedError { + require.NoError(t, err) + assert.Equal(t, "super-secret-token", serverDetails.AccessToken) + return + } + require.Error(t, err) + assert.Contains(t, err.Error(), "does not match") + if tc.forbiddenInErr != "" { + assert.NotContains(t, err.Error(), tc.forbiddenInErr) + } + }) + } } diff --git a/sca/bom/buildinfo/technologies/pnpm/pnpm.go b/sca/bom/buildinfo/technologies/pnpm/pnpm.go index 56b0dc33c..099429229 100644 --- a/sca/bom/buildinfo/technologies/pnpm/pnpm.go +++ b/sca/bom/buildinfo/technologies/pnpm/pnpm.go @@ -4,8 +4,6 @@ import ( "encoding/json" "errors" "fmt" - "net" - "net/url" "os" "os/exec" "path/filepath" @@ -21,6 +19,7 @@ import ( "github.com/jfrog/jfrog-cli-core/v2/utils/coreutils" "github.com/jfrog/jfrog-cli-security/sca/bom/buildinfo/technologies" "github.com/jfrog/jfrog-cli-security/sca/bom/buildinfo/technologies/npm" + "github.com/jfrog/jfrog-cli-security/utils" "github.com/jfrog/jfrog-cli-security/utils/techutils" "github.com/jfrog/jfrog-cli-security/utils/xray" "github.com/jfrog/jfrog-client-go/utils/errorutils" @@ -122,16 +121,16 @@ func curationNoLockfileError(params technologies.BuildInfoBomGeneratorParams, wo if params.DependenciesRepository == "" { if registryConfig, regErr := GetNativePnpmRegistryConfig(); regErr == nil { params.DependenciesRepository = registryConfig.RepoName - // mirrors setRepoFromNpmrcForPnpm: .npmrc's URL always wins (so the probe hits the right instance in multi-server setups), only the token falls back to the existing ServerDetails. + // mirrors setRepoFromNpmrcForPnpm: .npmrc's URL is used only when its host matches the configured 'jf c' server, otherwise the probe is skipped. if registryConfig.AuthToken != "" { params.ServerDetails = &config.ServerDetails{ ArtifactoryUrl: registryConfig.ArtifactoryUrl, AccessToken: registryConfig.AuthToken, } } else if params.ServerDetails != nil { - if !sameRegistryHost(params.ServerDetails.ArtifactoryUrl, registryConfig.ArtifactoryUrl) { + if !utils.SameRegistryHost(params.ServerDetails.ArtifactoryUrl, registryConfig.ArtifactoryUrl) { // .npmrc is untrusted project content: never send the 'jf c' credentials to a different scheme/host. - log.Warn(fmt.Sprintf("pnpm curation probe: the registry declared in .npmrc (%s) does not match the configured 'jf c' server (%s) — skipping the probe to avoid sending its credentials to a different host.", redactedRegistryUrl(registryConfig.ArtifactoryUrl), redactedRegistryUrl(params.ServerDetails.ArtifactoryUrl))) + log.Warn(fmt.Sprintf("pnpm curation probe: the registry declared in .npmrc (%s) does not match the configured 'jf c' server (%s) — skipping the probe to avoid sending its credentials to a different host.", utils.RedactUrlUserinfo(registryConfig.ArtifactoryUrl), utils.RedactUrlUserinfo(params.ServerDetails.ArtifactoryUrl))) skipProbe = true } else { // copy before mutating: params.ServerDetails may be the shared struct ca.ServerDetails() returns, and overwriting its URL in place would leak to other techs in a multi-tech audit. @@ -149,7 +148,7 @@ func curationNoLockfileError(params technologies.BuildInfoBomGeneratorParams, wo memberRel = "" } if skipProbe { - return errorutils.CheckErrorf("'jf curation-audit' could not produce 'pnpm-lock.yaml' — 'pnpm install --lockfile-only' failed, and the direct dependencies were not probed because the registry declared in .npmrc does not match the configured 'jf c' server. Align the two (or select the matching server with --server-id) and re-run 'jf ca'. Underlying pnpm error: %s", resolveErr.Error()) + return errorutils.CheckErrorf("'jf curation-audit' could not produce 'pnpm-lock.yaml' — 'pnpm install --lockfile-only' failed, and the direct dependencies were not probed because the registry declared in .npmrc does not match the configured 'jf c' server. Align the two (or select the matching server with 'jf c use ' or JFROG_CLI_SERVER_ID) and re-run 'jf ca'. Underlying pnpm error: %s", resolveErr.Error()) } probed, totalProbed := probeBlockedPnpmDirectDeps(params, workspaceRoot, memberRel) outputRef := string(outFormat.Table) @@ -169,43 +168,6 @@ func curationNoLockfileError(params technologies.BuildInfoBomGeneratorParams, wo len(probed), outputRef, outputRef, resolveErr.Error()) } -// sameRegistryHost reports whether both URLs share the same scheme and host:port (paths ignored, default ports normalized). -func sameRegistryHost(configuredUrl, discoveredUrl string) bool { - configured, err := url.Parse(configuredUrl) - if err != nil || configured.Host == "" { - return false - } - discovered, err := url.Parse(discoveredUrl) - if err != nil || discovered.Host == "" { - return false - } - return strings.EqualFold(configured.Scheme, discovered.Scheme) && strings.EqualFold(effectiveHostPort(configured), effectiveHostPort(discovered)) -} - -// effectiveHostPort returns host:port with the scheme's default port (80/443) filled in when absent. -func effectiveHostPort(u *url.URL) string { - port := u.Port() - if port == "" { - switch strings.ToLower(u.Scheme) { - case "https": - port = "443" - case "http": - port = "80" - } - } - return net.JoinHostPort(strings.ToLower(u.Hostname()), port) -} - -// redactedRegistryUrl drops any userinfo (including username-only tokens) so credentials are never logged. -func redactedRegistryUrl(raw string) string { - u, err := url.Parse(raw) - if err != nil { - return "" - } - u.User = nil - return u.String() -} - // probeBlockedPnpmDirectDeps delegates to the shared probe mechanism yarn's fallback also uses; workspaceMemberRel, when non-empty, scopes it to one workspace member. func probeBlockedPnpmDirectDeps(params technologies.BuildInfoBomGeneratorParams, curWd, workspaceMemberRel string) ([]npm.BlockedDirectDep, int) { declared := collectDeclaredPnpmDirectDeps(curWd, workspaceMemberRel) diff --git a/sca/bom/buildinfo/technologies/pnpm/pnpm_test.go b/sca/bom/buildinfo/technologies/pnpm/pnpm_test.go index ad82265bc..a05e8d53a 100644 --- a/sca/bom/buildinfo/technologies/pnpm/pnpm_test.go +++ b/sca/bom/buildinfo/technologies/pnpm/pnpm_test.go @@ -53,7 +53,7 @@ func TestBuildDependencyTreeLimitedDepth(t *testing.T) { name: "With transitive dependencies", treeDepth: "1", expectedUniqueDeps: []string{ - "npm://axios:1.21.0", + "npm://axios:1.21.1", "npm://balaganjs:1.0.0", "npm://yargs:13.3.0", "npm://zen-website:1.0.0", @@ -63,7 +63,7 @@ func TestBuildDependencyTreeLimitedDepth(t *testing.T) { Nodes: []*xrayUtils.GraphNode{ { Id: "npm://balaganjs:1.0.0", - Nodes: []*xrayUtils.GraphNode{{Id: "npm://axios:1.21.0"}, {Id: "npm://yargs:13.3.0"}}, + Nodes: []*xrayUtils.GraphNode{{Id: "npm://axios:1.21.1"}, {Id: "npm://yargs:13.3.0"}}, }, }, }, @@ -885,6 +885,9 @@ func TestIsCurationInstallFailure(t *testing.T) { // Pins the fix: when .npmrc names a different host than the configured 'jf c' server (and has no token), the failed-lockfile probe must not send any request there. func TestCurationNoLockfileErrorSkipsProbeOnHostMismatch(t *testing.T) { + if coreutils.IsWindows() { + t.Skip("pnpm config get registry delegates to npm via cmd.exe, which is not resolvable on the Windows runner") + } if _, lookErr := exec.LookPath("pnpm"); lookErr != nil { t.Skip("pnpm is not on PATH") } @@ -922,18 +925,3 @@ func TestCurationNoLockfileErrorSkipsProbeOnHostMismatch(t *testing.T) { assert.Zero(t, atomic.LoadInt32(&requests), "no request (authenticated or not) may reach the host declared in .npmrc") assert.Equal(t, "https://configured-server.example.com/artifactory/", configured.ArtifactoryUrl, "shared ServerDetails must not be mutated") } - -func TestSameRegistryHost(t *testing.T) { - assert.True(t, sameRegistryHost("https://a.example.com/artifactory/", "https://A.example.com/artifactory/api/npm/r/")) - assert.False(t, sameRegistryHost("https://a.example.com/artifactory/", "http://a.example.com/artifactory/"), "scheme mismatch") - assert.False(t, sameRegistryHost("https://a.example.com/artifactory/", "https://b.example.com/artifactory/"), "host mismatch") - assert.False(t, sameRegistryHost("", "https://b.example.com/"), "empty configured URL") - assert.True(t, sameRegistryHost("https://a.example.com/artifactory/", "https://a.example.com:443/artifactory/api/npm/r/"), "default https port") - assert.True(t, sameRegistryHost("http://a.example.com:80/", "http://a.example.com/"), "default http port") - assert.False(t, sameRegistryHost("https://a.example.com/", "https://a.example.com:8443/"), "non-default port") -} - -func TestRedactedRegistryUrl(t *testing.T) { - assert.Equal(t, "https://a.example.com/artifactory/api/npm/r/", redactedRegistryUrl("https://secrettoken@a.example.com/artifactory/api/npm/r/")) - assert.Equal(t, "https://a.example.com/x", redactedRegistryUrl("https://user:pass@a.example.com/x")) -} diff --git a/utils/urls.go b/utils/urls.go new file mode 100644 index 000000000..e25eb79d2 --- /dev/null +++ b/utils/urls.go @@ -0,0 +1,44 @@ +package utils + +import ( + "net" + "net/url" + "strings" +) + +// SameRegistryHost reports whether both URLs share the same scheme and host:port (paths ignored, default ports 80/443 normalized). +func SameRegistryHost(configuredUrl, discoveredUrl string) bool { + configured, err := url.Parse(configuredUrl) + if err != nil || configured.Host == "" { + return false + } + discovered, err := url.Parse(discoveredUrl) + if err != nil || discovered.Host == "" { + return false + } + return strings.EqualFold(configured.Scheme, discovered.Scheme) && strings.EqualFold(effectiveHostPort(configured), effectiveHostPort(discovered)) +} + +// effectiveHostPort returns host:port with the scheme's default port filled in when absent. +func effectiveHostPort(u *url.URL) string { + port := u.Port() + if port == "" { + switch strings.ToLower(u.Scheme) { + case "https": + port = "443" + case "http": + port = "80" + } + } + return net.JoinHostPort(strings.ToLower(u.Hostname()), port) +} + +// RedactUrlUserinfo drops any userinfo (including username-only tokens) so credentials never reach logs or errors. +func RedactUrlUserinfo(raw string) string { + u, err := url.Parse(raw) + if err != nil { + return "" + } + u.User = nil + return u.String() +} diff --git a/utils/urls_test.go b/utils/urls_test.go new file mode 100644 index 000000000..257996595 --- /dev/null +++ b/utils/urls_test.go @@ -0,0 +1,48 @@ +package utils + +import ( + "net/url" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestSameRegistryHost(t *testing.T) { + testCases := []struct { + name string + configured string + discovered string + expected bool + }{ + {name: "same host, different path and case", configured: "https://a.example.com/artifactory/", discovered: "https://A.example.com/artifactory/api/npm/r/", expected: true}, + {name: "explicit default https port equals no port", configured: "https://a.example.com/artifactory/", discovered: "https://a.example.com:443/artifactory/api/npm/r/", expected: true}, + {name: "explicit default port on the configured side", configured: "https://a.example.com:443/", discovered: "https://a.example.com/artifactory/", expected: true}, + {name: "explicit default http port equals no port", configured: "http://a.example.com:80/", discovered: "http://a.example.com/", expected: true}, + {name: "scheme mismatch", configured: "https://a.example.com/artifactory/", discovered: "http://a.example.com/artifactory/", expected: false}, + {name: "host mismatch", configured: "https://a.example.com/artifactory/", discovered: "https://b.example.com/artifactory/", expected: false}, + {name: "non-default port mismatch", configured: "https://a.example.com/", discovered: "https://a.example.com:8443/", expected: false}, + {name: "empty configured url", configured: "", discovered: "https://b.example.com/", expected: false}, + } + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + assert.Equal(t, tc.expected, SameRegistryHost(tc.configured, tc.discovered)) + }) + } +} + +func TestRedactUrlUserinfo(t *testing.T) { + testCases := []struct { + name string + raw string + expected string + }{ + {name: "username-only token", raw: "https://secrettoken@a.example.com/artifactory/api/npm/r/", expected: "https://a.example.com/artifactory/api/npm/r/"}, + {name: "user and password", raw: (&url.URL{Scheme: "https", User: url.UserPassword("user", "pw"), Host: "a.example.com", Path: "/x"}).String(), expected: "https://a.example.com/x"}, + {name: "no userinfo is unchanged", raw: "https://a.example.com/x", expected: "https://a.example.com/x"}, + } + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + assert.Equal(t, tc.expected, RedactUrlUserinfo(tc.raw)) + }) + } +}