diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 311962014..fdadbb354 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -547,11 +547,12 @@ v5.0 removed the v4 spellings `scan --apply` (use `--mode agent`), `scan --vendo **Experimental, and outside the semver policy.** This is for Socket Enterprise customers whose builds may only install through their own artifact host. `--patch-mirror-url` is hidden from `--help`. The flag, `SOCKET_PATCH_MIRROR_URL`, `SOCKET_PATCH_MIRROR_AUTHORIZATION`, the `redirect_mirror_*` codes and everything in this section may change or be removed in any release without a semver bump. The one exception is the rule "A run that was not given the mirror leaves its pins alone" below: it holds for every hosted run, mirror or not, and is additive (MINOR). -A patch mirror is a caching proxy the operator runs in front of the patch server that serves `https://patch.socket.dev/` at `/`. `--patch-mirror-url ` / `SOCKET_PATCH_MIRROR_URL` names that base. It is tested against an Artifactory generic remote repository with npm, pnpm, yarn classic, yarn berry, pip, uv and Bundler; nothing else is tested yet, a Maven, Gradle or sbt build included. +A patch mirror is a caching proxy the operator runs in front of the patch server that serves `https://patch.socket.dev/` at `/`. `--patch-mirror-url ` / `SOCKET_PATCH_MIRROR_URL` names that base. It is tested against an Artifactory generic remote repository with npm, pnpm, yarn classic, yarn berry, Bun, vlt, pip, uv, PDM, Pipenv, Bundler and Go; nothing else is tested yet, a Maven, Gradle or sbt build included, and Composer too (no Composer patch was available to test with). * **Operator configuration only.** The base is read from the flag or the environment, never from `socket.yml` or any other repository file (the socket.yml trust boundary below): it names the host every later install fetches from and the host whose references `vex` attests. It must be an `http(s)` URL with a host and no userinfo, query or fragment, in the characters a grant URL may hold; trailing slashes are dropped. Anything else is a usage error (exit 2, `Error: --patch-mirror-url (or SOCKET_PATCH_MIRROR_URL) is not a usable patch mirror base URL: `), checked before the project is read. The message never repeats the value. `apply` is the exception: it does not use the mirror and runs unattended from install hooks, so there a base it cannot use is no mirror and no error. -* **What hosted mode writes.** `scan` / `get --mode hosted` move each granted reference onto the mirror before anything else reads it: the artifact URL, and the registry index URL of a gem or Maven-layout reference, keep their path (grant token and patch uuid included) and take the base in place of scheme and authority. The integrity pins are unchanged, and a re-run is idempotent. A Go reference is not moved: its pin is the module path `patch.socket.dev/gopatch/`, which names no host to fetch from. A Cargo or NuGet reference is not written at all: `skipped` / `redirect_mirror_unsupported` (their registry index is rendered by the patch server with its own absolute download URLs, which a mirror cannot rewrite; the detail names `--mode vendored`). A reference with no path to serve, or whose mirrored URL the grant gate refuses, is `skipped` / `redirect_mirror_url_refused`. -* **A project already pinned on the patch server.** npm, pnpm, yarn classic, `requirements.txt` and uv locks are re-pinned onto the mirror by the same run. The yarn berry, Bun, Bundler, Poetry and PDM rewriters own an earlier pin only on the host they are writing, so they leave a direct pin as it is: the patch is `skipped` (`redirect_unconfirmed`) and a `redirect_mirror_pin_not_moved` warning names the file, the host and the remedy (`rollback `, then the same command again). +* **What hosted mode writes.** `scan` / `get --mode hosted` move each granted reference onto the mirror before anything else reads it: the artifact URL, and the registry index URL of a gem or Maven-layout reference, keep their path (grant token and patch uuid included) and take the base in place of scheme and authority. The integrity pins are unchanged, and a re-run is idempotent. A Go reference is not moved: its pin is the module path `patch.socket.dev/gopatch/`, which names no host to fetch from (go finds it through `GOPROXY`, see *Installing through the mirror*). A Cargo or NuGet reference is not written at all: `skipped` / `redirect_mirror_unsupported` (their registry index is rendered by the patch server with its own absolute download URLs, which a mirror cannot rewrite; the detail names `--mode vendored`). A reference with no path to serve, or whose mirrored URL the grant gate refuses, is `skipped` / `redirect_mirror_url_refused`. +* **Installing through the mirror.** The build installs from the pins alone, so it needs read access to the repository, and each package manager is handed the repository's credentials its own way: npm and pnpm send what `.npmrc` holds for the host (`///:_auth=…`); pip, uv, PDM and Pipenv what a netrc file holds for it; Bundler what `bundle config ` holds; vlt the token its keychain holds for the base or a URL above it (`vlt token add --registry=`). yarn classic sends none for a URL pin outside its registry's path, and yarn berry and Bun none for a URL pin at all, so they need a repository that allows anonymous reads. Go fetches a Socket module over the GOPROXY protocol from the patch server's root, which the mirror serves at its base: list the base first in `GOPROXY` (`GOPROXY=,https://proxy.golang.org`), and go fetches every Socket module through the mirror and moves past its 404 for every other module. The run writes nothing for this. go sends credentials (netrc, `GOAUTH`) only over `https`, so a plain-`http` mirror must allow anonymous reads. A generic remote repository is enough for Go; Artifactory OSS has no Go API (`/api/go/` answers 404 even for a repository of type Go). +* **A project already pinned on the patch server.** npm, pnpm, yarn classic, vlt, `requirements.txt`, uv and Pipenv locks are re-pinned onto the mirror by the same run. A Go pin is never moved (see *What hosted mode writes*). The yarn berry, Bun, Bundler, Poetry and PDM rewriters own an earlier pin only on the host they are writing, so they leave a direct pin as it is: the patch is `skipped` (`redirect_unconfirmed`) and a `redirect_mirror_pin_not_moved` warning names the file, the host and the remedy (`rollback `, then the same command again). * **pnpm takes `trustLockfile`, never the registry route.** The registry address a grant carries (`npmRegistryUrl`, see "pnpm registry route") is not moved onto the mirror: the document the patch server answers there names the tarball on the patch server itself, which a mirror cannot rewrite, so pnpm would refuse a mirrored tarball against it. A mirrored tarball is no file of that address, which reads as no address, and a mirror run pins a pnpm project exactly as a patch service without registries does (`trustLockfile: true`, with nothing said of registries). A project an earlier run routed is taken off the route by the run that moves its pins onto the mirror: the registries (on the patch server, which the run still knows for one: the configured server, else the one the grants' registry addresses name), the overrides, the locks' records and the registry keys go as in *Leaving the route*, each entry reported as usual, and the `redirect_pnpm_trust_lockfile` warning says "the patch mirror serves no registry for `@`, …". `repair` and `scan --prune` clean up a route's unused entries the same with or without the setting; a registry of the CLI's name shape declared under the mirror's base or elsewhere on its host is on no patch server and is the user's. * **The run's own downloads** (a wheel's metadata, a tarball's `package.json`, a gem for the stale-install refresh) read the patch server, not the mirror, which may want credentials the run does not have. * **The mirror is checked before anything is pinned.** One `HEAD` for each mirrored reference the project's files do not already hold (a re-run that pins nothing new sends none), in candidate order, after the unconfigured-host guard and before the rewrite. The request carries no Socket credential, carries `SOCKET_PATCH_MIRROR_AUTHORIZATION` as its `Authorization` header when that is set, and follows no redirect. 2xx: that pin proceeds. 401 / 403 / 407, or a 3xx: nothing more is asked, every pin the mirror has not already refused proceeds, and one `redirect_mirror_unverified` warning says they were not checked. A transport failure, or no answer within the per-attempt timeout: nothing more is asked, and that reference and every one not yet asked about are `skipped` / `redirect_mirror_unavailable`. Any other answer: that reference is `skipped` / `redirect_mirror_unavailable`. Nothing is written for a skipped reference, and a warning names its package; when the mirror served none of the references it was asked about there is one warning instead, about the mirror. Exit 0 either way, files byte-identical for the skipped references, no `.npmrc` setting when nothing was pinned. No retry. A dry run checks too. diff --git a/crates/socket-patch-cli/tests/e2e_artifactory_mirror.rs b/crates/socket-patch-cli/tests/e2e_artifactory_mirror.rs index 9128cfedb..7f35389eb 100644 --- a/crates/socket-patch-cli/tests/e2e_artifactory_mirror.rs +++ b/crates/socket-patch-cli/tests/e2e_artifactory_mirror.rs @@ -16,7 +16,13 @@ //! the installed bytes carry the patch. //! //! The patched artifact can only have come through Artifactory: the lock -//! names no other host for it. +//! names no other host for it. Go is the exception, because its pin is a +//! module path: that leg lists the repository first in `GOPROXY` and checks +//! that every Socket module was fetched from it. +//! +//! Legs: npm, pnpm, yarn classic, yarn berry, Bun, vlt, pip, uv, PDM, +//! Pipenv, Bundler and Go. There is no Composer leg: no Composer patch +//! was available to test with, so there is nothing to pin. //! //! ## Configuration //! @@ -24,7 +30,7 @@ //! | --- | --- | //! | `SOCKET_PATCH_ARTIFACTORY_E2E_BASE` | Base URL of a repository that needs credentials, such as `http://127.0.0.1:8081/artifactory/socket-patch`. Without it every leg skips. | //! | `SOCKET_PATCH_ARTIFACTORY_E2E_USER`, `..._PASSWORD` | A user with Read and Deploy/Cache on that repository. | -//! | `SOCKET_PATCH_ARTIFACTORY_E2E_ANON_BASE` | Base URL of a repository readable without credentials (the yarn legs need one: yarn sends no credentials for a URL pin). Without it those legs skip. | +//! | `SOCKET_PATCH_ARTIFACTORY_E2E_ANON_BASE` | Base URL of a repository readable without credentials (the yarn, Bun and Go legs need one: yarn and Bun send no credentials for a URL pin, and go sends none over plain `http`). Without it those legs skip. | //! | `SOCKET_PATCH_ARTIFACTORY_E2E_STRICT=1` | Fail instead of skipping a leg whose settings or toolchain are missing. | //! //! ```sh @@ -190,7 +196,19 @@ fn cli(cwd: &Path) -> Command { /// `scan --mode hosted --json --yes --patch-mirror-url `; the parsed /// envelope of a run that exited 0. fn scan_mirrored(cwd: &Path, base: &str, authorization: Option<&str>) -> serde_json::Value { + scan_mirrored_with(cwd, base, authorization, &[]) +} + +/// [`scan_mirrored`] with extra environment for the CLI (a Go module cache +/// to crawl, say). +fn scan_mirrored_with( + cwd: &Path, + base: &str, + authorization: Option<&str>, + env: &[(&str, &str)], +) -> serde_json::Value { let mut cmd = cli(cwd); + cmd.envs(env.iter().copied()); cmd.args([ "scan", "--mode", @@ -228,9 +246,15 @@ fn pinned(env: &serde_json::Value) -> Vec { } fn has_command(program: &str) -> bool { + has_command_with(program, "--version") +} + +/// [`has_command`] for a tool whose version probe is not `--version` +/// (`go version`). +fn has_command_with(program: &str, probe_arg: &str) -> bool { let mut probe = pm_command(program); probe - .arg("--version") + .arg(probe_arg) .stdout(std::process::Stdio::null()) .stderr(std::process::Stdio::null()); cache_env::isolate(&mut probe); @@ -242,6 +266,11 @@ fn has_command(program: &str) -> bool { fn pm_command(program: &str) -> Command { let mut cmd = hermetic::tool_command(program); hermetic::scrub_socket_vars(&mut cmd); + if program == "bun" { + // `BUN_CONFIG_REGISTRY`, `BUN_CONFIG_TOKEN` and `npm_config_*` + // would change what bun locks. + cache_env::scrub_ambient_bun_tool_env(&mut cmd); + } hermetic::scrub_extra(&mut cmd, &[hermetic::Extra::Venv, hermetic::Extra::Bundle]); for key in [ "NPM_CONFIG_REGISTRY", @@ -826,6 +855,187 @@ fn yarn_berry_installs_the_patch_through_an_anonymous_repository() { assert_patched(&minimist_entry(&fx.proj), LEG); } +/// Lock minimist with Bun, pin it through `base` and return the lock. The +/// caller gets a project whose `node_modules` holds the upstream copy. +fn bun_lock_and_pin( + fx: &Fixture, + base: &str, + authorization: Option<&str>, + leg: &str, +) -> Option { + write_npm_manifest(&fx.proj, ""); + let cache = fx.scratch.join("bun-upstream").display().to_string(); + let install = tool( + &fx.proj, + "bun", + &["install", "--ignore-scripts"], + &[("BUN_INSTALL_CACHE_DIR", &cache)], + ); + if !install.status.success() { + println!("{leg}: upstream `bun install` failed:\n{}", dump(&install)); + return None; + } + assert_pristine(&minimist_entry(&fx.proj), leg); + let env = scan_mirrored(&fx.proj, base, authorization); + assert_eq!( + pinned(&env), + [format!("pkg:npm/{NPM_NAME}@{NPM_VERSION}")], + "{leg}: {env:#}" + ); + let lock = read(&fx.proj.join("bun.lock")); + assert_mirrored_pin(&lock, base, leg); + std::fs::remove_dir_all(fx.proj.join("node_modules")).unwrap(); + Some(lock) +} + +/// `bun install --frozen-lockfile` from a cold cache of its own. +fn bun_frozen_install(fx: &Fixture, cache: &str) -> Output { + let cache = fx.scratch.join(cache).display().to_string(); + tool( + &fx.proj, + "bun", + &["install", "--frozen-lockfile", "--ignore-scripts"], + &[("BUN_INSTALL_CACHE_DIR", &cache)], + ) +} + +/// Bun sends no credentials for a URL pin, so it reads a repository that +/// allows anonymous access. With a repository that needs credentials, the +/// credentials `.npmrc` holds for its host do not help: the install is +/// refused (the contract's "Installing through the mirror"). +#[test] +#[ignore = "live: a real Artifactory, the production patch API and the npm registry. Run with --ignored."] +fn bun_installs_the_patch_through_an_anonymous_repository() { + const LEG: &str = "bun_installs_the_patch_through_an_anonymous_repository"; + let Some(base) = setting("SOCKET_PATCH_ARTIFACTORY_E2E_ANON_BASE") else { + soft_skip!(LEG, "SOCKET_PATCH_ARTIFACTORY_E2E_ANON_BASE is not set"); + }; + if !has_command("bun") { + soft_skip!(LEG, "`bun` is not on PATH"); + } + let fx = fixture(); + let Some(lock) = bun_lock_and_pin(&fx, &base, None, LEG) else { + soft_skip!(LEG, "the upstream lock could not be made"); + }; + assert!( + lock.contains(&format!( + "\"{NPM_NAME}@{base}/patch/npm/{NPM_NAME}/{NPM_VERSION}/" + )), + "{LEG}: bun.lock must resolve {NPM_NAME} to the mirrored tarball:\n{lock}" + ); + let installed = bun_frozen_install(&fx, "bun-cold"); + assert!( + installed.status.success(), + "{LEG}: `bun install --frozen-lockfile` through Artifactory failed:\n{}", + dump(&installed) + ); + assert_patched(&minimist_entry(&fx.proj), LEG); + + // The repository that needs credentials, with them in `.npmrc` under + // its host: Bun still sends none for the pin. + let Some(private) = Private::from_env() else { + println!( + "{LEG}: SOCKET_PATCH_ARTIFACTORY_E2E_BASE is not set; the credential case is not run" + ); + return; + }; + let fx = fixture(); + if bun_lock_and_pin(&fx, &private.base, Some(&private.authorization()), LEG).is_none() { + soft_skip!(LEG, "the upstream lock could not be made"); + } + std::fs::write(fx.proj.join(".npmrc"), private.npmrc_auth()).unwrap(); + let refused = bun_frozen_install(&fx, "bun-cold-private"); + assert!( + !refused.status.success() && dump(&refused).contains("401"), + "{LEG}: Bun sent credentials for a URL pin; the contract says it sends none, so \ + update \"Installing through the mirror\":\n{}", + dump(&refused) + ); +} + +/// vlt sends the token its keychain holds for a registry URL to every +/// request under that URL, so a token stored for the mirror's base reaches +/// the pins. `vlt token add` reads the token from a terminal, so the leg +/// writes the keychain file it would write. +#[test] +#[ignore = "live: a real Artifactory, the production patch API and the npm registry. Run with --ignored."] +fn vlt_installs_the_patch_through_artifactory() { + const LEG: &str = "vlt_installs_the_patch_through_artifactory"; + let Some(private) = Private::from_env() else { + soft_skip!( + LEG, + "SOCKET_PATCH_ARTIFACTORY_E2E_BASE / _USER / _PASSWORD are not set" + ); + }; + if !has_command("vlt") { + soft_skip!(LEG, "`vlt` is not on PATH"); + } + let fx = fixture(); + write_npm_manifest(&fx.proj, ""); + // Each run gets its own XDG tree: vlt keeps its cache and its keychain + // there. + let xdg = |name: &str| { + let root = fx.scratch.join(name); + [ + ("XDG_CACHE_HOME", root.join("cache").display().to_string()), + ("XDG_DATA_HOME", root.join("data").display().to_string()), + ("XDG_CONFIG_HOME", root.join("config").display().to_string()), + ] + }; + let vlt = |args: &[&str], name: &str| { + let env = xdg(name); + let env: Vec<(&str, &str)> = env.iter().map(|(k, v)| (*k, v.as_str())).collect(); + tool(&fx.proj, "vlt", args, &env) + }; + let install = vlt(&["install"], "upstream"); + if !install.status.success() { + soft_skip!(LEG, "upstream `vlt install` failed:\n{}", dump(&install)); + } + assert_pristine(&minimist_entry(&fx.proj), LEG); + + let env = scan_mirrored(&fx.proj, &private.base, Some(&private.authorization())); + assert_eq!( + pinned(&env), + [format!("pkg:npm/{NPM_NAME}@{NPM_VERSION}")], + "{LEG}: {env:#}" + ); + assert_mirrored_pin(&read(&fx.proj.join("vlt-lock.json")), &private.base, LEG); + + let _ = std::fs::remove_dir_all(fx.proj.join("node_modules")); + let refused = vlt(&["ci"], "cold-a"); + assert!( + !refused.status.success() && dump(&refused).contains("401"), + "{LEG}: an install with no credentials must be refused:\n{}", + dump(&refused) + ); + + let keychain = fx.scratch.join("cold-b/data/vlt/auth/keychain.json"); + std::fs::create_dir_all(keychain.parent().unwrap()).unwrap(); + std::fs::write( + &keychain, + serde_json::json!({ private.base.as_str(): private.authorization() }).to_string(), + ) + .unwrap(); + let _ = std::fs::remove_dir_all(fx.proj.join("node_modules")); + let installed = vlt(&["ci"], "cold-b"); + assert!( + installed.status.success(), + "{LEG}: `vlt ci` through Artifactory failed:\n{}", + dump(&installed) + ); + assert_patched(&minimist_entry(&fx.proj), LEG); + + // `list` reads the mirrored pin as a hosted patch. + let mut list = cli(&fx.proj); + list.args(["list", "--patch-mirror-url", &private.base]); + let out = list.output().unwrap(); + assert!( + String::from_utf8_lossy(&out.stdout).contains("Mode: hosted"), + "{LEG}: `list` must read the mirrored vlt pin:\n{}", + dump(&out) + ); +} + // --------------------------------------------------------------------------- // PyPI // --------------------------------------------------------------------------- @@ -995,6 +1205,148 @@ fn uv_installs_the_patch_through_artifactory() { ); } +/// PDM installs a `pdm.lock` URL file with the credentials a netrc file +/// holds for the repository's host. +#[test] +#[ignore = "live: a real Artifactory, the production patch API and PyPI. Run with --ignored."] +fn pdm_installs_the_patch_through_artifactory() { + const LEG: &str = "pdm_installs_the_patch_through_artifactory"; + let Some(private) = Private::from_env() else { + soft_skip!( + LEG, + "SOCKET_PATCH_ARTIFACTORY_E2E_BASE / _USER / _PASSWORD are not set" + ); + }; + if !has_command("pdm") { + soft_skip!(LEG, "`pdm` is not on PATH"); + } + let fx = fixture(); + std::fs::write( + fx.proj.join("pyproject.toml"), + format!( + "[project]\nname = \"artifactory-e2e\"\nversion = \"0.0.0\"\n\ + requires-python = \">=3.9\"\ndependencies = [\"{PYPI_NAME}=={PYPI_VERSION}\"]\n\n\ + [tool.pdm]\ndistribution = false\n" + ), + ) + .unwrap(); + let pdm = |args: &[&str], cache: &str, extra: &[(&str, &str)]| { + let cache = fx.scratch.join(cache).display().to_string(); + let mut env = vec![ + ("PDM_CACHE_DIR", cache.as_str()), + ("PDM_CHECK_UPDATE", "false"), + ]; + env.extend_from_slice(extra); + tool(&fx.proj, "pdm", args, &env) + }; + let locked = pdm(&["lock"], "upstream", &[]); + if !locked.status.success() { + soft_skip!(LEG, "`pdm lock` failed:\n{}", dump(&locked)); + } + + let env = scan_mirrored(&fx.proj, &private.base, Some(&private.authorization())); + assert_eq!( + pinned(&env), + [format!("pkg:pypi/{PYPI_NAME}@{PYPI_VERSION}")], + "{LEG}: {env:#}" + ); + assert_mirrored_pin(&read(&fx.proj.join("pdm.lock")), &private.base, LEG); + + let sync = ["sync", "--no-self"]; + let refused = pdm(&sync, "cold-a", &[]); + assert!( + !refused.status.success() && dump(&refused).contains("401"), + "{LEG}: an install with no credentials must be refused:\n{}", + dump(&refused) + ); + let _ = std::fs::remove_dir_all(fx.proj.join(".venv")); + let netrc = private.netrc(&fx.scratch).display().to_string(); + let synced = pdm(&sync, "cold-b", &[("NETRC", &netrc)]); + assert!( + synced.status.success(), + "{LEG}: `pdm sync` through Artifactory failed:\n{}", + dump(&synced) + ); + assert!( + urllib3_patched(&fx.proj.join(".venv")), + "{LEG}: the installed urllib3 is not patched" + ); +} + +/// Pipenv installs a `Pipfile.lock` file URL with the credentials a netrc +/// file holds for the repository's host. (`vendor` of a Pipenv project +/// pinned through a mirror is not covered here.) +#[test] +#[ignore = "live: a real Artifactory, the production patch API and PyPI. Run with --ignored."] +fn pipenv_installs_the_patch_through_artifactory() { + const LEG: &str = "pipenv_installs_the_patch_through_artifactory"; + let Some(private) = Private::from_env() else { + soft_skip!( + LEG, + "SOCKET_PATCH_ARTIFACTORY_E2E_BASE / _USER / _PASSWORD are not set" + ); + }; + if !has_command("pipenv") { + soft_skip!(LEG, "`pipenv` is not on PATH"); + } + let fx = fixture(); + std::fs::write( + fx.proj.join("Pipfile"), + format!( + "[[source]]\nurl = \"https://pypi.org/simple\"\nverify_ssl = true\nname = \"pypi\"\n\n\ + [packages]\n{PYPI_NAME} = \"=={PYPI_VERSION}\"\n" + ), + ) + .unwrap(); + let pipenv = |args: &[&str], cache: &str, extra: &[(&str, &str)]| { + let cache = fx.scratch.join(cache); + let pip_cache = cache.join("pip").display().to_string(); + let cache = cache.display().to_string(); + let mut env = vec![ + ("PIPENV_CACHE_DIR", cache.as_str()), + ("PIP_CACHE_DIR", pip_cache.as_str()), + ("PIPENV_VENV_IN_PROJECT", "1"), + ("PIPENV_IGNORE_VIRTUALENVS", "1"), + ("PIPENV_YES", "1"), + ("PIPENV_NOSPIN", "1"), + ]; + env.extend_from_slice(extra); + tool(&fx.proj, "pipenv", args, &env) + }; + let locked = pipenv(&["lock"], "upstream", &[]); + if !locked.status.success() { + soft_skip!(LEG, "`pipenv lock` failed:\n{}", dump(&locked)); + } + + let env = scan_mirrored(&fx.proj, &private.base, Some(&private.authorization())); + assert_eq!( + pinned(&env), + [format!("pkg:pypi/{PYPI_NAME}@{PYPI_VERSION}")], + "{LEG}: {env:#}" + ); + assert_mirrored_pin(&read(&fx.proj.join("Pipfile.lock")), &private.base, LEG); + + let _ = std::fs::remove_dir_all(fx.proj.join(".venv")); + let refused = pipenv(&["sync"], "cold-a", &[]); + assert!( + !refused.status.success() && dump(&refused).contains("401"), + "{LEG}: an install with no credentials must be refused:\n{}", + dump(&refused) + ); + let _ = std::fs::remove_dir_all(fx.proj.join(".venv")); + let netrc = private.netrc(&fx.scratch).display().to_string(); + let synced = pipenv(&["sync"], "cold-b", &[("NETRC", &netrc)]); + assert!( + synced.status.success(), + "{LEG}: `pipenv sync` through Artifactory failed:\n{}", + dump(&synced) + ); + assert!( + urllib3_patched(&fx.proj.join(".venv")), + "{LEG}: the installed urllib3 is not patched" + ); +} + // --------------------------------------------------------------------------- // RubyGems // --------------------------------------------------------------------------- @@ -1162,3 +1514,168 @@ fn bundler_fetches_the_patched_gems_through_artifactory() { "{LEG}: the gem Bundler fetched through Artifactory is not the patched gem the lock pins" ); } + +// --------------------------------------------------------------------------- +// Go +// --------------------------------------------------------------------------- + +const GO_MODULE: &str = "github.com/jackc/pgx/v5"; +const GO_VERSION: &str = "v5.7.0"; +/// Prints `PANIC` on the upstream module and `REJECTED` on the patched one: +/// the patch makes `FunctionCall.Decode` refuse a negative argument length. +const GO_MAIN: &str = r#"package main + +import ( + "fmt" + + "github.com/jackc/pgx/v5/pgproto3" +) + +func probe() (result string) { + defer func() { + if recover() != nil { + result = "PANIC" + } + }() + var msg pgproto3.FunctionCall + if msg.Decode([]byte{0, 0, 0, 1, 0, 0, 0, 1, 255, 255, 255, 254}) != nil { + return "REJECTED" + } + return "ACCEPTED" +} + +func main() { fmt.Println(probe()) } +"#; + +/// The go environment of one "machine": its own module and build caches, +/// no ambient configuration, `GOPROXY` as given. +fn go_env(cache: &Path, proxy: &str) -> Vec<(&'static str, String)> { + let at = |name: &str| cache.join(name).display().to_string(); + vec![ + ("GOMODCACHE", at("mod")), + ("GOPATH", at("path")), + ("GOCACHE", at("build")), + ("GOTOOLCHAIN", "local".into()), + ("GOENV", "off".into()), + ("GOWORK", "off".into()), + // Writable, so the tempdir can be removed. + ("GOFLAGS", "-mod=readonly -modcacherw".into()), + ("GOPRIVATE", String::new()), + ("GONOPROXY", String::new()), + ("GONOSUMDB", String::new()), + ("GOSUMDB", "sum.golang.org".into()), + ("GOPROXY", proxy.into()), + ] +} + +fn go(cwd: &Path, args: &[&str], env: &[(&'static str, String)]) -> Output { + let env: Vec<(&str, &str)> = env.iter().map(|(k, v)| (*k, v.as_str())).collect(); + tool(cwd, "go", args, &env) +} + +/// Every `# get : ` line `go -x` printed for a Socket module. +fn socket_module_fetches(out: &Output) -> Vec { + String::from_utf8_lossy(&out.stderr) + .lines() + .filter_map(|line| line.strip_prefix("# get ")) + .filter(|line| line.contains("/gopatch/") && line.contains(": ")) + .map(str::to_string) + .collect() +} + +/// A Go pin is the module path `patch.socket.dev/gopatch/`, which a +/// mirror run leaves as it is. go fetches that module through the GOPROXY +/// protocol from the patch server's root, which a generic remote of it +/// serves at its base, so a build that lists the base first in `GOPROXY` +/// fetches every Socket module through Artifactory and falls through its +/// 404s for the rest. go sends credentials only over https, so a plain-http +/// repository must allow anonymous reads. +#[test] +#[ignore = "live: a real Artifactory, the production patch API and the Go module proxy. Run with --ignored."] +fn go_fetches_the_patched_modules_through_an_anonymous_repository() { + const LEG: &str = "go_fetches_the_patched_modules_through_an_anonymous_repository"; + let Some(base) = setting("SOCKET_PATCH_ARTIFACTORY_E2E_ANON_BASE") else { + soft_skip!(LEG, "SOCKET_PATCH_ARTIFACTORY_E2E_ANON_BASE is not set"); + }; + if !has_command_with("go", "version") { + soft_skip!(LEG, "`go` is not on PATH"); + } + let fx = fixture(); + std::fs::write(fx.proj.join("main.go"), GO_MAIN).unwrap(); + std::fs::write( + fx.proj.join("go.mod"), + format!("module example.com/app\n\ngo 1.21\n\nrequire {GO_MODULE} {GO_VERSION}\n"), + ) + .unwrap(); + let upstream = go_env(&fx.scratch.join("go-upstream"), "https://proxy.golang.org"); + let tidy = go( + &fx.proj, + &["mod", "tidy"], + &[&upstream[..], &[("GOFLAGS", "-mod=mod -modcacherw".into())]].concat(), + ); + if !tidy.status.success() { + soft_skip!(LEG, "`go mod tidy` failed:\n{}", dump(&tidy)); + } + let run = go(&fx.proj, &["run", "."], &upstream); + assert_eq!( + String::from_utf8_lossy(&run.stdout).trim(), + "PANIC", + "{LEG}: the upstream module must be the vulnerable one:\n{}", + dump(&run) + ); + + let crawl: Vec<(&str, &str)> = upstream + .iter() + .filter(|(k, _)| matches!(*k, "GOMODCACHE" | "GOPATH" | "GOCACHE")) + .map(|(k, v)| (*k, v.as_str())) + .collect(); + let env = scan_mirrored_with(&fx.proj, &base, None, &crawl); + assert!( + pinned(&env).contains(&format!("pkg:golang/{GO_MODULE}@{GO_VERSION}")), + "{LEG}: {env:#}" + ); + let go_mod = read(&fx.proj.join("go.mod")); + assert!( + go_mod.contains(&format!( + "replace {GO_MODULE} {GO_VERSION} => {PATCH_HOST}/gopatch/" + )), + "{LEG}: the pin is the module path, which a mirror run leaves as it is:\n{go_mod}" + ); + let (_, base_rest) = base.split_once("://").expect("base is a URL"); + assert!( + !go_mod.contains(base_rest) && !read(&fx.proj.join("go.sum")).contains(base_rest), + "{LEG}: go.mod and go.sum name no mirror" + ); + + // A fresh machine with the repository first in GOPROXY. + let cold = go_env( + &fx.scratch.join("go-cold"), + &format!("{base},https://proxy.golang.org"), + ); + let download = go(&fx.proj, &["mod", "download", "-x", "all"], &cold); + assert!( + download.status.success(), + "{LEG}: `go mod download` through Artifactory failed:\n{}", + dump(&download) + ); + let fetches = socket_module_fetches(&download); + let zips: Vec<&String> = fetches.iter().filter(|f| f.contains(".zip: ")).collect(); + assert!( + !zips.is_empty() + && fetches + .iter() + .all(|f| f.starts_with(&format!("{base}/{PATCH_HOST}/gopatch/"))), + "{LEG}: every Socket module must come from the repository:\n{fetches:#?}" + ); + assert!( + zips.iter().all(|f| f.contains(".zip: 200")), + "{LEG}: {zips:#?}" + ); + let run = go(&fx.proj, &["run", "."], &cold); + assert_eq!( + String::from_utf8_lossy(&run.stdout).trim(), + "REJECTED", + "{LEG}: the module built from the repository must be the patched one:\n{}", + dump(&run) + ); +} diff --git a/crates/socket-patch-core/src/origin.rs b/crates/socket-patch-core/src/origin.rs index 0655f518b..f075cabc3 100644 --- a/crates/socket-patch-core/src/origin.rs +++ b/crates/socket-patch-core/src/origin.rs @@ -112,22 +112,61 @@ const GO_SERVE_ROOT: &str = "gopatch"; /// first in the path; an operator's deployment may sit under a path prefix /// (`prefixed`), where the first such level counts. fn served_tail<'a>(segments: &'a [&'a str], prefixed: bool) -> Option<&'a [&'a str]> { + let (_, start) = served_level(segments, prefixed)?; + segments.get(start..) +} + +/// Where [`served_tail`]'s level sits in `segments`: the index of its root +/// (`patch`, `patch-registry`, `gopatch`) and the index of the first segment +/// below it. +fn served_level(segments: &[&str], prefixed: bool) -> Option<(usize, usize)> { let tail_at = |i: usize| { let root = *segments.get(i)?; if root == GO_SERVE_ROOT { - Some(i + 1) + Some((i, i + 1)) } else if SERVE_ROOTS.contains(&root) && ECOSYSTEM_DIRS.contains(segments.get(i + 1)?) { - Some(i + 2) + Some((i, i + 2)) } else { None } }; - let start = if prefixed { - (0..segments.len()).find_map(tail_at)? + if prefixed { + (0..segments.len()).find_map(tail_at) } else { - tail_at(0)? + tail_at(0) + } +} + +/// The path of a Socket-HOSTED `url` as the patch server itself serves it: +/// its percent-decoded segments from the serve level on (`patch`, `npm`, +/// ``, …), with the path prefix of an operator's deployment or of a +/// patch mirror's base dropped. `None` for a url [`hosted_patch_uuid`] +/// does not accept. A reader that checks what a hosted path embeds reads +/// this, never the url's own path, which under a mirror starts with the +/// mirror's base (`/artifactory/socket-patch/patch/npm/…`). +/// +/// Under a mirror the serve level is the first segment below the base, so +/// a base that itself holds a `gopatch` or `patch/` segment is never +/// read as the level. +pub(crate) fn hosted_served_path(url: &str, extra_origins: &[String]) -> Option> { + use crate::utils::purl::percent_decode_purl_component; + + hosted_patch_uuid(url, extra_origins)?; + let (parsed, socket_host) = accepted_hosted_url(url, extra_origins)?; + let segments: Vec<&str> = parsed.path_segments()?.collect(); + let root = match mirror_base_depth(&parsed, extra_origins) { + Some(depth) => { + let below = segments.get(depth..)?; + depth + served_level(below, false)?.0 + } + None => served_level(&segments, !socket_host)?.0, }; - segments.get(start..) + Some( + segments[root..] + .iter() + .map(|segment| percent_decode_purl_component(segment).into_owned()) + .collect(), + ) } /// `url` normalized the way [`hosted_patch_url_uuids`] reads it: `\/` @@ -298,6 +337,22 @@ pub(crate) fn on_mirror(url: &str, origins: &[String]) -> bool { .is_some_and(|parsed| on_configured_origin(&parsed, &mirrors)) } +/// The number of path segments of the deepest patch mirror base among +/// `origins` (a [`mirror_entry`]) that `url` is at or below, or `None` when +/// it is under no mirror's base. +fn mirror_base_depth(url: &reqwest::Url, origins: &[String]) -> Option { + origins + .iter() + .filter(|entry| entry_url(entry).1) + .filter(|entry| on_configured_origin(url, std::slice::from_ref(*entry))) + .filter_map(|entry| reqwest::Url::parse(entry_url(entry).0).ok()) + .map(|base| { + base.path_segments() + .map_or(0, |s| s.filter(|seg| !seg.is_empty()).count()) + }) + .max() +} + /// Whether `path` is `base` or below it, a whole segment at a time. A base /// of `/` (a mirror given with no path) holds every path. fn under_base_path(path: &str, base: &str) -> bool { @@ -477,6 +532,11 @@ impl<'a> OriginPolicy<'a> { hosted_patch_uuid(url, self.origins) } + /// [`hosted_served_path`] under this policy's origins. + pub(crate) fn hosted_served_path(&self, url: &str) -> Option> { + hosted_served_path(url, self.origins) + } + /// Classify `s` (see [`Located`]). pub(crate) fn locate(&self, s: &str, opts: LocateOpts) -> Located { let vendored = match opts.grammar { @@ -1415,4 +1475,41 @@ mod tests { Some("/m/") ); } + + /// The served path drops a mirror's base, even one that holds a + /// serve-level name itself, and the patch server's path is read as is. + #[test] + fn hosted_served_path_starts_below_the_mirror_base() { + let tail = format!("patch/npm/left-pad/1.3.0/tok/{UUID}/left-pad-1.3.0.tgz"); + let want: Vec = tail.split('/').map(str::to_string).collect(); + assert_eq!( + hosted_served_path(&format!("https://patch.socket.dev/{tail}"), &[]), + Some(want.clone()) + ); + for base in [ + "http://art.example/artifactory/socket-patch", + "http://art.example/artifactory/gopatch", + "http://art.example/patch/npm", + "http://art.example", + ] { + let origins = [mirror_entry(base)]; + assert_eq!( + hosted_served_path(&format!("{base}/{tail}"), &origins), + Some(want.clone()), + "{base}" + ); + } + // Below a mirror's base, the serve level must come first. + let base = "http://art.example/artifactory/socket-patch"; + let origins = [mirror_entry(base)]; + assert_eq!( + hosted_served_path(&format!("{base}/extra/{tail}"), &origins), + None + ); + // Not under the base: not hosted at all. + assert_eq!( + hosted_served_path(&format!("http://art.example/other/{tail}"), &origins), + None + ); + } } diff --git a/crates/socket-patch-core/src/vex/discover/mod.rs b/crates/socket-patch-core/src/vex/discover/mod.rs index 8df5f54f7..70f9395a7 100644 --- a/crates/socket-patch-core/src/vex/discover/mod.rs +++ b/crates/socket-patch-core/src/vex/discover/mod.rs @@ -2289,6 +2289,11 @@ impl<'a> DiscoverCtx<'a> { self.origin.hosted_uuid(url) } + /// [`OriginPolicy::hosted_served_path`] under this run's origins. + pub(crate) fn hosted_served_path(&self, url: &str) -> Option> { + self.origin.hosted_served_path(url) + } + /// [`OriginPolicy::locate`] under this run's origins. pub(crate) fn locate(&self, s: &str, opts: LocateOpts) -> Located { self.origin.locate(s, opts) diff --git a/crates/socket-patch-core/src/vex/discover/vlt.rs b/crates/socket-patch-core/src/vex/discover/vlt.rs index 2ba89e9b3..3c49ed4ae 100644 --- a/crates/socket-patch-core/src/vex/discover/vlt.rs +++ b/crates/socket-patch-core/src/vex/discover/vlt.rs @@ -85,7 +85,6 @@ use crate::constants::npm_family::{VLT_CONFIG, VLT_LOCK}; use crate::patch::redirect::hosted_url_names; use crate::patch::redirect::vlt::{discarding_lock_codes, discarding_lock_detail}; use crate::utils::digest::is_sri_pin; -use crate::utils::purl::percent_decode_purl_component; use crate::vendor::lock_inventory::vlt::{vlt_lock_model, VltLockNode}; use crate::vendor::lock_inventory::LockIntegrity; use crate::vendor::vlt_bundled::store_bundled_copies; @@ -347,7 +346,7 @@ fn classify_registry(ctx: &DiscoverCtx<'_>, node: &VltLockNode) -> Classified { node.name )); } - if !hosted_url_names(url, name, version) || !embedded_identity_agrees(url, name, version) { + if !hosted_url_names(url, name, version) || !embedded_identity_agrees(ctx, url, name, version) { return invalid(format!( "{key}: {url:?} is not an artifact of {name}@{version} (its leaf must be the \ package's own -.tgz and its path must embed that name and \ @@ -381,17 +380,13 @@ fn classify_registry(ctx: &DiscoverCtx<'_>, node: &VltLockNode) -> Classified { /// //`, the name spelled over one or more segments, /// each percent-decoded) embeds `name@version`. The token-only /// `/patch/npm///` shape embeds neither and agrees; any -/// other path does not. -fn embedded_identity_agrees(url: &str, name: &str, version: &str) -> bool { - let Ok(parsed) = reqwest::Url::parse(url) else { +/// other path does not. The path is the one the patch server serves, read +/// below a patch mirror's base or a deployment's path prefix +/// ([`DiscoverCtx::hosted_served_path`]). +fn embedded_identity_agrees(ctx: &DiscoverCtx<'_>, url: &str, name: &str, version: &str) -> bool { + let Some(segments) = ctx.hosted_served_path(url) else { return false; }; - let Some(segments) = parsed.path_segments() else { - return false; - }; - let segments: Vec = segments - .map(|s| percent_decode_purl_component(s).into_owned()) - .collect(); let Some(rest) = segments .strip_prefix(&["patch".to_string(), "npm".to_string()]) .filter(|rest| rest.len() == 3 || rest.len() >= 5) @@ -528,6 +523,58 @@ mod tests { } } + /// A pin a mirror run wrote sits under the mirror's base + /// (`/patch/npm///…`): the name and version it + /// embeds are read below the base, so the node is the hosted ref it is. + /// Without the mirror configured the same url is on no patch host. + #[tokio::test] + async fn a_pin_under_a_patch_mirror_base_is_a_hosted_ref() { + let base = "http://127.0.0.1:8081/artifactory/socket-patch"; + let mirrored = url(UUID_A, "left-pad-1.3.0.tgz").replace("https://patch.socket.dev", base); + let text = lock( + Some(1), + &[node( + "~npm~left-pad@1.3.0", + "left-pad", + Some(SRI), + Some(&mirrored), + )], + ); + let p = Project::new().with_origin(&crate::origin::mirror_entry(base)); + p.write("vlt-lock.json", &text); + let out = p.run(|c, o| Box::pin(super::extract(c, o))).await; + assert_refs(&out, &[(PURL, UUID_A, WiringMode::Hosted)]); + assert!(out.diagnostics.is_empty(), "{:?}", out.diagnostics); + + // The name or version the mirrored path embeds must still agree. + let other = mirrored.replace("/left-pad/1.3.0/", "/left-pad/1.2.0/"); + let text = lock( + Some(1), + &[node( + "~npm~left-pad@1.3.0", + "left-pad", + Some(SRI), + Some(&other), + )], + ); + let p = Project::new().with_origin(&crate::origin::mirror_entry(base)); + p.write("vlt-lock.json", &text); + let out = p.run(|c, o| Box::pin(super::extract(c, o))).await; + assert!(out.refs.is_empty(), "{:?}", out.refs); + + let out = discover(&lock( + Some(1), + &[node( + "~npm~left-pad@1.3.0", + "left-pad", + Some(SRI), + Some(&mirrored), + )], + )) + .await; + assert!(out.refs.is_empty(), "{:?}", out.refs); + } + fn lock_with_options(version: &str, options: &str, nodes: &[String]) -> String { format!( "{{\n{version} \"options\": {options},\n \"nodes\": {{\n {}\n }},\n \ diff --git a/docs/configuration.md b/docs/configuration.md index 4cca0f4c5..c0b4c2206 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -74,8 +74,9 @@ Empty environment values are treated as unset. - `SOCKET_PATCH_MIRROR_URL` (experimental) names a mirror of Socket's patch server, such as an Artifactory remote repository, for builds that may only fetch from an internal host. Hosted mode then pins patches under that base, - and every command reads the pins there. Set it wherever Socket Patch runs - for the project; a repository file cannot set it. It is for Socket + and every command reads the pins there (a Go build also lists the base + first in `GOPROXY`). Set it wherever Socket Patch runs for the project; a + repository file cannot set it. It is for Socket Enterprise customers and may change in any release: ask Socket for the setup guide. The rules are in the [CLI contract](../crates/socket-patch-cli/CLI_CONTRACT.md#patch-mirror-experimental).