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
2 changes: 1 addition & 1 deletion crates/socket-patch-cli/CLI_CONTRACT.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`).

Expand Down
1 change: 1 addition & 0 deletions crates/socket-patch-cli/src/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
}
}
Expand Down
148 changes: 148 additions & 0 deletions crates/socket-patch-cli/tests/mode_migration_pypi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
1 change: 1 addition & 0 deletions crates/socket-patch-core/src/api/vendor_prefetch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
2 changes: 2 additions & 0 deletions crates/socket-patch-core/src/patch/jvm_jar.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)] {
Expand Down Expand Up @@ -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)
Expand Down
68 changes: 64 additions & 4 deletions crates/socket-patch-core/src/patch/redirect/pipenv.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down Expand Up @@ -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)]
Expand Down
38 changes: 38 additions & 0 deletions crates/socket-patch-core/src/utils/hatch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String, String> {
[(
"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", &current)
.unwrap_or_else(|e| panic!("{ours}: our earlier reference refused: {e}"));
assert!(edits["pyproject.toml"].contains(&current), "{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", &current).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]
Expand Down
Loading
Loading