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
192 changes: 192 additions & 0 deletions crates/socket-patch-cli/tests/in_process_pnpm_registry_cleanup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1930,3 +1930,195 @@ async fn the_removed_entries_are_listed_for_a_person() {
);
assert_gone_cleaned(root, "removed");
}

/// The patch record of [`KEPT`], for a `vex` that attests from the lock.
async fn mock_view(server: &MockServer) {
Mock::given(method("GET"))
.and(path(format!("/v0/orgs/{ORG}/patches/view/{}", KEPT.uuid)))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"uuid": KEPT.uuid,
"purl": KEPT.purl(),
"publishedAt": "2024-01-01T00:00:00Z",
"files": {
"package/index.js": {
"beforeHash": "a".repeat(64),
"afterHash": "b".repeat(64),
}
},
"vulnerabilities": {
"GHSA-rout-pnpm-vexx": {
"cves": ["CVE-2024-9"],
"summary": "registry route vex fixture",
"severity": "high",
"description": "d"
}
},
"description": "x", "license": "MIT", "tier": "free"
})))
.mount(server)
.await;
}

/// `vex` on a checkout with nothing installed: the number of
/// `not_affected` statements it wrote, and what it said.
fn vex_from_the_lock(root: &Path, server: &MockServer) -> (usize, String) {
let _ = std::fs::remove_dir_all(root.join("node_modules"));
let out = root.join("out.vex.json");
let _ = std::fs::remove_file(&out);
let mut cmd = hermetic::binary_command();
cmd.args(["vex", "--product", "pkg:npm/consumer@0.0.0", "--output"])
.arg(&out)
.args(["--patch-server-url", HOST, "--cwd", root.to_str().unwrap()])
.args([
"--api-url",
&server.uri(),
"--org",
ORG,
"--api-token",
"fake",
]);
let said = cmd.output().expect("run socket-patch vex");
let attested = std::fs::read_to_string(&out)
.ok()
.and_then(|text| serde_json::from_str::<Value>(&text).ok())
.and_then(|doc| doc["statements"].as_array().cloned())
.unwrap_or_default()
.iter()
.filter(|statement| statement["status"] == "not_affected")
.count();
(attested, String::from_utf8_lossy(&said.stderr).into_owned())
}

/// pnpm installs a routed lock only while pnpm-workspace.yaml declares the
/// registry and the override. With the override gone a frozen install
/// fails and a plain `pnpm install` takes the upstream release back; with
/// the registry gone, or the file left out of the commit, nothing
/// installs. `vex` attested the patch from the lock all the same (#2404).
/// The pin is still the project's: a hosted re-scan declares the route
/// again, and `rollback` still restores the upstream entry.
#[tokio::test]
async fn vex_attests_a_routed_pin_only_while_the_workspace_file_routes_it() {
let server = MockServer::start().await;
mock_api(&server, &[&KEPT], &[]).await;
mock_view(&server).await;
let routed_lock = lock(&[KEPT.recorded()], &[KEPT.routed()]);
let head = "packages:\n - '.'\n";
let registry = format!("namedRegistries:\n {}: {}\n", KEPT.alias, KEPT.address());
let route = format!(
"overrides:\n '{}': '{}:{}'\n",
KEPT.release(),
KEPT.alias,
KEPT.version
);

let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
write_project(
root,
&[KEPT.routed()],
Some(&created(&[&KEPT])),
&routed_lock,
);
let (attested, said) = vex_from_the_lock(root, &server);
assert_eq!(attested, 1, "the route as a scan writes it:\n{said}");

for (case, workspace, names) in [
(
"the override gone",
Some(format!("{head}{registry}")),
"`overrides` does not declare",
),
(
"the registry gone",
Some(format!("{head}{route}")),
"`namedRegistries` does not declare",
),
(
"both gone",
Some(head.to_string()),
"`namedRegistries` does not declare",
),
("no workspace file", None, "there is no pnpm-workspace.yaml"),
] {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
write_project(root, &[KEPT.routed()], workspace.as_deref(), &routed_lock);
let (attested, said) = vex_from_the_lock(root, &server);
assert_eq!(attested, 0, "{case}: attested from the lock alone:\n{said}");
for needle in [
names,
"pnpm-lock.yaml: the lock routes pkg:npm/kept-pkg@1.0.0",
"socket-patch scan --mode hosted",
] {
assert!(said.contains(needle), "{case}: no {needle:?} in:\n{said}");
}

// The remedy the message gives: the scan reads the pin as the
// project's own, declares the route again and changes no lock.
write_project(root, &[KEPT.routed()], workspace.as_deref(), &routed_lock);
let (code, doc) = scan_hosted(root, &server, &[]);
assert_eq!(code, Some(0), "{case}: {doc}");
// The run put a reference of this patch back into the project's
// files, so it reports the pin as changed: the file it rewrote is
// one to commit.
let pin_changed: Vec<&Value> = doc["events"]
.as_array()
.unwrap()
.iter()
.filter(|event| event["purl"] == KEPT.purl().as_str())
.map(|event| &event["details"]["pinChanged"])
.collect();
assert_eq!(pin_changed, [&json!(true)], "{case}: {doc}");
let declared = read(root, "pnpm-workspace.yaml").unwrap_or_default();
assert!(
declared.contains(&registry) && declared.contains(&route),
"{case}: the re-scan left the route undeclared:\n{declared}"
);
assert_eq!(
read(root, "pnpm-lock.yaml").as_deref(),
Some(routed_lock.as_str()),
"{case}"
);
let (attested, said) = vex_from_the_lock(root, &server);
assert_eq!(attested, 1, "{case}: after the re-scan:\n{said}");
}

// A member with a lock of its own, run on its own: the route is in
// the workspace file above it, which pnpm reads and this run does not.
let tmp = tempfile::tempdir().unwrap();
let member = tmp.path().join("packages").join("a");
std::fs::create_dir_all(&member).unwrap();
std::fs::write(
tmp.path().join("pnpm-workspace.yaml"),
format!("packages:\n - 'packages/*'\nsharedWorkspaceLockfile: false\n{registry}{route}"),
)
.unwrap();
write_project(&member, &[KEPT.routed()], None, &routed_lock);
let (attested, said) = vex_from_the_lock(&member, &server);
assert_eq!(attested, 1, "a member run on its own:\n{said}");

// An unwind still finds the pin it has to restore.
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
write_project(
root,
&[KEPT.routed()],
Some(&format!("{head}{registry}")),
&routed_lock,
);
let mut cmd = hermetic::binary_command();
cmd.env(
"SOCKET_NPM_REGISTRY",
format!("{}/npm-registry", server.uri()),
)
.args(["rollback", "--yes", "--json", "--patch-server-url", HOST])
.args(["--cwd", root.to_str().unwrap(), "--api-url", &server.uri()])
.args(["--org", ORG, "--api-token", "fake"]);
let (code, doc) = run_json(&mut cmd);
assert_eq!(code, Some(0), "{doc}");
let lock_text = read(root, "pnpm-lock.yaml").unwrap();
assert!(
!lock_text.contains(KEPT.alias) && !lock_text.contains(HOST),
"rollback left the route in the lock:\n{lock_text}"
);
}
41 changes: 41 additions & 0 deletions crates/socket-patch-core/src/formats/pnpm/named_registries.rs
Original file line number Diff line number Diff line change
Expand Up @@ -690,6 +690,47 @@ pub(crate) fn routes(text: &str, owned: &Owned) -> Vec<(HostedOverride, String)>
.collect()
}

/// Whether `text` (a pnpm-workspace.yaml) may route releases in a way this
/// reader cannot follow, so that a reader that finds no route there
/// cannot say the file declares none ([`routes`] and [`declared`] read
/// such a file as declaring nothing):
///
/// - a document that is not a single block mapping (a flow-style root,
/// several documents), of which no key is read;
/// - a registry map or an override map set more than once, on one line
/// with entries, or with an entry that is not a one-line `key: value`
/// ([`locate`]);
/// - a `registries` map, pnpm 12's other spelling of the registry map.
///
/// An empty inline mapping or a null (`overrides: {}`, `~`) declares
/// nothing, and is read as that.
pub(crate) fn routes_unreadable(text: &str) -> bool {
let lines: Vec<String> = text.split('\n').map(str::to_string).collect();
let values_of = |name: &str| -> Vec<&str> {
lines
.iter()
.filter_map(|line| top_level_key(line))
.filter(|(key, _)| key.as_str() == name)
.map(|(_, value)| value)
.collect()
};
let declares_nothing = |name: &str| match values_of(name).as_slice() {
[value] => {
let value: String = strip_comment(value).split_whitespace().collect();
matches!(value.as_str(), "{}" | "~" | "null")
}
_ => false,
};
block_insert_point(&lines).is_err()
|| !values_of("registries").is_empty()
|| [MapKind::Registry, MapKind::Override]
.into_iter()
.any(|kind| {
matches!(locate(&lines, kind.key()), Located::Unsupported(_))
&& !declares_nothing(kind.key())
})
}

/// Whether the file holds an entry of ours in any of the maps.
pub(crate) fn holds_ours(text: &str, owned: &Owned) -> bool {
MapKind::ALL.into_iter().any(|kind| {
Expand Down
7 changes: 7 additions & 0 deletions crates/socket-patch-core/src/vex/discover/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2316,6 +2316,13 @@ impl<'a> DiscoverCtx<'a> {
self.origin.hosted_uuid(url)
}

/// Whether `origin` (`http(s)://host[:port]`) is a patch server's
/// under this run's origins: where a registry address has to be for
/// the registry to be hosted mode's.
pub(crate) fn on_patch_server(&self, origin: &str) -> bool {
crate::origin::on_patch_server_origin(origin, self.origin.origins())
}

/// [`OriginPolicy::hosted_served_path`] under this run's origins.
pub(crate) fn hosted_served_path(&self, url: &str) -> Option<Vec<String>> {
self.origin.hosted_served_path(url)
Expand Down
Loading
Loading