Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 21 additions & 45 deletions commands/curation/curationaudit.go
Comment thread
gauriy-tech marked this conversation as resolved.
Resolved
Original file line number Diff line number Diff line change
Expand Up @@ -1905,37 +1905,35 @@ 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)
Comment thread
gauriy-tech marked this conversation as resolved.
Resolved
if err != nil {
return err
}
}

repoConfig := (&project.RepositoryConfig{}).
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
}

Expand Down Expand Up @@ -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 {
Expand All @@ -2021,18 +2012,18 @@ 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{}).
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
}

Expand Down Expand Up @@ -2208,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 <server-id>' 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 {
Expand Down
122 changes: 122 additions & 0 deletions commands/curation/curationaudit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7599,3 +7599,125 @@ 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.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))
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
}

// 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()

var setErr error
if tc.tech == "pnpm" {
setErr = ca.setRepoFromNpmrcForPnpm()
} else {
setErr = ca.setRepoFromNpmrc()
}

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)
})
}
}

// 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)
}
})
}
}
21 changes: 16 additions & 5 deletions sca/bom/buildinfo/technologies/pnpm/pnpm.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,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"
Expand Down Expand Up @@ -115,21 +116,28 @@ 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 {
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 {
// 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 !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.", 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.
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()))
Expand All @@ -139,6 +147,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 'jf c use <server-id>' 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)
if params.OutputFormat == outFormat.Json {
Expand Down
51 changes: 49 additions & 2 deletions sca/bom/buildinfo/technologies/pnpm/pnpm_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -49,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",
Expand All @@ -59,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"}},
},
},
},
Expand Down Expand Up @@ -878,3 +882,46 @@ 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 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")
}
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")
}
Loading
Loading