diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 311962014..5423dea82 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -556,7 +556,7 @@ A patch mirror is a caching proxy the operator runs in front of the patch server * **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. * **What every command reads.** The mirror's base counts as a patch host for `list`, `vex`, `rollback`, `remove`, `vendor`, `repair` and `scan` ("Patch hosts" under Manifest-less VEX): a mirrored reference is the patch server's own path under that base. A URL elsewhere on the mirror's host, in another repository of it, is not one: unlike a `--patch-server-url` origin, which holds its whole host, the mirror holds only what is under its base. Without the setting those references are on a host the run was not given and are not hosted pins. What a command downloads for itself while it restores a pin (a yarn berry checksum) comes from the patch server, never the mirror. -* **A source of the project's own on the mirror's host.** The yarn berry, Bun, Poetry and PDM rewriters take over an earlier hosted pin in place when it shares the new one's origin and file name. Under a mirror it must also sit under the mirror's base, so a fork of the same name and version in another repository of that host stays the project's own source and is refused as any other foreign source is. +* **A source of the project's own on the mirror's host.** The yarn berry, Bun, Poetry and PDM rewriters take over an earlier hosted pin in place when it shares the new one's origin and file name. The Pipenv, `pyproject.toml` / inline-script (PEP 723) and Hatch rewriters, and the uv.lock / `pylock.toml` direct-URL entries, take one over when it is in the patch server's path shape for the same package and version, on Socket's patch server or on the new one's origin; the `pyproject.toml` / inline-script and lock rewriters also take over the same artifact URL with only its grant token rotated. Under a mirror a pin on the mirror's host must also sit under the mirror's base, so a fork of the same name and version in another repository of that host, even one in the patch server's path shape, stays the project's own source and is refused as any other foreign source is. * **A run that was not given the mirror leaves its pins alone.** Before the rewrite, a candidate whose patch uuid one of the project's candidate files already pins through a URL in the hosted shape on an origin that is neither Socket's patch server, a configured origin, nor an origin of this run's own grants is `skipped` / `redirect_pin_on_unconfigured_host`, with a warning naming the file, the host and the setting. Nothing is written for it. This holds with or without a mirror configured: a hosted run never moves a pin off a host it does not know onto the patch server. * **In-memory engine.** `hosted-bundle` and the embedding addon have no mirror setting: they write the patch server's own URLs, and they too leave a pin on a host their grants do not name alone (`redirect_pin_on_unconfigured_host`). diff --git a/crates/socket-patch-cli/src/args.rs b/crates/socket-patch-cli/src/args.rs index 2f1354fcd..1dcb35b37 100644 --- a/crates/socket-patch-cli/src/args.rs +++ b/crates/socket-patch-cli/src/args.rs @@ -722,6 +722,7 @@ impl GlobalArgs { use_public_proxy, vendor_url: self.vendor_url.clone(), patch_server_url: self.patch_server_url.clone(), + patch_server_origins: crate::commands::hosted_unwind::patch_server_origins(self), offline: self.offline, } } diff --git a/crates/socket-patch-cli/tests/mode_migration_pypi.rs b/crates/socket-patch-cli/tests/mode_migration_pypi.rs index f8c046fcf..800c4ecda 100644 --- a/crates/socket-patch-cli/tests/mode_migration_pypi.rs +++ b/crates/socket-patch-cli/tests/mode_migration_pypi.rs @@ -3413,6 +3413,154 @@ async fn pipenv_hosted_to_vendored_keeps_the_requirements_patched() { ); } +/// The path a patch mirror (an Artifactory remote repository of the patch +/// server) is served under on its host. +const MIRROR_PREFIX: &str = "/artifactory/socket-patch"; + +/// The hosted → vendored takeover of a Pipenv project whose pins a hosted +/// run wrote through a patch mirror (`--patch-mirror-url`): `vendor` with +/// the same mirror reads the mirrored `Pipfile.lock` entry as the hosted +/// pin it is, restores it and wires the vendored wheel, as it does a pin +/// on the patch server. +#[tokio::test] +async fn pipenv_hosted_through_a_mirror_to_vendored() { + let (_tmp, root) = project(); + stage_pipenv(&root); + let server = MockServer::start().await; + let hosted_url = mount_hosted_api(&server, true).await; + let mirror = MockServer::start().await; + Mock::given(method("HEAD")) + .and(path_regex(format!("^{MIRROR_PREFIX}/patch/pypi/"))) + .respond_with(ResponseTemplate::new(200)) + .mount(&mirror) + .await; + let base = format!("{}{MIRROR_PREFIX}", mirror.uri()); + let mirrored_url = hosted_url.replace(&server.uri(), &base); + + let uri = server.uri(); + let mut args = hosted_scan_args(&uri); + args.extend(["--patch-mirror-url", &base]); + let (code, env) = run_cli(&root, &args, &[]); + assert_eq!(code, 0, "hosted scan through the mirror: {env:#}"); + let lock = std::fs::read_to_string(root.join("Pipfile.lock")).unwrap(); + assert!( + lock.contains(&mirrored_url), + "hosted mode pins Pipfile.lock through the mirror:\n{lock}\n{env:#}" + ); + + stage_manifest(&root); + prebuilt_common::mount_project(&server, &root).await; + mount_patch_view(&server).await; + // The mirror alone, as an operator runs it: no `--patch-server-url`. + let mut args = vec!["vendor", "--vendor-url", &uri, "--patch-mirror-url", &base]; + args.extend(api_args(&uri)); + let (code, env) = run_cli(&root, &args, &[]); + assert_eq!(code, 0, "vendor takeover through the mirror: {env:#}"); + let lock = std::fs::read_to_string(root.join("Pipfile.lock")).unwrap(); + assert!( + lock.contains(&format!(".socket/vendor/pypi/{UUID}/")) && !lock.contains(&base), + "Pipfile.lock is wired to the vendored wheel:\n{lock}\n{env:#}" + ); +} + +/// The mirror is matched by its base, never by its host alone: a +/// `Pipfile.lock` entry in the patch server's path shape in another +/// repository of the mirror's host is the project's own file reference. +/// `vendor` with the mirror neither takes it over nor wires over it, and +/// leaves the lock as it was. +#[tokio::test] +async fn pipenv_vendor_leaves_a_pin_elsewhere_on_the_mirrors_host_alone() { + let (_tmp, root) = project(); + stage_pipenv(&root); + let server = MockServer::start().await; + let hosted_url = mount_hosted_api(&server, true).await; + let mirror = MockServer::start().await; + let base = format!("{}{MIRROR_PREFIX}", mirror.uri()); + let fork = hosted_url.replace( + &server.uri(), + &format!("{}/artifactory/pypi-local", mirror.uri()), + ); + let lock = std::fs::read_to_string(root.join("Pipfile.lock")).unwrap(); + let mut doc: Value = serde_json::from_str(&lock).unwrap(); + let six = doc["default"]["six"].as_object_mut().unwrap(); + six.remove("version"); + six.insert("file".into(), Value::String(fork.clone())); + let mut text = serde_json::to_string_pretty(&doc).unwrap(); + text.push('\n'); + std::fs::write(root.join("Pipfile.lock"), &text).unwrap(); + + stage_manifest(&root); + prebuilt_common::mount_project(&server, &root).await; + mount_patch_view(&server).await; + let uri = server.uri(); + let mut args = vec!["vendor", "--vendor-url", &uri, "--patch-mirror-url", &base]; + args.extend(api_args(&uri)); + let (code, env) = run_cli(&root, &args, &[]); + assert_ne!(code, 0, "the fork is not taken over: {env:#}"); + assert!( + env.to_string().contains("user-declared file reference"), + "the fork is the project's own source: {env:#}" + ); + assert_eq!( + std::fs::read_to_string(root.join("Pipfile.lock")).unwrap(), + text, + "the lock is left as it was" + ); +} + +/// A hosted run through a patch mirror takes over an earlier `Pipfile.lock` +/// pin only under the mirror's base. One in the patch server's path shape +/// for the same release in another repository of the mirror's host is the +/// project's own source: the Pipenv rewriter refuses it +/// (`redirect_pipenv_refused`) and the lock is left as it was. Before, it +/// was taken for an earlier pin because it shared the grant's host. +#[tokio::test] +async fn pipenv_hosted_through_a_mirror_leaves_a_fork_on_its_host_alone() { + let (_tmp, root) = project(); + stage_pipenv(&root); + let server = MockServer::start().await; + let hosted_url = mount_hosted_api(&server, true).await; + let mirror = MockServer::start().await; + Mock::given(method("HEAD")) + .and(path_regex(format!("^{MIRROR_PREFIX}/patch/pypi/"))) + .respond_with(ResponseTemplate::new(200)) + .mount(&mirror) + .await; + let base = format!("{}{MIRROR_PREFIX}", mirror.uri()); + // Another patch uuid, so only the rewriter decides whether it is ours. + let fork = hosted_url + .replace( + &server.uri(), + &format!("{}/artifactory/pypi-local", mirror.uri()), + ) + .replace(UUID, "6d4f2b3c-8e5a-4f7b-8c9d-2e3f4a5b6c7d"); + let lock = std::fs::read_to_string(root.join("Pipfile.lock")).unwrap(); + let mut doc: Value = serde_json::from_str(&lock).unwrap(); + let six = doc["default"]["six"].as_object_mut().unwrap(); + six.remove("version"); + six.insert("file".into(), Value::String(fork.clone())); + let mut text = serde_json::to_string_pretty(&doc).unwrap(); + text.push('\n'); + std::fs::write(root.join("Pipfile.lock"), &text).unwrap(); + + let uri = server.uri(); + let mut args = hosted_scan_args(&uri); + args.extend(["--patch-mirror-url", &base]); + let (_code, env) = run_cli(&root, &args, &[]); + assert!( + env["warnings"] + .as_array() + .is_some_and(|ws| ws.iter().any(|w| w["code"] == "redirect_pipenv_refused")), + "the fork is a foreign source: {env:#}" + ); + assert_eq!(hosted_pinned(&env), 0, "{env:#}"); + assert_eq!( + std::fs::read_to_string(root.join("Pipfile.lock")).unwrap(), + text, + "the lock is left as it was" + ); +} + /// `pip lock -r requirements.txt -o pylock.toml` (pip 26.2.2) over /// [`stage_pip_lock`]'s requirements.txt, byte for byte. const PIP_LOCK: &str = r#"lock-version = "1.0" diff --git a/crates/socket-patch-core/src/api/vendor_prefetch.rs b/crates/socket-patch-core/src/api/vendor_prefetch.rs index 397ec5a3a..259669d94 100644 --- a/crates/socket-patch-core/src/api/vendor_prefetch.rs +++ b/crates/socket-patch-core/src/api/vendor_prefetch.rs @@ -1484,6 +1484,7 @@ mod tests { use_public_proxy: false, vendor_url: None, patch_server_url: None, + patch_server_origins: Vec::new(), offline: false, }; let serial = vendor_like(&cfg, false).await; diff --git a/crates/socket-patch-core/src/patch/jvm_jar.rs b/crates/socket-patch-core/src/patch/jvm_jar.rs index 60838e10e..b1107077d 100644 --- a/crates/socket-patch-core/src/patch/jvm_jar.rs +++ b/crates/socket-patch-core/src/patch/jvm_jar.rs @@ -1321,6 +1321,7 @@ mod tests { use_public_proxy: true, vendor_url: None, patch_server_url: None, + patch_server_origins: Vec::new(), offline: true, }; for service in [None, Some(&cfg)] { @@ -1399,6 +1400,7 @@ mod tests { use_public_proxy: true, vendor_url: Some(server.uri()), patch_server_url: None, + patch_server_origins: Vec::new(), offline: false, }; (server, cfg) diff --git a/crates/socket-patch-core/src/patch/redirect/pipenv.rs b/crates/socket-patch-core/src/patch/redirect/pipenv.rs index 755b4e74f..bc11bba21 100644 --- a/crates/socket-patch-core/src/patch/redirect/pipenv.rs +++ b/crates/socket-patch-core/src/patch/redirect/pipenv.rs @@ -89,10 +89,11 @@ pub(super) fn rewrite( } /// Whether `value` is a Socket-issued hosted reference for `dep`: the shared -/// recognizer ([`replaceable_hosted_pin`]) accepts it on the grant's own -/// origin (patch.socket.dev, or a `--patch-server-url` host, path prefix -/// included), and it names this package and version. Such an entry is ours -/// to rotate; anything else is a user's or a fork's source. +/// recognizer ([`replaceable_hosted_pin`]) accepts it on Socket's patch +/// server, or on the grant's own origin under the base the grant is served +/// from (a path-prefixed `--patch-server-url` deployment's prefix, a patch +/// mirror's base), and it names this package and version. Such an entry is +/// ours to rotate; anything else is a user's or a fork's source. fn owned_url(value: &str, dep: &DepOverride) -> bool { replaceable_hosted_pin(value, &dep.artifact_url, &dep.name, &dep.version) } @@ -575,6 +576,65 @@ mod tests { assert!(!rotation.is_empty()); assert!(second.contains("/rotated/") && !second.contains("/tok/")); } + + /// Under a patch mirror (`--patch-mirror-url`) the grant's URL sits in + /// one repository of an artifact host that serves the project's own + /// packages too. An earlier pin is ours to rotate only under the + /// mirror's base; a URL in the patch server's path shape in another + /// repository of that host, or one that leaves the base through `..`, + /// is the project's own source. A pin on Socket's patch server is + /// still ours and moves onto the mirror in place. + #[test] + fn owned_url_under_a_mirror_needs_the_mirror_base() { + let base = "https://repo.example/artifactory/socket-patch"; + let tail = |token: &str| { + format!("patch/pypi/urllib3/1.26.18/{token}/patch-one/urllib3-1.26.18-py3-none-any.whl") + }; + let mut dep = dependency("urllib3", "1.26.18", "patch-one"); + let direct = dep.artifact_url.clone(); + dep.artifact_url = format!("{base}/{}", tail("new")); + let earlier = format!("{base}/{}", tail("old")); + assert!(owned_url(&earlier, &dep)); + assert!(owned_url(&direct, &dep), "the patch server is ours"); + for own in [ + format!( + "https://repo.example/artifactory/pypi-local/{}", + tail("old") + ), + format!( + "https://repo.example/artifactory/socket-patch-2/{}", + tail("old") + ), + format!("https://repo.example/{}", tail("old")), + format!("{base}/../pypi-local/{}", tail("old")), + ] { + assert!(!owned_url(&own, &dep), "{own}"); + } + + // Through the rewriter: the earlier mirrored pin and the pin on the + // patch server are rotated onto the grant; the fork is a conflict. + let pinned = |url: &str| { + let mut first = dep.clone(); + first.artifact_url = url.to_string(); + plan(&lock(), &first, None).unwrap().0 + }; + for ours in [earlier.as_str(), direct.as_str()] { + let (rewritten, edits) = plan(&pinned(ours), &dep, None).unwrap(); + assert!(!edits.is_empty(), "{ours}"); + assert!( + rewritten.contains(&dep.artifact_url) && !rewritten.contains(ours), + "{ours}" + ); + } + let fork = format!( + "https://repo.example/artifactory/pypi-local/{}", + tail("old") + ); + assert!(matches!( + plan(&pinned(&fork), &dep, None), + Err(PlanError::Conflict(_)) + )); + } } #[cfg(test)] diff --git a/crates/socket-patch-core/src/utils/hatch.rs b/crates/socket-patch-core/src/utils/hatch.rs index 4a07d03fa..49aece098 100644 --- a/crates/socket-patch-core/src/utils/hatch.rs +++ b/crates/socket-patch-core/src/utils/hatch.rs @@ -1108,6 +1108,44 @@ mod tests { } } + /// Under a patch mirror (`--patch-mirror-url`) an earlier direct + /// reference is ours only under the mirror's base (or on Socket's patch + /// server): one in the patch server's path shape in another repository + /// of the mirror's host is the project's own and must be reverted first. + #[test] + fn an_earlier_reference_under_a_mirror_needs_the_mirror_base() { + const BASE: &str = "https://repo.example/artifactory/socket-patch"; + const TAIL: &str = "patch/pypi/six/1.16.0/11111111-1111-4111-8111-111111111111/aaaaaaaa-0000-4000-8000-000000000001/six-1.16.0-py2.py3-none-any.whl"; + let current = format!( + "{BASE}/patch/pypi/six/1.16.0/22222222-2222-4222-8222-222222222222/aaaaaaaa-0000-4000-8000-000000000004/six-1.16.0-py2.py3-none-any.whl" + ); + let declared = |url: &str| -> BTreeMap { + [( + "pyproject.toml".to_string(), + format!("[project]\nname = \"app\"\nversion = \"0.1.0\"\ndependencies = [\"six @ {url}\"]\n"), + )] + .into_iter() + .collect() + }; + for ours in [ + format!("{BASE}/{TAIL}"), + format!("https://patch.socket.dev/{TAIL}"), + ] { + let edits = rewrite(&declared(&ours), "six", "1.16.0", ¤t) + .unwrap_or_else(|e| panic!("{ours}: our earlier reference refused: {e}")); + assert!(edits["pyproject.toml"].contains(¤t), "{ours}"); + } + for own in [ + format!("https://repo.example/artifactory/pypi-local/{TAIL}"), + format!("{BASE}/../pypi-local/{TAIL}"), + ] { + assert!( + rewrite(&declared(&own), "six", "1.16.0", ¤t).is_err(), + "{own} must stay a user source" + ); + } + } + /// Hatch (via pip/uv) selects a release under PEP 440, so /// `==1.26.18.0` and `==01.26.18` are exact pins of 1.26.18. #[test] diff --git a/crates/socket-patch-core/src/utils/python_script.rs b/crates/socket-patch-core/src/utils/python_script.rs index 9ff311e5d..f6b04cf5a 100644 --- a/crates/socket-patch-core/src/utils/python_script.rs +++ b/crates/socket-patch-core/src/utils/python_script.rs @@ -1115,6 +1115,68 @@ mod tests { } } + /// Under a patch mirror (`--patch-mirror-url`) the grant's URL sits in + /// one repository of an artifact host that serves the project's own + /// packages too: a project or inline script re-pins an earlier source + /// under the mirror's base, or on Socket's patch server, and refuses + /// one in the patch server's path shape in another repository of that + /// host, or one that leaves the base through `..`. + #[test] + fn an_earlier_source_under_a_mirror_needs_the_mirror_base() { + let base = "https://repo.example/artifactory/socket-patch"; + let mirrored_a = OWN_A.replace("https://patch.socket.dev", base); + let mirrored_b = OWN_B.replace("https://patch.socket.dev", base); + let project = + "[project]\nname = \"app\"\nversion = \"0.1.0\"\ndependencies = [\"six==1.16.0\"]\n"; + let script = "# /// script\n# dependencies = [\"six==1.16.0\"]\n# ///\n"; + type Rewrite = fn(&str, &str, &str, ArtifactSource<'_>) -> Result, String>; + let writers: [(&str, Rewrite); 2] = [ + (project, rewrite_project_metadata), + (script, rewrite_script_metadata), + ]; + for (original, rewrite) in writers { + for earlier in [mirrored_a.as_str(), OWN_A] { + let wired = rewrite(original, "six", "1.16.0", ArtifactSource::Url(earlier)) + .unwrap() + .unwrap(); + let repinned = rewrite(&wired, "six", "1.16.0", ArtifactSource::Url(&mirrored_b)) + .unwrap_or_else(|e| panic!("{earlier}: our earlier source refused: {e}")) + .expect("re-pinned"); + assert!( + repinned.contains(&mirrored_b) && !repinned.contains(earlier), + "{repinned}" + ); + } + let wired = rewrite(original, "six", "1.16.0", ArtifactSource::Url(&mirrored_a)) + .unwrap() + .unwrap(); + for own in [ + mirrored_a.replace("/socket-patch/", "/pypi-local/"), + mirrored_a.replace("/socket-patch/", "/socket-patch-2/"), + mirrored_a.replace("/artifactory/socket-patch/", "/"), + mirrored_a.replace("/socket-patch/", "/socket-patch/../pypi-local/"), + ] { + let user = wired.replace(&mirrored_a, &own); + assert!( + rewrite(&user, "six", "1.16.0", ArtifactSource::Url(&mirrored_b)).is_err(), + "{own} must stay a user source" + ); + // The uv.lock / pylock.toml direct-URL takeover asks the same + // question. + assert!( + !same_hosted_artifact(&own, &mirrored_b, "six", "1.16.0"), + "{own}" + ); + } + } + for ours in [mirrored_a.as_str(), OWN_A] { + assert!( + same_hosted_artifact(ours, &mirrored_b, "six", "1.16.0"), + "{ours}" + ); + } + } + /// A package declared in ANY project table (dependencies, an extra, a /// PEP 735 group, the legacy `[tool.uv] dev-dependencies`) is direct: its /// source needs no override. Anything else gets one. diff --git a/crates/socket-patch-core/src/vendor/cargo.rs b/crates/socket-patch-core/src/vendor/cargo.rs index 956aefa0e..8a745db4a 100644 --- a/crates/socket-patch-core/src/vendor/cargo.rs +++ b/crates/socket-patch-core/src/vendor/cargo.rs @@ -3472,6 +3472,7 @@ mod tests { use_public_proxy: false, vendor_url: None, patch_server_url: None, + patch_server_origins: Vec::new(), offline, } } diff --git a/crates/socket-patch-core/src/vendor/composer_lock.rs b/crates/socket-patch-core/src/vendor/composer_lock.rs index 77f04ebd2..46b33ee71 100644 --- a/crates/socket-patch-core/src/vendor/composer_lock.rs +++ b/crates/socket-patch-core/src/vendor/composer_lock.rs @@ -2224,6 +2224,7 @@ mod tests { use_public_proxy: false, vendor_url: None, patch_server_url: None, + patch_server_origins: Vec::new(), offline, } } diff --git a/crates/socket-patch-core/src/vendor/gem.rs b/crates/socket-patch-core/src/vendor/gem.rs index 0151109a7..557362fa9 100644 --- a/crates/socket-patch-core/src/vendor/gem.rs +++ b/crates/socket-patch-core/src/vendor/gem.rs @@ -7665,6 +7665,7 @@ mod tests { use_public_proxy: false, vendor_url: None, patch_server_url: None, + patch_server_origins: Vec::new(), offline, } } diff --git a/crates/socket-patch-core/src/vendor/golang.rs b/crates/socket-patch-core/src/vendor/golang.rs index 6b3ab488b..cf9b5aee9 100644 --- a/crates/socket-patch-core/src/vendor/golang.rs +++ b/crates/socket-patch-core/src/vendor/golang.rs @@ -1865,6 +1865,7 @@ mod tests { use_public_proxy: false, vendor_url: None, patch_server_url: None, + patch_server_origins: Vec::new(), offline, } } diff --git a/crates/socket-patch-core/src/vendor/lock_inventory/pypi.rs b/crates/socket-patch-core/src/vendor/lock_inventory/pypi.rs index 4be169671..82a6cdc35 100644 --- a/crates/socket-patch-core/src/vendor/lock_inventory/pypi.rs +++ b/crates/socket-patch-core/src/vendor/lock_inventory/pypi.rs @@ -192,19 +192,30 @@ pub(crate) fn hosted_pypi_reference(url: &str, origins: &[String]) -> Option bool { - hosted_pypi_reference(previous, &[current.to_string()]).is_some_and(|coords| { - canonicalize_pypi_name(&coords.name) == canonicalize_pypi_name(name) - && coords.version == version - }) + hosted_pypi_reference(previous, &[]) + .or_else(|| { + hosted_pypi_reference(previous, &[current.to_string()]) + .filter(|_| crate::origin::same_hosted_base(previous, current)) + }) + .is_some_and(|coords| { + canonicalize_pypi_name(&coords.name) == canonicalize_pypi_name(name) + && coords.version == version + }) } /// Inventory the pypi lock the project carries. Fetchable resolution @@ -814,6 +825,62 @@ mod tests { ); assert!(parse_pipfile_lock(&format!("\u{feff}\u{feff}{lock}")).is_err()); } + + /// The one "is this earlier pin ours" rule the Pipenv, inline-script + /// and Hatch rewriters share. Under a patch mirror, whose host serves + /// the project's own packages too, a pin on the grant's host is ours + /// only under the base the grant is served from; one on Socket's patch + /// server is ours wherever the grant is served. + #[test] + fn replaceable_hosted_pin_under_a_mirror_needs_the_mirror_base() { + let leaf = "urllib3-1.26.18-py2.py3-none-any.whl"; + let tail = |token: &str| format!("patch/pypi/urllib3/1.26.18/{token}/u1/{leaf}"); + let base = "https://repo.example/artifactory/socket-patch"; + let current = format!("{base}/{}", tail("new")); + let ours = |previous: &str| { + super::replaceable_hosted_pin(previous, ¤t, "urllib3", "1.26.18") + }; + for previous in [ + format!("{base}/{}", tail("old")), + format!("{base}/{}#sha256=00", tail("old")), + format!( + "HTTPS://Repo.Example:443/artifactory/socket-patch/{}", + tail("old") + ), + format!("https://patch.socket.dev/{}", tail("old")), + ] { + assert!(ours(&previous), "{previous}"); + } + for previous in [ + format!( + "https://repo.example/artifactory/pypi-local/{}", + tail("old") + ), + format!( + "https://repo.example/artifactory/socket-patch-2/{}", + tail("old") + ), + format!("https://repo.example/{}", tail("old")), + format!("{base}/../pypi-local/{}", tail("old")), + format!("{base}/%2e%2e/pypi-local/{}", tail("old")), + format!( + "https://other.example/artifactory/socket-patch/{}", + tail("old") + ), + format!("{base}/{}", tail("old")).replace("1.26.18", "1.26.17"), + ] { + assert!(!ours(&previous), "{previous}"); + } + // Served from the root of its host (Socket's patch server, or a + // `--patch-server-url` deployment): the origin decides, as before. + let root = format!("http://127.0.0.1:4545/{}", tail("new")); + assert!(super::replaceable_hosted_pin( + &format!("http://127.0.0.1:4545/{}", tail("old")), + &root, + "urllib3", + "1.26.18" + )); + } } #[cfg(test)] diff --git a/crates/socket-patch-core/src/vendor/maven_repo.rs b/crates/socket-patch-core/src/vendor/maven_repo.rs index 85104d5c1..da7a93d28 100644 --- a/crates/socket-patch-core/src/vendor/maven_repo.rs +++ b/crates/socket-patch-core/src/vendor/maven_repo.rs @@ -3942,6 +3942,7 @@ mod tests { use_public_proxy: false, vendor_url: None, patch_server_url: None, + patch_server_origins: Vec::new(), offline, } } diff --git a/crates/socket-patch-core/src/vendor/mod.rs b/crates/socket-patch-core/src/vendor/mod.rs index 8d38a2ca4..6a8c9abb8 100644 --- a/crates/socket-patch-core/src/vendor/mod.rs +++ b/crates/socket-patch-core/src/vendor/mod.rs @@ -348,6 +348,12 @@ pub struct VendorServiceConfig { /// Optional override for the step-2 download host (rewrites the host of the /// server-returned absolute URL). pub patch_server_url: Option, + /// The run's patch-server origins, as every hosted reader recognizes + /// them: the `--patch-server-url` deployment and a patch mirror's base + /// (`crate::origin::mirror_entry`, which holds only what is under that + /// base). A backend's guards name a hosted reference on one of them, or + /// on Socket's own patch server, as socket-patch's own hosted pin. + pub patch_server_origins: Vec, /// Strict airgap — never contact the network. pub offline: bool, } diff --git a/crates/socket-patch-core/src/vendor/npm_common.rs b/crates/socket-patch-core/src/vendor/npm_common.rs index 0e477052c..0b1b644ef 100644 --- a/crates/socket-patch-core/src/vendor/npm_common.rs +++ b/crates/socket-patch-core/src/vendor/npm_common.rs @@ -1300,6 +1300,7 @@ mod tests { use_public_proxy: false, vendor_url: None, patch_server_url: None, + patch_server_origins: Vec::new(), offline: false, } } diff --git a/crates/socket-patch-core/src/vendor/npm_lock.rs b/crates/socket-patch-core/src/vendor/npm_lock.rs index cb5df69ba..bb2e82632 100644 --- a/crates/socket-patch-core/src/vendor/npm_lock.rs +++ b/crates/socket-patch-core/src/vendor/npm_lock.rs @@ -5898,6 +5898,7 @@ mod tests { use_public_proxy: false, vendor_url: None, patch_server_url: None, + patch_server_origins: Vec::new(), offline, } } diff --git a/crates/socket-patch-core/src/vendor/nuget_feed.rs b/crates/socket-patch-core/src/vendor/nuget_feed.rs index 621d80c33..8a4e6388b 100644 --- a/crates/socket-patch-core/src/vendor/nuget_feed.rs +++ b/crates/socket-patch-core/src/vendor/nuget_feed.rs @@ -5178,6 +5178,7 @@ mod tests { use_public_proxy: false, vendor_url: None, patch_server_url: None, + patch_server_origins: Vec::new(), offline: false, }; @@ -5259,6 +5260,7 @@ mod tests { use_public_proxy: false, vendor_url: None, patch_server_url: None, + patch_server_origins: Vec::new(), offline: false, }; @@ -6134,6 +6136,7 @@ mod tests { use_public_proxy: false, vendor_url: None, patch_server_url: None, + patch_server_origins: Vec::new(), offline: false, }; @@ -6329,6 +6332,7 @@ mod tests { use_public_proxy: false, vendor_url: None, patch_server_url: None, + patch_server_origins: Vec::new(), offline: false, } } diff --git a/crates/socket-patch-core/src/vendor/pypi.rs b/crates/socket-patch-core/src/vendor/pypi.rs index a3256b393..0d5b30dff 100644 --- a/crates/socket-patch-core/src/vendor/pypi.rs +++ b/crates/socket-patch-core/src/vendor/pypi.rs @@ -2080,10 +2080,11 @@ pub async fn vendor_pypi_with_pipenv_version<'a>( pipenv_version: &tokio::sync::OnceCell>, installed_sites: &InstalledSiteListings, ) -> VendorOutcome { + // The run's patch-server origins, its patch mirror's base included, as + // the takeover and the `scan` / `get` preview read them. let hosted_origins: Vec = service - .and_then(|s| s.patch_server_url.clone()) - .into_iter() - .collect(); + .map(|s| s.patch_server_origins.clone()) + .unwrap_or_default(); let PypiPrelude { base, version, @@ -6089,6 +6090,7 @@ wheels = [ use_public_proxy: false, vendor_url: None, patch_server_url: None, + patch_server_origins: Vec::new(), offline, } } @@ -7718,6 +7720,64 @@ wheels = [ .await } + /// The Pipenv backend reads the run's patch-server origins from its + /// service config, a patch mirror's base (`--patch-mirror-url`) + /// included, as the takeover and the `scan` / `get` preview do. A live + /// pin under the mirror's base is socket-patch's own hosted pin, named + /// with the rollback remedy; one in the same shape in another + /// repository of the mirror's host is the project's own file reference. + /// Before, the backend counted only `--patch-server-url` and called the + /// mirrored pin user-declared. + #[tokio::test] + async fn pipenv_guard_reads_a_mirrored_pin_as_hosted_only_under_the_mirror_base() { + const BASE: &str = "https://repo.example/artifactory/socket-patch"; + const TAIL: &str = "patch/pypi/six/1.16.0/grant/9f6b2c4e-1d3a-4f6b-8c2d-7e5a9b1c3d5f/\ + six-1.16.0-py2.py3-none-any.whl"; + let mut cfg = pypi_service_cfg("http://127.0.0.1:9", VendorSource::default(), true); + cfg.patch_server_origins = vec![ + "https://patch.socket.dev".to_string(), + crate::origin::mirror_entry(BASE), + ]; + for (url, hosted) in [ + (format!("{BASE}/{TAIL}"), true), + ( + format!("https://repo.example/artifactory/pypi-local/{TAIL}"), + false, + ), + (format!("{BASE}/../pypi-local/{TAIL}"), false), + ] { + let fx = pipenv_e2e_fixture().await; + let lock = PIPENV_REGISTRY_LOCK + .replace(r#""version": "==1.16.0""#, &format!(r#""file": "{url}""#)); + touch(&fx.root, "Pipfile.lock", &lock).await; + let sources = PatchSources::blobs_only(&fx.blobs); + let outcome = vendor_pypi_with_pipenv_version( + "pkg:pypi/six@1.16.0", + &fx.site_packages, + &fx.root, + &fx.record, + &sources, + "2026-06-09T00:00:00Z", + true, + false, + Some(&cfg), + &tokio::sync::OnceCell::new_with(Some(Some(2026))), + &InstalledSiteListings::default(), + ) + .await; + let VendorOutcome::Refused { code, detail } = outcome else { + panic!("{url}: a live file reference is refused: {outcome:?}"); + }; + assert_eq!(code, "pypi_pipenv_source_already_exists", "{url}"); + let expected = if hosted { + "HOSTED Socket patch" + } else { + "user-declared" + }; + assert!(detail.contains(expected), "{url}: {detail}"); + } + } + /// #612: `pipenv requirements > requirements.txt` beside Pipfile.lock is /// a second install source (Docker / plain pip). Vendored mode must wire /// both, as hosted mode does, and revert must restore both byte for byte. diff --git a/crates/socket-patch-core/src/vendor/pypi_pipenv.rs b/crates/socket-patch-core/src/vendor/pypi_pipenv.rs index 13ce94e51..61a590087 100644 --- a/crates/socket-patch-core/src/vendor/pypi_pipenv.rs +++ b/crates/socket-patch-core/src/vendor/pypi_pipenv.rs @@ -200,10 +200,11 @@ pub(super) fn hash_export_warning( /// writing). Entries match by PEP 503 canonical NAME in every package /// category. Registry pins and existing vendored wheel identities /// must both match the selected patch version. `hosted_origins` are the -/// run's `--patch-server-url` origins: a hosted reference on one of them -/// (or on patch.socket.dev) is refused with the rollback remedy, any other -/// file reference as user-declared. Production callers pass the ledger -/// through [`check_target_guards_superseding`]. +/// run's patch-server origins (`--patch-server-url`, and a patch mirror's +/// base as `crate::origin::mirror_entry` gives it): a hosted reference on +/// one of them (or on patch.socket.dev) is refused with the rollback +/// remedy, any other file reference as user-declared. Production callers +/// pass the ledger through [`check_target_guards_superseding`]. #[cfg(test)] pub(super) fn check_target_guards( p: &PipenvProject, diff --git a/crates/socket-patch-core/src/vendor/service_fetch.rs b/crates/socket-patch-core/src/vendor/service_fetch.rs index b3c2e2b66..eca4508e1 100644 --- a/crates/socket-patch-core/src/vendor/service_fetch.rs +++ b/crates/socket-patch-core/src/vendor/service_fetch.rs @@ -510,6 +510,7 @@ mod tests { use_public_proxy: false, vendor_url: None, patch_server_url: None, + patch_server_origins: Vec::new(), offline: false, } } @@ -641,6 +642,7 @@ mod tests { use_public_proxy: false, vendor_url: None, patch_server_url: None, + patch_server_origins: Vec::new(), offline: false, }; assert!(matches!( diff --git a/crates/socket-patch-core/src/vendor/test_support.rs b/crates/socket-patch-core/src/vendor/test_support.rs index f6a447e88..1989ff75e 100644 --- a/crates/socket-patch-core/src/vendor/test_support.rs +++ b/crates/socket-patch-core/src/vendor/test_support.rs @@ -62,6 +62,7 @@ pub(crate) fn service_cfg( use_public_proxy: false, vendor_url: None, patch_server_url: None, + patch_server_origins: Vec::new(), offline, } } diff --git a/crates/socket-patch-core/tests/vlt_locks.rs b/crates/socket-patch-core/tests/vlt_locks.rs index b0ba99ddb..2a38e5081 100644 --- a/crates/socket-patch-core/tests/vlt_locks.rs +++ b/crates/socket-patch-core/tests/vlt_locks.rs @@ -607,6 +607,7 @@ async fn vendor(case: &Case, staged: &Staged) -> VendorOutcome { use_public_proxy: true, vendor_url: None, patch_server_url: None, + patch_server_origins: Vec::new(), offline: false, }; vendor_npm_any(