diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 5408a1794..8f2665cba 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -2323,6 +2323,7 @@ command's integration tests check its output. | `redirect_maven_multimodule_unsupported` | `warnings[]` (warning) | scan / get `--mode hosted` (Maven): the root `pom.xml` heads a reactor that cannot be planned: a module pom is missing or not readable as a pom, a `` path is a property or leaves the project, or the grant serves the patched artifact under its original version (a same-GAV grant). The detail carries the reason. The poms and `.mvn/` stay byte-identical and the dep is not counted as redirected. A reactor that can be read is patched module by module: see [Hosted Maven reactors and property versions](#hosted-maven-reactors-and-property-versions). | | `redirect_maven_pin_would_move_module` | `warnings[]` (warning) | scan / get `--mode hosted` (Maven reactor): a parent pom resolves the base version itself above a module that resolves another version, so the parent takes no pin (Maven's management always reaches the children); the modules below it that select the base version are pinned. Also reported when a pin an earlier run wrote is taken out because a module it reaches now resolves another version, which the pin would hold back (the `redirect_maven_dep_management` edit has `action: "removed"`). Exit 0. | | `redirect_maven_edit_not_reversible` | `warnings[]` (warning) | scan / get `--mode hosted` (Maven): a pom would take an edit that `rollback` could not undo byte for byte from the pom alone. A pin in a `` that holds no entry (which would be left changed or removed) leaves that one pom as it is: the modules it would have wired stay unpatched, and `vex` withholds the statement while one of them resolves the base version. Any other case (a `` section that would not come back as it was) refuses the whole plan for the patch: nothing is written and the dep is not counted as redirected. Exit 0. See [Hosted Maven reactors and property versions](#hosted-maven-reactors-and-property-versions). | +| `redirect_maven_mirror_captures_repository` | `warnings[]` (warning) | scan / get `--mode hosted` (Maven, on disk): the Maven settings of the scanning machine declare a `` whose `` matches the `socket-patch-` repository the pin needs (`*`, `external:*`, or a list without `!socket-patch-`), without naming that repository itself (alone, or as one id of a list). The mirror does not hold the patched version, so the build could not resolve it: nothing is written for the dep, `pom.xml` and `.mvn/` stay byte-identical, and the dep is not counted as redirected or attested by the same run's `--vex`, whatever an earlier run left in the poms. Exit 0. Reported only for a dep that would get (or already has) the repository. The detail names the mirror id, its ``, the settings file and the exclusion to add, and says that only this machine's settings were read. It offers `scan --mode vendored` with its bound: vendored mode gets past a mirror through `maven.repo.local.tail`, which Maven reads from 3.9.2 on. When the project's Maven Wrapper pins an older Maven the detail does not offer it as the project stands, and says what makes it work (a wrapper at 3.9.2 or later, or the mirror also leaving `socket-patch-vendor` out). See [Hosted Maven behind a mirror](#hosted-maven-behind-a-mirror) | | `redirect_gem_no_checksums_section` | `warnings[]` (warning) | scan/get `--mode hosted` (gem): the lock has no `CHECKSUMS` section (Bundler < 2.6 does not write one), so it cannot record the sha256 of the patched gems. They are redirected all the same (manifest and lock converged, frozen installs accept the pair) and pinned by source alone. Reported once per run, naming the gems; relock with Bundler ≥ 2.6 (`bundle lock --add-checksums`) and re-run to pin the checksums too. | | `redirect_gem_merged_lock_layout` | `warnings[]` (warning) | scan/get `--mode hosted` (gem): the lock was written by Bundler < 2.2 (`BUNDLED WITH`), which lists every gem source in ONE `GEM` section, so this run added the patch registry to that section's `remote:` lines. The pair installs with that Bundler, frozen / deployment mode included. Newer Bundlers deprecate such a section and from 2.5 on refuse the pair under frozen / deployment mode: if a newer Bundler installs the project, run `bundle lock` with it, commit the lock and re-run the hosted scan. Raised only by a run that wrote the lock. | | `redirect_gem_unrecognized_declaration` | `warnings[]` (warning) | scan/get `--mode hosted` (gem): the gem's declaration cannot take a `source:` option in place (the detail gives the reason). The gem is skipped and the manifest and lock stay byte-identical for it; write the declaration as one `gem "", …` call with literal arguments on a line of its own, or use `--mode vendored` / `--mode agent`. | @@ -3011,6 +3012,65 @@ not reach that resolves the base version, or whose selection cannot be told on the machine that runs `vex`, withholds the attestation, with the module named. `vendor --check` does not ask this. +### Hosted Maven behind a mirror + +A `` in Maven's `settings.xml` replaces every repository its +`` matches. A `*` (or `external:*`) therefore +replaces the `socket-patch-` repository a hosted pin adds, and the +mirror does not hold the suffixed version: the build fails to resolve it. + +Before `scan --mode hosted` writes anything for a Maven patch on disk, it +reads the mirrors Maven is configured with on that machine and evaluates +Maven's own rule against the repository the pin would add (its id +`socket-patch-`, its `https://` URL, the `default` layout): + +* settings read: the user settings (`-s` / `--settings` from `MAVEN_ARGS`, + else from `.mvn/maven.config`, else `/.m2/settings.xml`; + `.mvn/maven.config` is read as the project's Maven reads it: one + argument per line under a Maven Wrapper that pins 3.9 or later, so a + settings path may hold spaces, split on whitespace under one that pins + an older Maven, and both ways, each as a way the build may be started, + when no wrapper says which) merged + over the global settings (`-gs` / `--global-settings` likewise, else + `conf/settings.xml` of the Maven Wrapper's unpacked distribution, in + either layout the wrapper unpacks to, else of the `mvn` on `PATH`, else, + with none there, of `$MAVEN_HOME` / `$M2_HOME`; the launcher itself has + ignored those two variables since Maven 3.5): the user's mirrors first, + then the global ones whose id the user does not declare. A mirror with no + `` has Maven's default id, `default`. A `.mvn/settings.xml` in the + project is evaluated the same way as a second set (Maven 4 loads it; a + Maven 3 build is often given it with `-s`); +* a mirror whose whole `` is the repository's id wins over every + pattern, and is not a capture: it was written for that repository. Nor is + a mirror that lists the id among others (`central,socket-patch-`): + whoever runs it chose to serve that repository there; +* otherwise the first mirror, in order, whose pattern matches: `*`, + `external:*` (not `localhost` / `127.0.0.1`, not `file:`), `external:http:*` + (plain HTTP only, so never the Socket repository), or a comma-separated + list of ids and wildcards in which `!id` excludes that repository. Ids are + whole ids and list segments are compared as written (`*, !id`, with a + space, excludes nothing), as in Maven; +* `` must accept `default`. + +When a mirror captures the repository, nothing is written for that dep and +the run reports `redirect_maven_mirror_captures_repository` (exit 0). The +dep is not counted as redirected and the same run's `--vex` does not attest +it, also when a pin an earlier run wrote is still in the poms: that pin +stays as it is, and the build behind the mirror cannot resolve it. No file +is touched for a gated dep, `.mvn/checksums/checksums.sha256` included. The +other patches of the run are unaffected. + +The gate applies only where a repository is at stake. A dep the rewriter +would not wire anyway (the build selects another version, no pom can take +the pin) is not gated: it is reported under its own reason, with no advice +about a mirror that plays no part in it. + +The repository id is one per patch and Maven has no pattern for a family of +ids, so a mirror can only leave Socket's repositories out one id at a time. +The settings read are the scanning machine's: the detail says so, since the +machine that builds may be configured otherwise. The in-memory engine has no +machine and reads no settings. + ### Hosted Maven reactors and property versions Hosted mode patches a multi-module reactor, and a declaration whose diff --git a/crates/socket-patch-cli/tests/common/hermetic.rs b/crates/socket-patch-cli/tests/common/hermetic.rs index 9260696e4..6ce85ef9a 100644 --- a/crates/socket-patch-cli/tests/common/hermetic.rs +++ b/crates/socket-patch-cli/tests/common/hermetic.rs @@ -108,9 +108,77 @@ pub fn command(bin: &Path) -> Command { // binary's exit: lift the short grace it gives telemetry still in // flight (the send's own 5 s request timeout still ends the wait). cmd.env("SOCKET_TELEMETRY_GRACE_MS", "30000"); + // Hosted mode weighs the mirrors of the machine's Maven settings before + // it adds a repository to a pom. The settings of whoever runs a suite + // (a `mirrorOf=*` in `~/.m2/settings.xml`, or in the installation's) + // must not decide what its scan wires. + cmd.env("MAVEN_ARGS", neutral_maven_args()); cmd } +/// The Maven settings file every socket-patch child is pointed at: real, +/// valid and empty, so it declares no mirror. +const NEUTRAL_MAVEN_SETTINGS: &str = "\n\ +\n"; + +/// The file of [`NEUTRAL_MAVEN_SETTINGS`], written on first use: one per +/// account, in the temp directory, outside every test's scratch tree and +/// never removed, so it outlives every test that was handed its path. +pub fn neutral_maven_settings() -> std::path::PathBuf { + static FILE: std::sync::OnceLock = std::sync::OnceLock::new(); + let file = FILE.get_or_init(|| { + let account: String = std::env::var("USER") + .or_else(|_| std::env::var("USERNAME")) + .unwrap_or_default() + .chars() + .filter(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '_') + .collect(); + let dir = std::env::temp_dir().join(format!("socket-patch-cli-maven-settings-{account}")); + std::fs::create_dir_all(&dir).expect("create the neutral Maven settings directory"); + let file = dir.join("settings.xml"); + // Written beside and renamed over, so a suite running at the same + // time never reads half a file. + if std::fs::read_to_string(&file).ok().as_deref() != Some(NEUTRAL_MAVEN_SETTINGS) { + let staged = dir.join(format!("settings.xml.{}", std::process::id())); + std::fs::write(&staged, NEUTRAL_MAVEN_SETTINGS) + .expect("write the neutral Maven settings"); + std::fs::rename(&staged, &file).expect("place the neutral Maven settings"); + } + file + }); + assert!( + file.is_file(), + "the neutral Maven settings file is gone: {}", + file.display() + ); + file.clone() +} + +/// The `MAVEN_ARGS` of a socket-patch child: [`neutral_maven_settings`] as +/// both the user settings (`-s`) and the global settings (`-gs`). +/// `MAVEN_ARGS` is where the CLI looks for the settings a build would be +/// started with, so with this value it reads no settings of the machine +/// at all. +/// +/// The value is for the socket-patch process alone. [`command`] is the +/// only place that sets it, and no test builds a Maven or a Gradle child +/// with [`command`]; `jvm_env::isolate_cli`, which Maven children do go +/// through, removes `MAVEN_ARGS` from a command that does not already +/// carry one. A real Maven reads `MAVEN_ARGS` too: it would take these +/// settings over the ones a test names on its command line, and it refuses +/// to start when a settings file named there does not exist, which is why +/// the file is a real one. +pub fn neutral_maven_args() -> String { + let file = neutral_maven_settings(); + let file = file.to_string_lossy(); + // (The CLI reads a double-quoted argument as one, on every platform.) + if file.contains(char::is_whitespace) { + format!("-s \"{file}\" -gs \"{file}\"") + } else { + format!("-s {file} -gs {file}") + } +} + /// [`command`] for the `socket-patch` binary cargo built for this test run. pub fn binary_command() -> Command { command(Path::new(env!("CARGO_BIN_EXE_socket-patch"))) diff --git a/crates/socket-patch-cli/tests/common/jvm_env.rs b/crates/socket-patch-cli/tests/common/jvm_env.rs index 116f08b6e..f85ca0d5c 100644 --- a/crates/socket-patch-cli/tests/common/jvm_env.rs +++ b/crates/socket-patch-cli/tests/common/jvm_env.rs @@ -85,6 +85,10 @@ pub fn stand_in_home() -> PathBuf { /// creates), carrying the version-manager roots over. Call it before /// applying a test's own env. pub fn isolate_cli(cmd: &mut Command) -> &mut Command { + let carried_maven_args = cmd + .get_envs() + .find(|(key, _)| *key == std::ffi::OsStr::new("MAVEN_ARGS")) + .and_then(|(_, value)| value.map(std::ffi::OsStr::to_os_string)); for key in AMBIENT { cmd.env_remove(key); } @@ -106,5 +110,16 @@ pub fn isolate_cli(cmd: &mut Command) -> &mut Command { let home = stand_in_home(); cmd.env("HOME", &home) .env("USERPROFILE", &home) - .env("GRADLE_USER_HOME", home.join(".gradle")) + .env("GRADLE_USER_HOME", home.join(".gradle")); + // The one variable of [`AMBIENT`] a command may already carry on + // purpose: `hermetic::command` gives the socket-patch binary a + // `MAVEN_ARGS` that names an empty settings file, so the mirrors of the + // machine's Maven settings decide nothing. That value is put back. A + // command that carries none (every Maven child: this function is also + // how a real `mvn` is isolated) gets none, so no real Maven is ever + // started with settings a test did not name. + if let Some(args) = carried_maven_args { + cmd.env("MAVEN_ARGS", args); + } + cmd } diff --git a/crates/socket-patch-cli/tests/common_selftests.rs b/crates/socket-patch-cli/tests/common_selftests.rs index e60627fd7..aaf290f8e 100644 --- a/crates/socket-patch-cli/tests/common_selftests.rs +++ b/crates/socket-patch-cli/tests/common_selftests.rs @@ -626,6 +626,54 @@ mod jvm_env_selftests { assert!(std::path::Path::new(&home).is_dir()); } + /// The neutral Maven settings can never break a real Maven. The file + /// the socket-patch child is pointed at exists and is a valid, empty + /// settings file (a real Maven refuses to start on a settings file + /// that is named and missing); only a command built for the + /// socket-patch binary carries it; and a Maven child, which is isolated + /// through the same `isolate_cli`, is started with no `MAVEN_ARGS` at + /// all, whatever the test process's environment holds. + #[test] + fn the_neutral_maven_settings_are_a_real_file_and_never_reach_a_maven_child() { + use crate::common::hermetic; + let maven_args = |cmd: &Command| -> Option> { + cmd.get_envs() + .find(|(k, _)| *k == "MAVEN_ARGS") + .map(|(_, v)| v.map(|v| v.to_string_lossy().into_owned())) + }; + let settings = hermetic::neutral_maven_settings(); + assert!(settings.is_absolute(), "{}", settings.display()); + assert!(settings.is_file(), "{}", settings.display()); + let text = std::fs::read_to_string(&settings).unwrap(); + assert!( + text.contains(" Vec { "PYTHONHOME", "PYTHONPATH", "PYTHONSTARTUP", + // (Also what `hermetic::command` itself sets for the socket-patch + // binary: neither the shell's value nor that one reaches a child.) + "MAVEN_ARGS", "REPIN", // One name under each of `REMOVED_PREFIXES`. "BAZELISK_SETTING", diff --git a/crates/socket-patch-cli/tests/e2e_redirect_maven_build.rs b/crates/socket-patch-cli/tests/e2e_redirect_maven_build.rs index 0c6606dc2..832c3f0e2 100644 --- a/crates/socket-patch-cli/tests/e2e_redirect_maven_build.rs +++ b/crates/socket-patch-cli/tests/e2e_redirect_maven_build.rs @@ -149,6 +149,20 @@ fn mount_api(s: &Server, jar: &[u8], pom: &[u8], view: &serde_json::Value) { /// (`tests/common/hermetic.rs`) with the per-test local repository as the /// crawler's maven repo. fn socket(cwd: &Path, m2: &Path, args: &[&str]) -> (Option, serde_json::Value, String) { + socket_with(cwd, m2, args, &[]) +} + +/// [`socket`] with `env` on top. Unless `env` says otherwise, the Maven +/// settings the CLI reads are the harness's empty ones +/// (`hermetic::neutral_maven_args`: `MAVEN_ARGS` is where the CLI looks +/// for the `-s` / `-gs` Maven would be started with): the mirrors of +/// whoever runs the suite must not decide a scan. +fn socket_with( + cwd: &Path, + m2: &Path, + args: &[&str], + env: &[(&str, &str)], +) -> (Option, serde_json::Value, String) { let mut cmd = hermetic::command(&binary()); hermetic::scrub_extra(&mut cmd, &[hermetic::Extra::Venv]); let out = cmd @@ -156,6 +170,8 @@ fn socket(cwd: &Path, m2: &Path, args: &[&str]) -> (Option, serde_json::Val .current_dir(cwd) .env("MAVEN_REPO_LOCAL", m2) .env_remove("M2_HOME") + .env_remove("MAVEN_HOME") + .envs(env.iter().copied()) .output() .expect("run socket-patch"); let stdout = String::from_utf8_lossy(&out.stdout).into_owned(); @@ -964,7 +980,16 @@ mod mediation { } fn scan(&self, proj: &Path) -> (Option, serde_json::Value, String) { - socket( + self.scan_with(proj, &[]) + } + + /// [`Self::scan`] with extra environment for the CLI. + fn scan_with( + &self, + proj: &Path, + env: &[(&str, &str)], + ) -> (Option, serde_json::Value, String) { + socket_with( proj, &self.m2, &[ @@ -982,6 +1007,7 @@ mod mediation { "--api-token", "fake", ], + env, ) } @@ -1632,4 +1658,140 @@ mod mediation { b.keys() ); } + + /// Every file under `from`, copied into the new directory `to`. + fn copy_tree(from: &Path, to: &Path) { + std::fs::create_dir_all(to).unwrap(); + for entry in std::fs::read_dir(from).unwrap() { + let entry = entry.unwrap(); + let target = to.join(entry.file_name()); + if entry.file_type().unwrap().is_dir() { + copy_tree(&entry.path(), &target); + } else { + std::fs::copy(entry.path(), &target).unwrap(); + } + } + } + + /// A company's `*` sends every repository to its + /// repository manager, the Socket one included, and the manager does + /// not hold the patched version: + /// + /// - a project wired where no such mirror is configured no longer + /// builds behind it (the bug); + /// - a scan that finds the mirror in the settings Maven would be + /// started with writes nothing, exits 0 and says why, naming the + /// mirror, its settings file and the two ways forward, and the + /// project builds behind the mirror as it did; + /// - once the mirror leaves the Socket repository out, the same scan + /// wires the project, and it builds behind the mirror with the + /// patched jar. + #[test] + #[ignore = "real Maven + Maven Central (dependency plugin); run with --ignored"] + fn maven_hosted_is_not_wired_behind_a_mirror_that_takes_every_repository() { + let Some(mvn) = Mvn::detect(SUITE) else { + return; + }; + let b = Bench::new(); + let proj = b.root.join("guarded"); + fixture::write_project(&proj, Shape::Selected, &b.server); + let Some(before) = fixture::resolve(SUITE, &mvn, &proj, &b.m2, &b.plain, "target/before") + else { + return; + }; + let pristine = fixture::snapshot(&proj); + // The company's repository manager serves what the fixture + // repository serves. (It keeps the id `central`, so the dependency + // plugin the local repository holds is not fetched again.) + let id = format!("socket-patch-{UUID}"); + let manager = format!("{}{}", b.server.uri(), fixture::REPO_ROUTE); + let corp = b.root.join("settings-corp.xml"); + write_settings_with_ids(&corp, &[("central", "*", &manager)]); + let maven_args = |settings: &Path| format!("-s {}", settings.display()); + // A local repository with the dependency plugin and none of the + // project's artifacts: what a build behind the mirror starts from. + // (Maven only probes, with a HEAD the test's server does not + // answer, for an artifact it holds from another repository id.) + let cold = |tag: &str| -> PathBuf { + let m2 = b.root.join(format!("m2-{tag}")); + copy_tree(&b.m2, &m2); + std::fs::remove_dir_all(m2.join("com").join("socketfixture")).unwrap(); + m2 + }; + + // Unguarded: wired where no mirror is configured, then built + // behind the mirror. + let wired = b.root.join("wired"); + fixture::write_project(&wired, Shape::Selected, &b.server); + let (code, env, stderr) = b.scan(&wired); + assert_eq!(code, Some(0), "{env}\n{stderr}"); + assert_eq!(env["summary"]["applied"], 1, "{env}"); + let out = mvn.copy_dependencies(&wired, &cold("unguarded"), &corp, "target/after"); + assert!( + !ok(&out) && dump(&out).contains(&b.suffixed), + "the mirror cannot serve the patched version:\n{}", + dump(&out) + ); + + // Guarded: the scan reads the settings Maven would be started with. + let (code, env, stderr) = b.scan_with(&proj, &[("MAVEN_ARGS", &maven_args(&corp))]); + assert_eq!(code, Some(0), "{env}\n{stderr}"); + assert_eq!(env["summary"]["applied"], 0, "{env}"); + assert_eq!(env["summary"]["failed"], 0, "{env}"); + let detail = warning(&env, "redirect_maven_mirror_captures_repository") + .unwrap_or_else(|| panic!("the scan says why: {env}"))["detail"] + .as_str() + .unwrap() + .to_string(); + for names in [ + "`central`", + "*", + corp.to_str().unwrap(), + &format!("*,!{id}"), + "scan --mode vendored", + "Only this machine's settings were read", + ] { + assert!(detail.contains(names), "{names}: {detail}"); + } + assert_eq!( + fixture::snapshot(&proj), + pristine, + "the project is left untouched: {env}" + ); + assert_eq!( + fixture::resolve_warm(&mvn, &proj, &cold("guarded"), &corp, "target/guarded", &[]), + before, + "and builds behind the mirror as it did" + ); + + // The first way forward: the mirror leaves the repository out. + // (The Socket repository is itself mirrored onto the test's + // server, under its own id, which is what a mirror written for + // that one repository looks like.) + let excluding = b.root.join("settings-corp-excluding.xml"); + let socket_url = format!("{}{}", b.server.uri(), PATCH.repo_path()); + write_settings_with_ids( + &excluding, + &[ + ("central", &format!("*,!{id}"), &manager), + (&id, &id, &socket_url), + ], + ); + let (code, env, stderr) = b.scan_with(&proj, &[("MAVEN_ARGS", &maven_args(&excluding))]); + assert_eq!(code, Some(0), "{env}\n{stderr}"); + assert_eq!(env["summary"]["applied"], 1, "{env}"); + assert!( + warning(&env, "redirect_maven_mirror_captures_repository").is_none(), + "{env}" + ); + let after = fixture::resolve_warm( + &mvn, + &proj, + &cold("excluding"), + &excluding, + "target/excluded", + &[], + ); + b.assert_only_the_victim_is_patched("behind the excluding mirror", &before, &after); + } } diff --git a/crates/socket-patch-cli/tests/maven_mediation_common/mod.rs b/crates/socket-patch-cli/tests/maven_mediation_common/mod.rs index 19cf486a6..cfdfd4966 100644 --- a/crates/socket-patch-cli/tests/maven_mediation_common/mod.rs +++ b/crates/socket-patch-cli/tests/maven_mediation_common/mod.rs @@ -45,7 +45,7 @@ pub const NEWER: &str = "1.11.0"; pub const MEMBER: &str = "META-INF/NOTICE.txt"; pub const MARKER: &str = "SOCKET-PATCH-MEDIATION-MARKER"; /// Where the server serves the fixture repository. -const REPO_ROUTE: &str = "/fixture-repo"; +pub const REPO_ROUTE: &str = "/fixture-repo"; pub fn purl() -> String { purl_of(BASE) diff --git a/crates/socket-patch-cli/tests/maven_production/mod.rs b/crates/socket-patch-cli/tests/maven_production/mod.rs index 20d494417..48a15d037 100644 --- a/crates/socket-patch-cli/tests/maven_production/mod.rs +++ b/crates/socket-patch-cli/tests/maven_production/mod.rs @@ -506,6 +506,14 @@ fn maven_env_moves_home_and_keeps_what_the_cli_isolation_carries() { "-Duser.home=/nonexistent/maven-production-home" )) ); + // A real Maven reads `MAVEN_ARGS` and refuses to start on a settings + // file named there that does not exist; it must be started with none, + // and with the settings its own command line names. + assert_eq!( + env.get(std::ffi::OsStr::new("MAVEN_ARGS")), + Some(&None), + "a Maven child is started with no MAVEN_ARGS" + ); // Everything else the CLI's isolation sets or removes (the // version-manager roots among it) reaches Maven unchanged. let mut cli = Command::new("socket-patch"); diff --git a/crates/socket-patch-core/src/crawlers/gradle_cache.rs b/crates/socket-patch-core/src/crawlers/gradle_cache.rs index e655d6cd2..b5d1549eb 100644 --- a/crates/socket-patch-core/src/crawlers/gradle_cache.rs +++ b/crates/socket-patch-core/src/crawlers/gradle_cache.rs @@ -664,7 +664,7 @@ const WRAPPER_PROPERTIES: &str = "gradle/wrapper/gradle-wrapper.properties"; /// ends at the first unescaped `=`, `:` or whitespace, and `\t`, `\n`, /// `\r`, `\f`, `\uXXXX` and `\` escapes are resolved. A later key /// wins. -fn parse_properties(bytes: &[u8]) -> HashMap { +pub(crate) fn parse_properties(bytes: &[u8]) -> HashMap { let bytes = crate::formats::text::strip_bom_bytes(bytes); let text: String = bytes.iter().map(|&b| b as char).collect(); let text = text.replace("\r\n", "\n"); diff --git a/crates/socket-patch-core/src/crawlers/maven_crawler.rs b/crates/socket-patch-core/src/crawlers/maven_crawler.rs index a235fc5c0..bca99b601 100644 --- a/crates/socket-patch-core/src/crawlers/maven_crawler.rs +++ b/crates/socket-patch-core/src/crawlers/maven_crawler.rs @@ -18,6 +18,9 @@ mod local_repo_tests; mod oracle; #[cfg(test)] mod scala_cache_tests; +mod settings_mirrors; + +pub(crate) use settings_mirrors::settings_mirror_sets; /// How many `.pom` paths the parallel parse takes at a time. Every phase /// stays in walk order whatever the chunk, so this only bounds peak diff --git a/crates/socket-patch-core/src/crawlers/maven_crawler/settings_mirrors.rs b/crates/socket-patch-core/src/crawlers/maven_crawler/settings_mirrors.rs new file mode 100644 index 000000000..e13c1eb56 --- /dev/null +++ b/crates/socket-patch-core/src/crawlers/maven_crawler/settings_mirrors.rs @@ -0,0 +1,670 @@ +//! The mirrors Maven is configured with on this machine, for the project it +//! would build: what hosted mode weighs before it adds a repository to a +//! pom ([`crate::formats::maven::mirror`]). +//! +//! Maven merges two settings files, the user's over the installation's: +//! +//! * the user settings: `-s` / `--settings` on the command line, which +//! here is `MAVEN_ARGS` (Maven 3.9+) and then the project's +//! `.mvn/maven.config`; else `/.m2/settings.xml`; +//! * the global settings: `-gs` / `--global-settings` likewise; else +//! `conf/settings.xml` of the Maven that would run: the Maven Wrapper's +//! distribution when the project has a wrapper and that distribution is +//! unpacked, else the `mvn` on `PATH` (since Maven 3.5 the launcher +//! takes its home from where it stands and ignores `$MAVEN_HOME` / +//! `$M2_HOME`), else, with no `mvn` on `PATH`, the installation those +//! two variables name (a build that calls `$MAVEN_HOME/bin/mvn`). +//! +//! A `.mvn/settings.xml` in the project is read as well, as a second way +//! the build may be started: Maven 4 loads it as the project settings, and +//! a Maven 3 build is commonly given it with `-s` on a command line this +//! scan cannot see. +//! +//! What a build machine is configured with is not known here; only what +//! this one is. + +use std::path::{Path, PathBuf}; + +use super::{character_data, interpolate}; +use crate::formats::maven::maven_config_line_args; +use crate::formats::maven::mirror::{merge, Mirror}; +use crate::gradle::home::{split_opts, system_property}; +use crate::gradle::{Env, Os}; + +/// The ``s the settings file text `raw` declares, in order. A +/// mirror without a `` is one Maven rejects, and is left out; +/// one without an `` has Maven's default id, `default`, and is a +/// mirror like any other. Values are trimmed and `${…}` placeholders +/// resolved through `lookup` (one that is undefined stays as written), as +/// Maven reads them. +pub(crate) fn parse_mirrors( + raw: &str, + source: &str, + lookup: &dyn Fn(&str) -> Option, +) -> Vec { + use crate::formats::xml; + let Ok(text) = xml::blank_non_markup(raw) else { + return Vec::new(); + }; + let Some(settings) = xml::elements(&text, "settings") + .ok() + .and_then(|found| found.first().copied()) + else { + return Vec::new(); + }; + let value = |parent: &xml::Element, name: &str| -> Option { + let element = *xml::children(&text, parent, name).ok()?.first()?; + let data = character_data(&raw[element.inner_start..element.inner_end])?; + let data = data.trim(); + let data = interpolate(data, lookup).unwrap_or_else(|| data.to_string()); + (!data.is_empty()).then_some(data) + }; + let mut out = Vec::new(); + for mirrors in xml::children(&text, &settings, "mirrors").unwrap_or_default() { + for mirror in xml::children(&text, &mirrors, "mirror").unwrap_or_default() { + let Some(mirror_of) = value(&mirror, "mirrorOf") else { + continue; + }; + out.push(Mirror { + id: value(&mirror, "id").unwrap_or_else(|| DEFAULT_MIRROR_ID.to_string()), + mirror_of, + layouts: value(&mirror, "mirrorOfLayouts"), + source: source.to_string(), + }); + } + } + out +} + +/// The id Maven's settings model gives a `` that declares none. +const DEFAULT_MIRROR_ID: &str = "default"; + +/// The value of the option `short` / `long` in `args`, in the spellings +/// Maven takes (measured on 3.8.9, 3.9.9 and 4.0.0-rc-7): `-s path`, +/// `--settings path` (the value is the next argument), `--settings=path`, +/// and `-spath`, the value joined to the short option. A joined value is +/// taken as Maven takes it when it begins with a blank (`-s path` held in +/// ONE argument, which is what a Maven that reads one argument per line +/// makes of such a line: it then looks for a file whose name begins with +/// that blank, finds none, and does not start). Any other joined value is +/// taken only when `is_file` says it names a file: other options begin +/// with the same letters, and a name taken by mistake would stand in for +/// the settings Maven really reads. The first one wins, as in Maven. +fn option_value( + args: &[String], + short: &str, + long: &str, + is_file: &dyn Fn(&str) -> bool, +) -> Option { + let mut args = args.iter(); + while let Some(arg) = args.next() { + if arg == short || arg == long { + return args.next().cloned(); + } + if let Some(value) = arg + .strip_prefix(long) + .and_then(|rest| rest.strip_prefix('=')) + { + return Some(value.to_string()); + } + if let Some(value) = arg + .strip_prefix(short) + .filter(|value| !arg.starts_with("--") && !value.is_empty()) + { + if value.starts_with(char::is_whitespace) || is_file(value) { + return Some(value.to_string()); + } + } + } + None +} + +/// The arguments of a `.mvn/maven.config`, as the project's Maven reads +/// the file: one per line, so a path may hold spaces (Maven 3.9 and later, +/// Maven 4: [`maven_config_line_args`]), or split on whitespace, where it +/// may not (before 3.9). `#` lines are comments. +/// +/// `maven` is the release the project's Maven Wrapper pins, which decides +/// the reading. With no wrapper nothing says which Maven reads the file, +/// so where the two readings differ both are weighed, each a way the +/// build may be started (the whitespace one first: a line it splits is +/// one a Maven 3.9 does not start with). +fn config_readings(config: &str, maven: Option<(u32, u32, u32)>) -> Vec> { + let by_line: Vec = maven_config_line_args(config).map(str::to_string).collect(); + let by_whitespace: Vec = config + .lines() + .filter(|line| !line.trim_start().starts_with('#')) + .flat_map(str::split_whitespace) + .map(str::to_string) + .collect(); + match maven { + Some(release) if release >= (3, 9, 0) => vec![by_line], + Some(_) => vec![by_whitespace], + None if by_line == by_whitespace => vec![by_line], + None => vec![by_whitespace, by_line], + } +} + +/// The merged mirrors of each way Maven may be started for the project at +/// `root` on this machine (see the module docs): the user settings over +/// the global ones, and, when the project keeps a `.mvn/settings.xml`, +/// that file over the global ones. Sets with no mirror are left out. +/// `home_dir` is the account's home, for when the environment names none. +pub(crate) fn settings_mirror_sets( + env: &dyn Env, + os: Os, + home_dir: Option<&Path>, + root: &Path, + maven_config: Option<&str>, +) -> Vec> { + use crate::utils::fs::is_usable_home; + let set = |k: &str| env.var(k).filter(|v| !v.is_empty()); + let property = |name: &str| { + ["MAVEN_ARGS", "MAVEN_OPTS"].iter().find_map(|k| { + set(k) + .and_then(|opts| system_property(&opts, name, os)) + .filter(|v| !v.is_empty()) + }) + }; + let user_home = set("MAVEN_OPTS") + .and_then(|opts| system_property(&opts, "user.home", os)) + .map(PathBuf::from) + .filter(|h| is_usable_home(h)) + .or_else(|| match os { + Os::Windows => ["USERPROFILE", "HOME"] + .iter() + .filter_map(|k| set(k).map(PathBuf::from)) + .find(|h| is_usable_home(h)), + Os::Unix => crate::utils::fs::home_from_env(|k| set(k).map(Into::into)), + }) + .or_else(|| { + home_dir + .filter(|h| is_usable_home(h)) + .map(Path::to_path_buf) + }); + let lookup = |name: &str| match name { + "user.home" => user_home.as_ref().map(|h| h.display().to_string()), + _ => match name.strip_prefix("env.") { + Some(var) => set(var), + None => property(name), + }, + }; + let read = |path: &Path| -> Vec { + // FIFO-safe: a FIFO planted as a settings file is refused. + match crate::utils::fs::read_regular_to_string_sync(path) { + Ok(raw) => parse_mirrors(&raw, &path.display().to_string(), &lookup), + Err(_) => Vec::new(), + } + }; + let rooted = |path: &str| { + let path = PathBuf::from(path); + if path.has_root() { + path + } else { + root.join(path) + } + }; + let is_file = |path: &str| rooted(path).is_file(); + let project = root.join(".mvn").join("settings.xml"); + // The command line (MAVEN_ARGS) wins over `.mvn/maven.config`, which + // is read both ways a Maven reads it. + let command_line = set("MAVEN_ARGS") + .map(|opts| split_opts(&opts, os)) + .unwrap_or_default(); + let wrapper_maven = crate::utils::fs::read_regular_to_bytes_sync( + &root + .join(".mvn") + .join("wrapper") + .join("maven-wrapper.properties"), + ) + .ok() + .and_then(|props| crate::crawlers::gradle_cache::wrapper_distribution_version(&props, "maven")); + let readings = match maven_config { + Some(config) => config_readings(config, wrapper_maven), + None => vec![Vec::new()], + }; + let mut sets = Vec::new(); + for reading in readings { + let mut args = command_line.clone(); + args.extend(reading); + let named = |short: &str, long: &str| { + option_value(&args, short, long, &is_file).map(|p| rooted(&p)) + }; + let user = named("-s", "--settings").or_else(|| { + user_home + .as_ref() + .map(|h| h.join(".m2").join("settings.xml")) + }); + let global = named("-gs", "--global-settings").or_else(|| { + wrapper_settings(root, set("MAVEN_USER_HOME"), user_home.as_deref()) + .or_else(|| path_settings(set("PATH"), os)) + .or_else(|| { + set("MAVEN_HOME") + .or_else(|| set("M2_HOME")) + .map(|home| PathBuf::from(home).join("conf").join("settings.xml")) + }) + }); + let global = global.as_deref().map(&read).unwrap_or_default(); + sets.push(merge( + user.as_deref().map(&read).unwrap_or_default(), + global.clone(), + )); + if project.is_file() && user.as_deref() != Some(project.as_path()) { + sets.push(merge(read(&project), global)); + } + } + sets.retain(|mirrors| !mirrors.is_empty()); + sets.dedup(); + sets +} + +/// `conf/settings.xml` of the Maven distribution the project's Maven +/// Wrapper runs, when it is unpacked on this machine, under +/// `/wrapper/dists/`. The wrapper has two layouts: +/// +/// * the `only-script` wrapper (the default since Maven Wrapper 3.3) +/// unpacks to `//conf/`, e.g. +/// `apache-maven-3.9.6/1a2b3c/conf/`; +/// * the wrapper jar unpacks to `///conf/`, e.g. +/// `apache-maven-3.9.6-bin/1a2b3c/apache-maven-3.9.6/conf/`. +fn wrapper_settings( + root: &Path, + maven_user_home: Option, + user_home: Option<&Path>, +) -> Option { + let props = root + .join(".mvn") + .join("wrapper") + .join("maven-wrapper.properties"); + let props = crate::utils::fs::read_regular_to_bytes_sync(&props).ok()?; + let url = crate::crawlers::gradle_cache::parse_properties(&props).remove("distributionUrl")?; + let archive = url.trim().rsplit('/').next()?; + let name = archive + .strip_suffix(".zip") + .or_else(|| archive.strip_suffix(".tar.gz"))?; + let dists = maven_user_home + .map(PathBuf::from) + .or_else(|| user_home.map(|h| h.join(".m2")))? + .join("wrapper") + .join("dists"); + let mut found: Vec = Vec::new(); + let mut names = vec![name]; + names.extend(name.strip_suffix("-bin")); + for name in names { + let Ok(hashes) = std::fs::read_dir(dists.join(name)) else { + continue; + }; + for hash in hashes.flatten() { + // The script's layout: the distribution is the hash directory. + let direct = hash.path().join("conf").join("settings.xml"); + if direct.is_file() { + found.push(direct); + continue; + } + let Ok(unpacked) = std::fs::read_dir(hash.path()) else { + continue; + }; + for dir in unpacked.flatten() { + let settings = dir.path().join("conf").join("settings.xml"); + if settings.is_file() { + found.push(settings); + } + } + } + } + found.sort(); + found.into_iter().next() +} + +/// `conf/settings.xml` of the Maven whose launcher is first on `path`. A +/// package manager's launcher may sit beside a `libexec` that holds the +/// distribution (Homebrew), so that is looked in too. +fn path_settings(path: Option, os: Os) -> Option { + let (separator, launcher) = match os { + Os::Windows => (';', "mvn.cmd"), + Os::Unix => (':', "mvn"), + }; + let launcher = path? + .split(separator) + .filter(|dir| !dir.is_empty()) + .map(|dir| Path::new(dir).join(launcher)) + .find(|candidate| candidate.is_file())?; + let home = std::fs::canonicalize(launcher) + .ok()? + .parent()? + .parent()? + .to_path_buf(); + [home.join("conf"), home.join("libexec").join("conf")] + .into_iter() + .map(|conf| conf.join("settings.xml")) + .find(|settings| settings.is_file()) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::BTreeMap; + + const ID: &str = "socket-patch-77777777-7777-7777-7777-777777777777"; + const URL: &str = "https://patch.socket.dev/patch-registry/maven/t/u/maven2"; + + fn settings(mirrors: &[(&str, &str)]) -> String { + let mut body = String::from("\n \n"); + for (id, of) in mirrors { + body.push_str(&format!( + " \n {id}\n {of}\n \ + https://nexus.example/repo\n \n" + )); + } + body.push_str(" \n\n"); + body + } + + fn write(path: &Path, text: &str) { + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, text).unwrap(); + } + + fn env(pairs: &[(&str, &Path)]) -> BTreeMap { + pairs + .iter() + .map(|(k, v)| (k.to_string(), v.display().to_string())) + .collect() + } + + /// What captures the Socket repository in `sets`, by mirror id. + fn captured(sets: &[Vec]) -> Option<&str> { + crate::formats::maven::mirror::capturing(sets, ID, URL).map(|m| m.id.as_str()) + } + + #[test] + fn mirrors_are_read_as_maven_reads_them() { + let none = |_: &str| None; + let raw = "\n\n \ + \n \ + \n \n corp \n * \n \ + https://nexus.example/repo\n default\n \ + \n \n no-pattern\n https://x.example\n \ + \n \n by-env\n ${env.MIRROR_OF}\n \ + https://y.example\n \n \n \n \n \ + p\n \n \n\n"; + let mirrors = parse_mirrors(raw, "settings.xml", &none); + let read: Vec<(&str, &str, Option<&str>)> = mirrors + .iter() + .map(|m| (m.id.as_str(), m.mirror_of.as_str(), m.layouts.as_deref())) + .collect(); + assert_eq!( + read, + [ + ("corp", "*", Some("default")), + ("by-env", "${env.MIRROR_OF}", None) + ] + ); + let lookup = |name: &str| (name == "env.MIRROR_OF").then(|| "central".to_string()); + let mirrors = parse_mirrors(raw, "settings.xml", &lookup); + assert_eq!(mirrors[1].mirror_of, "central"); + assert!(mirrors.iter().all(|m| m.source == "settings.xml")); + for broken in ["", "", ""] { + assert_eq!(parse_mirrors(broken, "s", &none), Vec::new(), "{broken}"); + } + // A mirror with no is one Maven accepts, under the id + // `default`: it takes repositories like any other, and a user's + // one shadows a global one of that id. + let anonymous = "*\ + https://nexus.example/repo"; + let mirrors = parse_mirrors(anonymous, "settings.xml", &none); + assert_eq!(mirrors.len(), 1); + assert_eq!( + (mirrors[0].id.as_str(), mirrors[0].mirror_of.as_str()), + ("default", "*") + ); + assert_eq!(captured(&[mirrors.clone()]), Some("default")); + let global = parse_mirrors( + &settings(&[("default", "central"), ("corp", "*")]), + "global.xml", + &none, + ); + let merged = merge(mirrors, global); + assert_eq!( + merged.iter().map(|m| m.id.as_str()).collect::>(), + ["default", "corp"] + ); + } + + #[test] + fn the_user_settings_are_found_where_maven_finds_them() { + let tmp = tempfile::tempdir().unwrap(); + let home = tmp.path().join("home"); + let root = tmp.path().join("proj"); + std::fs::create_dir_all(&root).unwrap(); + write(&home.join(".m2/settings.xml"), &settings(&[("home", "*")])); + write( + &tmp.path().join("ci/settings.xml"), + &settings(&[("ci", "*")]), + ); + write(&root.join("conf/team.xml"), &settings(&[("team", "*")])); + let sets = |env: &BTreeMap, config: Option<&str>| { + settings_mirror_sets(env, Os::current(), None, &root, config) + }; + + // `~/.m2/settings.xml`. + let base = env(&[("HOME", &home)]); + assert_eq!(captured(&sets(&base, None)), Some("home")); + // `-s` in `.mvn/maven.config`, relative to the project, in every + // spelling; then `MAVEN_ARGS`, which wins. + for config in [ + "-s\nconf/team.xml\n", + "-s conf/team.xml\n", + "--settings=conf/team.xml\n", + "-B --settings conf/team.xml\n", + ] { + assert_eq!( + captured(&sets(&base, Some(config))), + Some("team"), + "{config}" + ); + } + let mut args = base.clone(); + args.insert( + "MAVEN_ARGS".into(), + format!("-B -s {}", tmp.path().join("ci/settings.xml").display()), + ); + assert_eq!( + captured(&sets(&args, Some("-s conf/team.xml\n"))), + Some("ci") + ); + // A settings file that is named but missing mirrors nothing, and + // the default one is then not read either. + let mut missing = base.clone(); + missing.insert("MAVEN_ARGS".into(), "-s /nonexistent/settings.xml".into()); + assert_eq!(sets(&missing, None), Vec::>::new()); + // No home at all: nothing to read. + assert_eq!(sets(&BTreeMap::new(), None), Vec::>::new()); + } + + /// `.mvn/maven.config` is read both ways a Maven reads it. Maven 3.9 + /// and later take one argument per line, so a settings path may hold + /// a space; before 3.9 the file is split on whitespace. Measured on + /// Maven 3.8.9, 3.9.9 and 4.0.0-rc-7. A path the line reading names is + /// opened whole: read split, it would name no file, the mirror in it + /// would go unseen, and the pin would be written into a build that + /// cannot resolve it. + #[test] + fn maven_config_is_read_one_argument_per_line_and_split_on_whitespace() { + let tmp = tempfile::tempdir().unwrap(); + let home = tmp.path().join("home"); + let root = tmp.path().join("proj"); + std::fs::create_dir_all(&root).unwrap(); + std::fs::create_dir_all(&home).unwrap(); + write( + &root.join("my settings/team settings.xml"), + &settings(&[("spaced", "*")]), + ); + write(&root.join("conf/team.xml"), &settings(&[("team", "*")])); + let base = env(&[("HOME", &home)]); + let sets = + |config: &str| settings_mirror_sets(&base, Os::current(), None, &root, Some(config)); + // One argument per line: every spelling Maven 3.9+ takes. + for config in [ + "-s\nmy settings/team settings.xml\n", + "--settings\nmy settings/team settings.xml\n", + "--settings=my settings/team settings.xml\n", + "-smy settings/team settings.xml\n", + "\"-s\"\n\"my settings/team settings.xml\"\n", + "-B\n# the team's settings\n -s \n my settings/team settings.xml \n-o\n", + // The global settings are named the same way. + "-gs\nmy settings/team settings.xml\n", + "--global-settings=my settings/team settings.xml\n", + ] { + assert_eq!(captured(&sets(config)), Some("spaced"), "{config:?}"); + } + // Split on whitespace: what a Maven before 3.9 makes of one line. + for config in [ + "-B -s conf/team.xml\n", + "-B --settings conf/team.xml -o\n", + "-o -gs conf/team.xml\n", + ] { + assert_eq!(captured(&sets(config)), Some("team"), "{config:?}"); + } + // An option that only begins like `-s` names no settings file, and + // does not stand in for the ones Maven reads. + write(&home.join(".m2/settings.xml"), &settings(&[("home", "*")])); + assert_eq!(captured(&sets("-sadp\n-ntp\n")), Some("home")); + // `-s path` on one line: a Maven that reads one argument per line + // looks for a file whose name begins with the blank and does not + // start, so that reading names no settings (and the default ones + // are not read instead); split on whitespace it names the file. + assert_eq!(captured(&sets("-s conf/team.xml\n")), Some("team")); + std::fs::remove_file(root.join("conf/team.xml")).unwrap(); + assert_eq!(captured(&sets("-s conf/team.xml\n")), None); + // The arguments themselves. With no wrapper nothing says which + // Maven reads the file, so both readings are weighed where they + // differ; a wrapper's Maven decides. + let (line, split) = ( + vec!["-s".to_string(), "my settings/x.xml".to_string()], + vec![ + "-s".to_string(), + "my".to_string(), + "settings/x.xml".to_string(), + ], + ); + let spaced = "-s\nmy settings/x.xml\n"; + assert_eq!(config_readings(spaced, None), [split.clone(), line.clone()]); + assert_eq!(config_readings(spaced, Some((3, 9, 0))), [line.clone()]); + assert_eq!(config_readings(spaced, Some((4, 0, 0))), [line]); + assert_eq!(config_readings(spaced, Some((3, 8, 9))), [split]); + assert_eq!( + config_readings("-B\n-ntp\n", None), + [vec!["-B".to_string(), "-ntp".to_string()]] + ); + + // The same through the settings lookup. Under a wrapper that pins + // a Maven before 3.9 a path with a space names no file (and that + // Maven does not start); under one that pins 3.9 or later a line + // of several options names none. + std::fs::remove_file(home.join(".m2/settings.xml")).unwrap(); + write(&root.join("conf/team.xml"), &settings(&[("team", "*")])); + let wrapper = |version: &str| { + write( + &root.join(".mvn/wrapper/maven-wrapper.properties"), + &format!( + "distributionUrl=https\\://repo.maven.apache.org/maven2/org/apache/maven/\ + apache-maven/{version}/apache-maven-{version}-bin.zip\n" + ), + ); + }; + let spaced = "-s\nmy settings/team settings.xml\n"; + let several = "-B -s conf/team.xml\n"; + wrapper("3.9.9"); + assert_eq!(captured(&sets(spaced)), Some("spaced")); + assert_eq!(captured(&sets(several)), None); + wrapper("3.8.9"); + assert_eq!(captured(&sets(spaced)), None); + assert_eq!(captured(&sets(several)), Some("team")); + } + + #[test] + fn the_global_and_project_settings_are_weighed_too() { + let tmp = tempfile::tempdir().unwrap(); + let home = tmp.path().join("home"); + let root = tmp.path().join("proj"); + let maven = tmp.path().join("maven"); + std::fs::create_dir_all(&root).unwrap(); + write( + &maven.join("conf/settings.xml"), + &settings(&[("corp", "*"), ("blocker", "external:http:*")]), + ); + let base = env(&[("HOME", &home), ("MAVEN_HOME", &maven)]); + let sets = |env: &BTreeMap, config: Option<&str>| { + settings_mirror_sets(env, Os::current(), None, &root, config) + }; + // The installation's settings alone. + assert_eq!(captured(&sets(&base, None)), Some("corp")); + // The user's mirror of the same id replaces it. + write( + &home.join(".m2/settings.xml"), + &settings(&[("corp", "central")]), + ); + assert_eq!(captured(&sets(&base, None)), None); + // `-gs` names other global settings. + write( + &root.join("global.xml"), + &settings(&[("other", "external:*")]), + ); + assert_eq!( + captured(&sets(&base, Some("-gs\nglobal.xml\n"))), + Some("other") + ); + // The Maven on PATH is the one that runs, whatever `MAVEN_HOME` + // says: the launcher takes its home from where it stands. + let bin = tmp.path().join("dist/bin"); + let launcher = if cfg!(windows) { "mvn.cmd" } else { "mvn" }; + write(&bin.join(launcher), "#!/bin/sh\n"); + write( + &tmp.path().join("dist/conf/settings.xml"), + &settings(&[("on-path", "*")]), + ); + let on_path = env(&[("HOME", &home), ("PATH", &bin)]); + assert_eq!(captured(&sets(&on_path, None)), Some("on-path")); + let both = env(&[("HOME", &home), ("PATH", &bin), ("MAVEN_HOME", &maven)]); + assert_eq!(captured(&sets(&both, None)), Some("on-path")); + // The wrapper's distribution, once unpacked, is the Maven that runs. + write( + &root.join(".mvn/wrapper/maven-wrapper.properties"), + "distributionUrl=https\\://repo.example/apache-maven-3.9.6-bin.zip\n", + ); + assert_eq!(captured(&sets(&on_path, None)), Some("on-path")); + // The wrapper jar's layout: ///conf. + let jar_layout = home.join( + ".m2/wrapper/dists/apache-maven-3.9.6-bin/abc123/apache-maven-3.9.6/conf/settings.xml", + ); + write(&jar_layout, &settings(&[("wrapped", "*")])); + assert_eq!(captured(&sets(&on_path, None)), Some("wrapped")); + // The script's layout (the default since Maven Wrapper 3.3): the + // archive name without `-bin`, and the distribution in the hash + // directory itself. + std::fs::remove_file(&jar_layout).unwrap(); + assert_eq!(captured(&sets(&on_path, None)), Some("on-path")); + write( + &home.join(".m2/wrapper/dists/apache-maven-3.9.6/def456/conf/settings.xml"), + &settings(&[("only-script", "*")]), + ); + assert_eq!(captured(&sets(&on_path, None)), Some("only-script")); + // The properties file is read as Java reads one (`:` separator, + // a continued line). + write( + &root.join(".mvn/wrapper/maven-wrapper.properties"), + "distributionType=only-script\ndistributionUrl: https\\://repo.example/\\\n apache-maven-3.9.6-bin.zip\n", + ); + assert_eq!(captured(&sets(&on_path, None)), Some("only-script")); + // A settings file the project keeps is a second way to be started. + let quiet = env(&[("HOME", &home)]); + std::fs::remove_file(root.join(".mvn/wrapper/maven-wrapper.properties")).unwrap(); + assert_eq!(captured(&sets(&quiet, None)), None); + write( + &root.join(".mvn/settings.xml"), + &settings(&[("project", "*")]), + ); + assert_eq!(captured(&sets(&quiet, None)), Some("project")); + } +} diff --git a/crates/socket-patch-core/src/formats/maven/mirror.rs b/crates/socket-patch-core/src/formats/maven/mirror.rs new file mode 100644 index 000000000..7239e099e --- /dev/null +++ b/crates/socket-patch-core/src/formats/maven/mirror.rs @@ -0,0 +1,347 @@ +//! Maven's `settings.xml` mirrors, and whether one would take over a +//! repository hosted mode adds to a pom. Pure: the settings are read by +//! the caller ([`crate::crawlers::maven_crawler::settings_mirrors`]). +//! +//! A `` replaces every repository its `` matches: Maven +//! then asks the mirror's URL, never the repository's own. A company's +//! `*` therefore sends the `socket-patch-` +//! repository to its repository manager, which does not hold the patched +//! version, and the build fails to resolve it. +//! +//! The matching is Maven's own (`DefaultMirrorSelector`, the same in +//! maven-core and maven-resolver): +//! +//! * a mirror whose whole `` is the repository's id wins over +//! every pattern, whatever the order of the mirrors; +//! * otherwise the first mirror, in settings order, whose pattern matches: +//! `*`; `external:*` (any repository not on `localhost` / `127.0.0.1` +//! and not a `file:` URL); `external:http:*` (the same, over plain +//! HTTP); a comma-separated list of ids and those wildcards, in which +//! `!id` excludes that repository; +//! * and whose `` (empty by default: any) accepts the +//! repository's layout. +//! +//! An id in a pattern is always a whole id: `!socket-patch-*` excludes +//! nothing. The settings reader trims the whole ``, but a segment +//! of a list is compared as written: in `*, !id` the exclusion starts with +//! a space, is no exclusion, and the mirror takes the repository. +//! +//! Checked against Maven itself: every case of the tests below was run +//! through `DefaultMirrorSelector` of Maven 3.6.3, 3.9.4, 3.9.16 and +//! 4.0.0-rc-7 (the same answers, but for `external:http:*`, which Maven +//! knows from 3.8.1), and the spaced, the glob and the padded patterns +//! through real builds of 3.6.3, 3.9.16 and 4.0.0-rc-7. + +use serde::{Deserialize, Serialize}; + +/// One `` of a settings file. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct Mirror { + pub(crate) id: String, + pub(crate) mirror_of: String, + /// ``, when the mirror names any. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub(crate) layouts: Option, + /// The settings file that declares the mirror. + pub(crate) source: String, +} + +/// The layout of every repository hosted mode writes. +const LAYOUT: &str = "default"; + +/// `scheme` and `host` of a repository URL, as the resolver reads them +/// (`RemoteRepository.getProtocol` / `getHost`): the scheme is what comes +/// before `://` (so `dav:http`), the host what follows it up to a `/` or +/// a port, without any `user@`. +fn scheme_and_host(url: &str) -> (&str, &str) { + let Some((scheme, rest)) = url.split_once("://") else { + return (url.split(':').next().unwrap_or_default(), ""); + }; + let authority = rest.split('/').next().unwrap_or_default(); + let host = authority.rsplit('@').next().unwrap_or_default(); + (scheme, host.split(':').next().unwrap_or_default()) +} + +fn is_local(host: &str) -> bool { + host == "localhost" || host == "127.0.0.1" +} + +fn is_external(url: &str) -> bool { + let (scheme, host) = scheme_and_host(url); + !(is_local(host) || scheme.eq_ignore_ascii_case("file")) +} + +fn is_external_http(url: &str) -> bool { + let (scheme, host) = scheme_and_host(url); + ["http", "dav", "dav:http", "dav+http"] + .iter() + .any(|s| scheme.eq_ignore_ascii_case(s)) + && !is_local(host) +} + +/// Whether the `` `pattern` matches the repository `id` at `url` +/// (Maven's `matchPattern`). Segments are read left to right, each as +/// written: an exclusion of the id ends the reading with no match, the id +/// itself ends it with a match, and a wildcard matches unless a later +/// segment excludes the id. +pub(crate) fn matches_pattern(pattern: &str, id: &str, url: &str) -> bool { + if pattern == "*" || pattern == id { + return true; + } + let mut matched = false; + for segment in pattern.split(',') { + if segment.len() > 1 && segment.starts_with('!') { + if &segment[1..] == id { + return false; + } + } else if segment == id { + return true; + } else if (segment == "external:*" && is_external(url)) + || (segment == "external:http:*" && is_external_http(url)) + || segment == "*" + { + matched = true; + } + } + matched +} + +/// Whether a mirror's `` accepts `layout` (Maven's +/// `matchesLayout`): none, or `*`, accepts any; else a list read like +/// [`matches_pattern`]. +fn matches_layout(layouts: Option<&str>, layout: &str) -> bool { + let Some(layouts) = layouts.filter(|l| !l.is_empty() && *l != "*") else { + return true; + }; + if layouts == layout { + return true; + } + let mut matched = false; + for segment in layouts.split(',') { + if segment.len() > 1 && segment.starts_with('!') { + if &segment[1..] == layout { + return false; + } + } else if segment == layout { + return true; + } else if segment == "*" { + matched = true; + } + } + matched +} + +/// Whether `mirror` names the repository `id`: its `` is the +/// id, or lists it as an id of its own (`central,socket-patch-`), +/// each segment compared as written, as Maven compares it. +fn names(mirror: &Mirror, id: &str) -> bool { + mirror.mirror_of.split(',').any(|segment| segment == id) +} + +/// The mirror Maven uses for the repository `id` at `url`, and whether it +/// names that repository ([`names`]). +pub(crate) fn select<'m>(mirrors: &'m [Mirror], id: &str, url: &str) -> Option<(&'m Mirror, bool)> { + let layout_ok = |m: &&Mirror| matches_layout(m.layouts.as_deref(), LAYOUT); + let exact = mirrors.iter().filter(layout_ok).find(|m| m.mirror_of == id); + exact.map(|m| (m, true)).or_else(|| { + mirrors + .iter() + .filter(layout_ok) + .find(|m| matches_pattern(&m.mirror_of, id, url)) + .map(|m| (m, names(m, id))) + }) +} + +/// `dominant` followed by the mirrors of `recessive` whose id it does not +/// declare, as Maven merges the user settings over the global ones. +pub(crate) fn merge(dominant: Vec, recessive: Vec) -> Vec { + let mut merged = dominant; + for mirror in recessive { + if !merged.iter().any(|m| m.id == mirror.id) { + merged.push(mirror); + } + } + merged +} + +/// The mirror that would take over the repository `id` at `url` without +/// naming it, in any of `sets` (each the merged mirrors of one way Maven +/// may be started). A mirror whose `` names the id, alone or as +/// one id of a list, was written for that repository: whoever runs it +/// chose to serve the Socket repository there, and it is not one. (Nor +/// would the exclusion the warning suggests change anything for it.) +pub(crate) fn capturing<'m>(sets: &'m [Vec], id: &str, url: &str) -> Option<&'m Mirror> { + sets.iter() + .find_map(|mirrors| match select(mirrors, id, url) { + Some((mirror, false)) => Some(mirror), + _ => None, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + const ID: &str = "socket-patch-77777777-7777-7777-7777-777777777777"; + const URL: &str = "https://patch.socket.dev/patch-registry/maven/t/u/maven2"; + + fn mirror(id: &str, of: &str) -> Mirror { + Mirror { + id: id.into(), + mirror_of: of.into(), + layouts: None, + source: "settings.xml".into(), + } + } + + /// The cases of Maven's "Using Mirrors for Repositories" guide. + #[test] + fn the_documented_patterns_match_as_maven_matches_them() { + // `*`: everything. + assert!(matches_pattern("*", ID, URL)); + // `external:*`: everything not on the localhost and not file based. + assert!(matches_pattern("external:*", ID, URL)); + assert!(!matches_pattern( + "external:*", + ID, + "http://localhost:8081/repo" + )); + assert!(!matches_pattern("external:*", ID, "http://127.0.0.1/repo")); + assert!(!matches_pattern("external:*", ID, "file:///srv/repo")); + assert!(!matches_pattern("external:*", ID, "file:/srv/repo")); + // `external:http:*`: any repository not on the localhost using HTTP. + assert!(!matches_pattern("external:http:*", ID, URL)); + assert!(matches_pattern( + "external:http:*", + ID, + "http://patch.example/m2" + )); + assert!(matches_pattern( + "external:http:*", + ID, + "dav:http://patch.example/m2" + )); + assert!(!matches_pattern( + "external:http:*", + ID, + "http://localhost/m2" + )); + // `repo,repo1`: repo or repo1. + assert!(matches_pattern(&format!("central,{ID}"), ID, URL)); + assert!(!matches_pattern("central,jboss", ID, URL)); + // `*,!repo1`: everything except repo1. + assert!(!matches_pattern(&format!("*,!{ID}"), ID, URL)); + assert!(matches_pattern("*,!central", ID, URL)); + assert!(matches_pattern(ID, ID, URL)); + assert!(!matches_pattern("central", ID, URL)); + } + + /// The reading is ordered, as in `DefaultMirrorSelector.matchPattern`. + #[test] + fn a_list_is_read_left_to_right() { + // An exclusion ends it, wherever the wildcard stands. + assert!(!matches_pattern(&format!("!{ID},*"), ID, URL)); + assert!(!matches_pattern(&format!("external:*,!{ID}"), ID, URL)); + // The id itself ends it before a later exclusion is read. + assert!(matches_pattern(&format!("{ID},!{ID}"), ID, URL)); + // A segment is compared as written: a space before `!` makes it + // no exclusion (the mirror takes the repository), and one around + // an id makes it another id. + assert!(matches_pattern(&format!("*, !{ID}"), ID, URL)); + assert!(!matches_pattern(&format!("central , {ID}"), ID, URL)); + // An id is a whole id: no pattern excludes a family of them. + assert!(matches_pattern("*,!socket-patch-*", ID, URL)); + assert!(matches_pattern("*,!socket-patch", ID, URL)); + // A lone `!` is not an exclusion, and matches nothing. + assert!(!matches_pattern("!", ID, URL)); + assert!(!matches_pattern("", ID, URL)); + } + + /// A mirror that lists the repository's id among others was written + /// for it: whoever runs that mirror chose to serve the Socket + /// repository there, so it is no capture (and excluding the id from a + /// list that names it would change nothing). + #[test] + fn a_mirror_that_lists_the_repository_is_no_capture() { + for of in [ + format!("central,{ID}"), + format!("{ID},central"), + format!("*,{ID}"), + format!("external:*,{ID},!other"), + ] { + let mirrors = vec![mirror("internal", &of)]; + assert_eq!( + select(&mirrors, ID, URL).map(|(m, named)| (m.id.as_str(), named)), + Some(("internal", true)), + "{of}" + ); + assert_eq!(capturing(&[mirrors], ID, URL), None, "{of}"); + } + // Naming another id, or the id with a space before it (a segment + // is compared as written), is not naming this repository. + for of in ["*,central".to_string(), format!("*, {ID}")] { + let mirrors = vec![mirror("corp", &of)]; + assert_eq!( + capturing(&[mirrors], ID, URL).map(|m| m.id.as_str()), + Some("corp"), + "{of}" + ); + } + } + + #[test] + fn a_mirror_of_the_repository_alone_wins_over_any_pattern() { + let mirrors = [mirror("corp", "*"), mirror("socket", ID)]; + let (chosen, exact) = select(&mirrors, ID, URL).unwrap(); + assert_eq!((chosen.id.as_str(), exact), ("socket", true)); + assert_eq!(capturing(&[mirrors.to_vec()], ID, URL), None); + // Without it, the first matching pattern in settings order. + let mirrors = [ + mirror("only-central", "central"), + mirror("corp", "external:*"), + mirror("all", "*"), + ]; + let (chosen, exact) = select(&mirrors, ID, URL).unwrap(); + assert_eq!((chosen.id.as_str(), exact), ("corp", false)); + assert_eq!( + capturing(&[vec![], mirrors.to_vec()], ID, URL).map(|m| m.id.as_str()), + Some("corp") + ); + // The blocker Maven 3.8.1+ ships matches plain HTTP only. + let blocker = [mirror("maven-default-http-blocker", "external:http:*")]; + assert_eq!(select(&blocker, ID, URL), None); + assert_eq!(select(&[], ID, URL), None); + } + + #[test] + fn a_mirror_for_another_layout_is_not_chosen() { + let layouts = |l: &str| Mirror { + layouts: Some(l.into()), + ..mirror("corp", "*") + }; + for accepted in ["", "*", "default", "legacy,default", "*,!legacy"] { + assert!( + select(&[layouts(accepted)], ID, URL).is_some(), + "{accepted}" + ); + } + for refused in ["legacy", "*,!default", "!default,*", "p2"] { + assert_eq!(select(&[layouts(refused)], ID, URL), None, "{refused}"); + } + } + + #[test] + fn the_user_settings_shadow_a_global_mirror_of_the_same_id() { + let merged = merge( + vec![mirror("corp", "central")], + vec![mirror("corp", "*"), mirror("blocker", "external:http:*")], + ); + let ids: Vec<(&str, &str)> = merged + .iter() + .map(|m| (m.id.as_str(), m.mirror_of.as_str())) + .collect(); + assert_eq!(ids, [("corp", "central"), ("blocker", "external:http:*")]); + assert_eq!(capturing(&[merged], ID, URL), None); + } +} diff --git a/crates/socket-patch-core/src/formats/maven/mod.rs b/crates/socket-patch-core/src/formats/maven/mod.rs index 6db52935b..e16444076 100644 --- a/crates/socket-patch-core/src/formats/maven/mod.rs +++ b/crates/socket-patch-core/src/formats/maven/mod.rs @@ -17,6 +17,7 @@ pub(crate) use properties::{ use super::xml::{blank_non_markup, child_text, elements, open_tags, Element}; +pub(crate) mod mirror; pub(crate) mod declared_maven; pub(crate) mod trusted_checksums; pub(crate) mod version; @@ -1009,20 +1010,28 @@ fn java_trim(s: &str) -> &str { s.trim_matches(|c: char| c <= ' ') } -/// [`maven_config_properties`] as Maven 3.9+ alone reads it: only the -/// argument a whole line holds, never a token of the older whitespace split. -pub(crate) fn maven_config_line_properties(config: &str) -> BTreeMap { - let trim = java_trim; +/// The arguments of a `maven.config` as Maven 3.9+ (and Maven 4) reads the +/// file: one per line, so an argument may hold spaces (a settings path, +/// say); each line trimmed, a wholly quoted one unquoted, `#` lines and +/// empty ones dropped. Maven before 3.9 splits the whole file on +/// whitespace instead. +pub(crate) fn maven_config_line_args(config: &str) -> impl Iterator { fn unquote(s: &str) -> &str { s.strip_prefix('"') .and_then(|s| s.strip_suffix('"')) .map_or(s, java_trim) } - let mut args = config + config .lines() - .map(|line| unquote(trim(line))) + .map(|line| unquote(java_trim(line))) .filter(|arg| !arg.is_empty() && !arg.starts_with('#')) - .peekable(); +} + +/// [`maven_config_properties`] as Maven 3.9+ alone reads it: only the +/// argument a whole line holds, never a token of the older whitespace split. +pub(crate) fn maven_config_line_properties(config: &str) -> BTreeMap { + let trim = java_trim; + let mut args = maven_config_line_args(config).peekable(); let mut props = BTreeMap::new(); while let Some(arg) = args.next() { let def = match arg.strip_prefix("--define") { diff --git a/crates/socket-patch-core/src/hosted/engine.rs b/crates/socket-patch-core/src/hosted/engine.rs index e83890fe3..91c343d39 100644 --- a/crates/socket-patch-core/src/hosted/engine.rs +++ b/crates/socket-patch-core/src/hosted/engine.rs @@ -833,6 +833,42 @@ async fn read_maven_reactor( out.undecodable_maven_poms = undecodable; } +/// Hand the pom rewriter the mirrors Maven is configured with on this +/// machine +/// ([`settings_mirror_sets`](crate::crawlers::maven_crawler::settings_mirror_sets)), +/// under [`MAVEN_MIRRORS_KEY`](crate::patch::redirect::MAVEN_MIRRORS_KEY): +/// it adds no repository to a pom that one of them would take over (the +/// gem path's mirror gate, for Maven). On disk only: a memory view has no +/// machine, and so no settings to read. +fn read_maven_mirrors( + view: &ProjectView<'_>, + env: &(dyn crate::gradle::Env + Sync), + out: &mut CandidateFiles, +) { + if !out.files.contains_key("pom.xml") { + return; + } + let Some(root) = view.disk_root() else { + return; + }; + let sets = crate::crawlers::maven_crawler::settings_mirror_sets( + env, + crate::gradle::Os::current(), + None, + root, + out.files + .get(crate::patch::redirect::MVN_CONFIG) + .map(String::as_str), + ); + if sets.is_empty() { + return; + } + if let Ok(json) = serde_json::to_string(&sets) { + out.files + .insert(crate::patch::redirect::MAVEN_MIRRORS_KEY.to_string(), json); + } +} + /// An in-memory project's Go files as the hosted engine reads them /// ([`read_advisory`]: a link or an entry without content is unreadable, /// but still exists). @@ -999,6 +1035,26 @@ pub async fn read_candidate_files( view: &ProjectView<'_>, unreadable: &BTreeSet, candidates: &[Candidate], +) -> CandidateFiles { + read_candidate_files_in( + view, + unreadable, + candidates, + &crate::crawlers::gradle_cache::ProcessEnv, + ) + .await +} + +/// [`read_candidate_files`] with the environment the machine's own +/// configuration is looked up through (today: where Maven's settings +/// files are, for the mirror gate). The process environment in +/// production; a test hands in its own, so what a developer keeps in +/// `~/.m2/settings.xml` decides nothing. +pub async fn read_candidate_files_in( + view: &ProjectView<'_>, + unreadable: &BTreeSet, + candidates: &[Candidate], + env: &(dyn crate::gradle::Env + Sync), ) -> CandidateFiles { let mut out = CandidateFiles::default(); for name in REDIRECT_CANDIDATE_FILES.iter() { @@ -1161,6 +1217,7 @@ pub async fn read_candidate_files( // the poms of the modules that select it. if candidates.iter().any(|c| c.dep.ecosystem == "maven") { read_maven_reactor(view, unreadable, &mut out).await; + read_maven_mirrors(view, env, &mut out); } // NuGet merges the user config and every parent directory's config @@ -6174,7 +6231,18 @@ snapshots: gradle_rewrite_in(&ProjectView::Memory(p)).await } + /// Over `view`, with no machine behind it: an empty environment, so + /// no home, no `PATH` and no settings file of whoever runs the tests + /// decides what a Maven project is wired to. async fn gradle_rewrite_in(view: &ProjectView<'_>) -> (CandidateFiles, Rewritten) { + gradle_rewrite_with(view, &BTreeMap::new()).await + } + + /// [`gradle_rewrite_in`] on a machine whose environment is `env`. + async fn gradle_rewrite_with( + view: &ProjectView<'_>, + env: &BTreeMap, + ) -> (CandidateFiles, Rewritten) { let outer = OuterAllowRemote::default; let options = RewriteOptions { dry_run: false, @@ -6194,7 +6262,7 @@ snapshots: prior_discovery: None, }; let candidates = vec![gradle_candidate()]; - let read = read_candidate_files(view, &BTreeSet::new(), &candidates).await; + let read = read_candidate_files_in(view, &BTreeSet::new(), &candidates, env).await; let done = rewrite(view, read.clone(), &candidates, BTreeMap::new(), options).await; (read, done) } @@ -6617,6 +6685,141 @@ snapshots: assert!(done.confirmed.is_empty(), "{:?}", done.confirmed); } + /// On disk the engine reads the mirrors of the Maven settings the + /// build would be started with, and a project whose Socket repository + /// one of them would take over is left alone: nothing written, nothing + /// confirmed, the reason given, and no refusal of the run. A mirror + /// that leaves the repository out wires as usual, and so does the + /// same project in memory, where no machine's settings exist. + #[tokio::test] + async fn a_maven_project_behind_a_capturing_mirror_is_left_alone() { + use crate::patch::redirect::MAVEN_MIRRORS_KEY; + let pom = "\n 4.0.0\n x\n y\n 1\n \n \n com.socketfixture\n victim\n 1.10.0\n \n \n\n"; + // Both settings files are named, so none of this machine's is read. + let config = "-s\nsettings.xml\n-gs\nglobal.xml\n"; + let settings = |mirror_of: &str| { + format!( + "\n \n \n corp\n \ + {mirror_of}\n https://nexus.example/repo\n \ + \n \n\n" + ) + }; + let tmp = tempfile::tempdir().unwrap(); + let write = |rel: &str, text: &str| { + let path = tmp.path().join(rel); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, text).unwrap(); + }; + write("pom.xml", pom); + write(".mvn/maven.config", config); + write("global.xml", "\n"); + write("settings.xml", &settings("*")); + let view = ProjectView::Disk(tmp.path()); + let (read, done) = gradle_rewrite_in(&view).await; + assert!(read.files.contains_key(MAVEN_MIRRORS_KEY)); + assert!(done.rewrite.files.is_empty(), "{:?}", done.rewrite.files); + assert!(done.confirmed.is_empty(), "{:?}", done.confirmed); + let warning = done + .rewrite + .warnings + .iter() + .find(|w| w.code == "redirect_maven_mirror_captures_repository") + .unwrap_or_else(|| panic!("{:?}", done.rewrite.warnings)); + assert!( + warning.detail.contains("`corp`") && warning.detail.contains("settings.xml"), + "{}", + warning.detail + ); + assert!(guard(&view, &done, &[gradle_candidate()]).is_none()); + + // The mirror leaves the repository out. + write( + "settings.xml", + &settings(&format!("*,!socket-patch-{GRADLE_UUID}")), + ); + let (_, done) = gradle_rewrite_in(&view).await; + assert!(done.rewrite.files["pom.xml"].contains("1.10.0-socket.4d5e6f70")); + assert_eq!(done.confirmed.len(), 1, "{:?}", done.rewrite.warnings); + + // A project an earlier run wired, on a machine whose mirror now + // takes the repository: the pom still names the patch, and the + // build behind that mirror cannot resolve it. Nothing is written, + // and the patch is not confirmed by the text it still matches. + let wired = done.rewrite.files.clone(); + for (rel, text) in &wired { + write(rel, text); + } + write("settings.xml", &settings("*")); + let (_, done) = gradle_rewrite_in(&view).await; + assert!(done.rewrite.files.is_empty(), "{:?}", done.rewrite.files); + assert!( + std::fs::read_to_string(tmp.path().join("pom.xml")) + .unwrap() + .contains("1.10.0-socket.4d5e6f70"), + "the wiring is left as it is" + ); + assert!(done.confirmed.is_empty(), "{:?}", done.confirmed); + assert!(done + .rewrite + .warnings + .iter() + .any(|w| w.code == "redirect_maven_mirror_captures_repository")); + write("pom.xml", pom); + + // The settings are found through the environment the engine is + // given, never the test process's own: a settings file named in + // that environment's `MAVEN_ARGS` is the one read. + std::fs::remove_file(tmp.path().join(".mvn/maven.config")).unwrap(); + write("ci/settings.xml", &settings("*")); + let (_, done) = gradle_rewrite_in(&view).await; + assert!( + done.rewrite.files["pom.xml"].contains("1.10.0-socket.4d5e6f70"), + "no environment, no settings: wired" + ); + let ci = BTreeMap::from([( + "MAVEN_ARGS".to_string(), + format!( + "-s {} -gs {}", + tmp.path().join("ci/settings.xml").display(), + tmp.path().join("global.xml").display() + ), + )]); + let (read, done) = gradle_rewrite_with(&view, &ci).await; + assert!(read.files.contains_key(MAVEN_MIRRORS_KEY)); + assert!(done.rewrite.files.is_empty(), "{:?}", done.rewrite.files); + write(".mvn/maven.config", config); + + // A settings path with a space, on a line of its own as Maven 3.9 + // and later read `maven.config`: the file is opened whole, and the + // mirror in it gates the pin. + write("team settings/settings.xml", &settings("*")); + write( + ".mvn/maven.config", + "-s\nteam settings/settings.xml\n-gs\nglobal.xml\n", + ); + write("settings.xml", &settings("central")); + let (read, done) = gradle_rewrite_in(&view).await; + assert!(read.files.contains_key(MAVEN_MIRRORS_KEY)); + assert!(done.rewrite.files.is_empty(), "{:?}", done.rewrite.files); + assert!(done + .rewrite + .warnings + .iter() + .any(|w| w.code == "redirect_maven_mirror_captures_repository" + && w.detail.contains("team settings"))); + write(".mvn/maven.config", config); + + // In memory: the files are there, but no machine to read them for. + let mut p = MemoryProject::new(); + p.insert_text("pom.xml", pom); + p.insert_text(".mvn/maven.config", config); + p.insert_text("settings.xml", settings("*").as_str()); + let view = ProjectView::Memory(&p); + let (read, done) = gradle_rewrite_in(&view).await; + assert!(!read.files.contains_key(MAVEN_MIRRORS_KEY)); + assert!(done.rewrite.files["pom.xml"].contains("1.10.0-socket.4d5e6f70")); + } + /// #1809: a Maven 4 root whose subprojects Maven discovers (model /// 4.1.0, `pom` packaging, no list) is a reactor once a direct /// subdirectory holds a `pom.xml`. The engine reads that pom beside diff --git a/crates/socket-patch-core/src/patch/redirect/mod.rs b/crates/socket-patch-core/src/patch/redirect/mod.rs index a1d26b834..78a61276f 100644 --- a/crates/socket-patch-core/src/patch/redirect/mod.rs +++ b/crates/socket-patch-core/src/patch/redirect/mod.rs @@ -465,10 +465,12 @@ pub struct RewriteResult { serde(skip_serializing_if = "std::collections::BTreeSet::is_empty") )] pub refused_gradle_uuids: std::collections::BTreeSet, - /// Maven patch uuids the reactor planner decided (a reactor root, or a - /// single pom's `${property}` version): their pins may sit in module - /// poms, a property or a comment-recorded declaration, so the pom - /// rewriter's own report confirms them, never a substring. + /// Maven patch uuids the pom rewriter decided itself, so its own + /// report confirms them, never a substring: those the reactor planner + /// planned (a reactor root, or a single pom's `${property}` version; + /// their pins may sit in module poms, a property or a comment-recorded + /// declaration), and those the mirror gate held back, which are never + /// confirmed whatever an earlier run left in the poms. #[cfg_attr( test, serde(skip_serializing_if = "std::collections::BTreeSet::is_empty") @@ -9061,6 +9063,11 @@ pub(crate) const MVN_CHECKSUMS: &str = ".mvn/checksums/checksums.sha256"; /// `distributionUrl` names the Maven release the project builds with, so the /// rewriter can tell when the Trusted Checksums files it writes are inert. pub(crate) const MVN_WRAPPER_PROPERTIES: &str = ".mvn/wrapper/maven-wrapper.properties"; +/// Engine-supplied input: the `settings.xml` mirrors Maven is configured +/// with on the machine that scans, as the JSON of +/// [`settings_mirror_sets`](crate::crawlers::maven_crawler::settings_mirror_sets). +/// Absent in memory, where no machine's settings are known. +pub const MAVEN_MIRRORS_KEY: &str = ""; /// Strip any `sha256-`/`sha256:` SRI-style prefix off a stored hash, leaving the /// bare lowercase hex Maven's trusted-checksums summary file expects (twin of @@ -9157,11 +9164,107 @@ pub fn maven_reactor_root(files: &BTreeMap) -> bool { crate::vendor::jvm::maven_reactor::is_reactor_root(&read, &list) } +/// The Maven pom rewriter, behind the mirror gate. +/// +/// The mirrors of the scanning machine's Maven settings come in under +/// [`MAVEN_MIRRORS_KEY`]. A mirror that takes every repository takes a +/// Socket one too, and does not hold the patched version: a pin whose +/// repository such a mirror captures would break the build it is meant to +/// patch. So a dep is gated before anything is written for it, and only +/// where a repository is at stake: +/// +/// * the dep is planned on its own, with no mirror in sight, and is gated +/// when that plan would declare its repository in a pom, or a pom +/// already declares it (an earlier run wired it). A dep the rewriter +/// would not wire anyway (its version is not selected, its pom cannot +/// take the pin) is not gated: it goes through as usual and is told its +/// own reason; +/// * a gated dep gets the mirror's warning and nothing else: no pom, no +/// `.mvn` file, no checksum line is touched for it. It is recorded as +/// decided and not confirmed ([`RewriteResult::maven_reactor_uuids`]), +/// so wiring an earlier run left is not counted as a redirect, or +/// attested, by a substring it still matches. fn rewrite_maven_pom( files: &BTreeMap, overrides: &[DepOverride], selection: Option<&MavenSelection>, result: &mut RewriteResult, +) { + let mirror_sets: Vec> = files + .get(MAVEN_MIRRORS_KEY) + .and_then(|json| serde_json::from_str(json).ok()) + .unwrap_or_default(); + let captured = |dep: &DepOverride| { + let ov = registry_override_of_kind(dep, "maven2")?; + let repo_id = generation::hosted_pin_name(&dep.patch_uuid); + crate::formats::maven::mirror::capturing(&mirror_sets, &repo_id, &ov.index_url) + .map(|mirror| (repo_id, mirror)) + }; + if !overrides + .iter() + .any(|dep| dep.ecosystem == "maven" && captured(dep).is_some()) + { + return rewrite_maven_poms(files, overrides, selection, result); + } + let declares = |texts: &BTreeMap, repo_id: &str| { + let id = format!("{repo_id}"); + texts + .iter() + .any(|(rel, text)| !sbt::is_synthetic_key(rel) && text.contains(&id)) + }; + // The Maven the project's wrapper pins, as vendored mode reads it: the + // warning's advice depends on it. + let wrapper = crate::vendor::jvm::wrapper_version( + &|rel: &str| files.get(rel).map(|text| text.as_bytes().to_vec()), + "maven", + ); + let mut wired: Vec = Vec::with_capacity(overrides.len()); + for dep in overrides { + let gate = (dep.ecosystem == "maven") + .then(|| captured(dep)) + .flatten() + .filter(|(repo_id, _)| { + declares(files, repo_id) || { + let mut alone = RewriteResult::default(); + rewrite_maven_poms(files, std::slice::from_ref(dep), selection, &mut alone); + declares(&alone.files, repo_id) + } + }); + let Some((repo_id, mirror)) = gate else { + wired.push(dep.clone()); + continue; + }; + let ga = match registry_override_of_kind(dep, "maven2") { + Some(ov) => format!( + "{}:{}", + ov.identifiers + .maven_group_id + .as_deref() + .or(dep.namespace.as_deref()) + .unwrap_or_default(), + ov.identifiers + .maven_artifact_id + .as_deref() + .unwrap_or(&dep.name) + ), + None => full_name(dep), + }; + result.warnings.push(RewriteWarning { + code: "redirect_maven_mirror_captures_repository".into(), + detail: maven_mirror_detail(&ga, &repo_id, mirror, wrapper), + }); + result.maven_reactor_uuids.insert(dep.patch_uuid.clone()); + } + rewrite_maven_poms(files, &wired, selection, result); +} + +/// The Maven pom rewriter proper: every dep it is given is one no mirror +/// of the machine's settings captures ([`rewrite_maven_pom`]). +fn rewrite_maven_poms( + files: &BTreeMap, + overrides: &[DepOverride], + selection: Option<&MavenSelection>, + result: &mut RewriteResult, ) { let maven: Vec<&DepOverride> = overrides .iter() @@ -10147,6 +10250,64 @@ fn pin_maven_checksums( } } +/// Why a dep is not wired behind `mirror`, and the ways forward. The +/// settings read are the scanning machine's, which the line says: the +/// machine that builds may be configured otherwise. +/// +/// The second way forward is vendored mode, and only where it is one. A +/// vendored patch gets past a mirror through `maven.repo.local.tail`, +/// which Maven reads from 3.9.2 on; an older Maven reads it through +/// vendored mode's own file repository, which a mirror of everything takes +/// like any other. So the advice names that bound, and for a project whose +/// Maven Wrapper pins an older Maven (`wrapper`, as vendored mode itself +/// reads it) it does not offer vendored mode as it stands, but says what +/// makes it work. +fn maven_mirror_detail( + ga: &str, + repo_id: &str, + mirror: &crate::formats::maven::mirror::Mirror, + wrapper: Option<(u32, u32, u32)>, +) -> String { + let vendor_repo = crate::vendor::jvm::maven_reactor::REPO_ID; + let exclude = format!( + "exclude the repository from that mirror ({of},!{repo_id}; Maven \ + matches whole repository ids, so each patch needs its own exclusion) and re-run", + of = mirror.mirror_of, + ); + let ways = match wrapper { + Some((major, minor, patch)) if (major, minor, patch) < (3, 9, 2) => format!( + "To patch it, {exclude}. `scan --mode vendored` is no way round the mirror for \ + this project as it stands: its Maven Wrapper pins Maven {major}.{minor}.{patch}, \ + and a Maven before 3.9.2 reads a vendored patch through the `{vendor_repo}` file \ + repository, which this mirror would take as well. Vendored mode does work once \ + the wrapper pins Maven 3.9.2 or later, or once the mirror also leaves \ + `{vendor_repo}` out (one id for every vendored patch)" + ), + Some((major, minor, patch)) => format!( + "Either {exclude}, or patch with `scan --mode vendored`, which commits the patched \ + artifact: Maven {major}.{minor}.{patch}, which the Maven Wrapper pins, reads it \ + through maven.repo.local.tail, which no mirror redirects" + ), + None => format!( + "Either {exclude}, or patch with `scan --mode vendored`, which commits the patched \ + artifact: Maven 3.9.2 and later read it through maven.repo.local.tail, which no \ + mirror redirects (an older Maven reads it through the `{vendor_repo}` file \ + repository, which this mirror would take as well unless it leaves that id out \ + too)" + ), + }; + format!( + "{ga}: on this machine Maven's settings send the {repo_id} repository to the mirror \ + `{id}` ({of} in {source}), which does not serve the patched \ + artifact, so the build could not resolve it; pom.xml and .mvn/ were left as they are \ + and the dep is not counted as redirected. {ways}. Only this machine's settings were \ + read: the machine that builds needs the same exclusion", + id = mirror.id, + of = mirror.mirror_of, + source = mirror.source, + ) +} + /// One dep handed to the reactor planner. struct ReactorDep<'a> { dep: &'a DepOverride, @@ -11660,6 +11821,360 @@ mod tests { const MAVEN_UUID: &str = "aaaaaaaa-1111-4222-8333-444444444444"; + /// The engine-supplied mirrors of one settings file. + fn maven_mirrors(mirrors: &[(&str, &str)]) -> (String, String) { + let set: Vec = mirrors + .iter() + .map(|(id, of)| crate::formats::maven::mirror::Mirror { + id: id.to_string(), + mirror_of: of.to_string(), + layouts: None, + source: "/home/dev/.m2/settings.xml".into(), + }) + .collect(); + ( + MAVEN_MIRRORS_KEY.to_string(), + serde_json::to_string(&vec![set]).unwrap(), + ) + } + + /// A mirror that takes every repository would take the Socket one too, + /// and does not hold the patched version. The dep is not wired: no + /// file is written, and the line names the mirror, its settings file + /// and the two ways forward. A single pom, a `${property}` version, a + /// reactor and a same-GAV grant alike. + #[test] + fn maven_is_not_wired_behind_a_mirror_that_would_take_its_repository() { + let pom = pom_with_dep("\n 1.7.36", ""); + let property = pom_with_dep("\n ${slf4j.version}", "").replace( + " ", + " \n 1.7.36\n \n ", + ); + let declares = " \n org.slf4j\n \ + slf4j-api\n 1.7.36\n \ + \n"; + let reactor = [ + ("pom.xml", REACTOR_ROOT.to_string()), + ("a/pom.xml", reactor_module("a", declares)), + ("b/pom.xml", reactor_module("b", "")), + ]; + let shapes: [(&str, Vec<(&str, String)>, DepOverride); 4] = [ + ( + "literal", + vec![("pom.xml", pom.clone())], + granted_maven_override(), + ), + ( + "property", + vec![("pom.xml", property)], + granted_maven_override(), + ), + ("reactor", reactor.to_vec(), granted_maven_override()), + ( + "same GAV", + vec![("pom.xml", pom.clone())], + legacy_maven_override(), + ), + ]; + for (shape, poms, dep) in shapes { + let id = format!("socket-patch-{}", dep.patch_uuid); + let files = |mirrors: &[(&str, &str)]| -> BTreeMap { + poms.iter() + .map(|(rel, text)| (rel.to_string(), text.clone())) + .chain([maven_mirrors(mirrors)]) + .collect() + }; + for captures in [ + "*", + "external:*", + "central,*", + "*,!central", + "*, !socket-patch-x", + ] { + let r = rewrite_registry_redirect( + &files(&[("only-central", "central"), ("corp", captures)]), + std::slice::from_ref(&dep), + ); + assert!( + r.files.is_empty(), + "{shape}, {captures}: {:?}", + r.files.keys() + ); + assert!(r.edits.is_empty(), "{shape}, {captures}: {:?}", r.edits); + assert_eq!( + warning_codes(&r), + ["redirect_maven_mirror_captures_repository"], + "{shape}, {captures}" + ); + let detail = &r.warnings[0].detail; + for names in [ + "`corp`", + &format!("{captures}"), + "/home/dev/.m2/settings.xml", + &format!("{captures},!{id}"), + "scan --mode vendored", + "Only this machine's settings were read", + ] { + assert!( + detail.contains(names), + "{shape}, {captures}: {names}: {detail}" + ); + } + // Decided, and not confirmed: nothing an earlier run left + // in a pom may count as a redirect by a substring. + assert!( + r.maven_reactor_uuids.contains(&dep.patch_uuid) + && r.confirmed_maven_reactor_uuids.is_empty(), + "{shape}, {captures}" + ); + } + // A mirror that leaves the repository alone, or one written for + // that repository, changes nothing: the same files as with no + // settings at all. + let plain = rewrite_registry_redirect(&files(&[]), std::slice::from_ref(&dep)); + assert!(plain.files.contains_key("pom.xml"), "{shape}"); + let excluded = format!("*,!{id}"); + // A mirror that lists the repository among others serves it + // on purpose: the operator's choice, not a capture. + let listed = format!("central,{id}"); + for leaves in [ + vec![("corp", "central")], + vec![("blocker", "external:http:*")], + vec![("corp", excluded.as_str())], + vec![("corp", "*"), ("socket", id.as_str())], + vec![("internal", listed.as_str())], + ] { + let r = rewrite_registry_redirect(&files(&leaves), std::slice::from_ref(&dep)); + assert_eq!(r.files, plain.files, "{shape}: {leaves:?}"); + assert_eq!( + warning_codes(&r), + warning_codes(&plain), + "{shape}: {leaves:?}" + ); + } + } + // A pin an earlier run wrote is left as it is, and reported. + let wired = rewrite_registry_redirect( + &BTreeMap::from([("pom.xml".to_string(), pom)]), + &[granted_maven_override()], + ); + let mut files: BTreeMap = wired.files.clone(); + files.extend([maven_mirrors(&[("corp", "*")])]); + let r = rewrite_registry_redirect(&files, &[granted_maven_override()]); + assert!(r.files.is_empty(), "{:?}", r.files.keys()); + assert_eq!( + warning_codes(&r), + ["redirect_maven_mirror_captures_repository"] + ); + // And not confirmed, though every file still names the patch: the + // build behind that mirror cannot resolve it. + assert!( + r.maven_reactor_uuids.contains(MAVEN_UUID) + && r.confirmed_maven_reactor_uuids.is_empty() + ); + } + + /// The advice of the warning must lead somewhere. Vendored mode gets + /// past a mirror through `maven.repo.local.tail`, which Maven reads + /// from 3.9.2 on; an older Maven reads a vendored patch through the + /// `socket-patch-vendor` file repository, which the same mirror takes. + /// So the bound is in the text, and a project whose wrapper pins an + /// older Maven is not sent to vendored mode as it stands. + #[test] + fn maven_mirror_warning_offers_vendored_mode_only_where_it_works() { + let pom = pom_with_dep("\n 1.7.36", ""); + let detail = |wrapper: Option<&str>| -> String { + let mut files: BTreeMap = [("pom.xml".to_string(), pom.clone())] + .into_iter() + .chain([maven_mirrors(&[("corp", "*")])]) + .collect(); + if let Some(version) = wrapper { + files.insert(MVN_WRAPPER_PROPERTIES.to_string(), maven_wrapper(version)); + } + let r = rewrite_registry_redirect(&files, &[granted_maven_override()]); + assert_eq!( + warning_codes(&r), + ["redirect_maven_mirror_captures_repository"], + "{wrapper:?}" + ); + assert!(r.files.is_empty(), "{wrapper:?}"); + r.warnings[0].detail.clone() + }; + let exclusion = format!("*,!socket-patch-{MAVEN_UUID}"); + + // No wrapper: the Maven is not known, so the bound is given, with + // what an older Maven needs. + let unknown = detail(None); + for part in [ + exclusion.as_str(), + "or patch with `scan --mode vendored`", + "Maven 3.9.2 and later read it through maven.repo.local.tail", + "an older Maven reads it through the `socket-patch-vendor` file repository", + ] { + assert!(unknown.contains(part), "{part}: {unknown}"); + } + + // A wrapper that pins a Maven which reads the tail: offered, and + // said of that Maven. + for version in ["3.9.2", "3.9.16", "4.0.0"] { + let offered = detail(Some(version)); + for part in [ + exclusion.as_str(), + "or patch with `scan --mode vendored`", + &format!("Maven {version}, which the Maven Wrapper pins, reads it through"), + ] { + assert!(offered.contains(part), "{version}: {part}: {offered}"); + } + assert!(!offered.contains("is no way round"), "{version}: {offered}"); + } + + // A wrapper that pins an older Maven: vendored mode is not a way + // out as the project stands, and the text says what is. + for version in ["3.6.3", "3.8.9", "3.9.1"] { + let withheld = detail(Some(version)); + for part in [ + exclusion.as_str(), + "`scan --mode vendored` is no way round the mirror", + &format!("its Maven Wrapper pins Maven {version}"), + "once the wrapper pins Maven 3.9.2 or later", + "once the mirror also leaves `socket-patch-vendor` out", + ] { + assert!(withheld.contains(part), "{version}: {part}: {withheld}"); + } + assert!( + !withheld.contains("or patch with `scan --mode vendored`"), + "{version}: {withheld}" + ); + } + // One line of prose each way. + for text in [detail(None), detail(Some("3.9.16")), detail(Some("3.8.9"))] { + assert!(!text.contains(" "), "{text:?}"); + } + } + + /// The gate is for a dep that would get a repository. One the rewriter + /// would not wire anyway is told its own reason, with no advice about + /// a mirror that plays no part in it. + #[test] + fn maven_mirror_gate_leaves_a_dep_that_would_not_be_wired_to_its_own_reason() { + // The pom declares another version than the patch is for. + let other_version = pom_with_dep("\n 2.0.9", ""); + // The dependency is not declared with a version the pom can take. + let no_pom: Vec<(&str, String)> = vec![]; + for (shape, poms) in [ + ("another version", vec![("pom.xml", other_version)]), + ("no pom", no_pom), + ] { + let files = |mirrors: &[(&str, &str)]| -> BTreeMap { + poms.iter() + .map(|(rel, text)| (rel.to_string(), text.clone())) + .chain(mirrors.first().map(|_| maven_mirrors(mirrors))) + .collect() + }; + let dep = granted_maven_override(); + let plain = rewrite_registry_redirect(&files(&[]), std::slice::from_ref(&dep)); + assert!( + !plain.files.contains_key("pom.xml"), + "{shape}: not wired to begin with" + ); + let r = rewrite_registry_redirect(&files(&[("corp", "*")]), std::slice::from_ref(&dep)); + assert_eq!(warning_codes(&r), warning_codes(&plain), "{shape}"); + assert!( + !warning_codes(&r).contains(&"redirect_maven_mirror_captures_repository"), + "{shape}" + ); + assert_eq!(r.files, plain.files, "{shape}"); + assert!(r.maven_reactor_uuids.is_empty(), "{shape}"); + } + } + + /// A gated dep has nothing written for it at all: not even the + /// checksum lines a grant with a malformed hash would otherwise have + /// dropped. The warning says `.mvn/` was left as it is, and it is. + #[test] + fn maven_mirror_gate_touches_no_file_of_a_gated_dep() { + let mut dep = granted_maven_override(); + dep.integrity.sha256 = Some("sha256-q83vEjRWeJA=".into()); + let stale = format!( + "{} org/slf4j/slf4j-api/{MAVEN_SUFFIXED}/slf4j-api-{MAVEN_SUFFIXED}.jar\n", + "c".repeat(64) + ); + let base = BTreeMap::from([ + ( + "pom.xml".to_string(), + pom_with_dep("\n 1.7.36", ""), + ), + (MVN_CHECKSUMS.to_string(), stale.clone()), + ]); + // With no mirror the stale line goes (and the pin lands). + let plain = rewrite_registry_redirect(&base, std::slice::from_ref(&dep)); + assert!( + plain + .files + .get(MVN_CHECKSUMS) + .is_some_and(|sums| !sums.contains(MAVEN_SUFFIXED)), + "{:?}", + plain.files.keys() + ); + let mut gated = base.clone(); + gated.extend([maven_mirrors(&[("corp", "*")])]); + let r = rewrite_registry_redirect(&gated, std::slice::from_ref(&dep)); + assert!(r.files.is_empty(), "{:?}", r.files.keys()); + assert!(r.edits.is_empty(), "{:?}", r.edits); + assert_eq!( + warning_codes(&r), + ["redirect_maven_mirror_captures_repository"] + ); + } + + /// A dep the gate holds back does not keep another dep of the same + /// run from being wired, and the other dep's files are the only ones + /// written. + #[test] + fn maven_mirror_gate_is_per_dep() { + let second_uuid = "88888888-8888-4888-8888-888888888888"; + let mut second = granted_maven_override(); + second.name = "slf4j-simple".into(); + second.patch_uuid = second_uuid.into(); + let ov = second.registry_override.as_mut().unwrap(); + ov.index_url = + format!("https://patch.socket.dev/patch-registry/maven/tok/{second_uuid}/maven2"); + ov.identifiers.name = "org.slf4j/slf4j-simple".into(); + ov.identifiers.maven_artifact_id = Some("slf4j-simple".into()); + ov.identifiers.maven_suffixed_version = Some("1.7.36-socket.88888888".into()); + let pom = pom_with_dep("\n 1.7.36", "").replace( + " ", + " \n org.slf4j\n \ + slf4j-simple\n 1.7.36\n \ + \n ", + ); + // The mirror takes every repository but the second patch's. + let of = format!("*,!socket-patch-{second_uuid}"); + let files: BTreeMap = [("pom.xml".to_string(), pom)] + .into_iter() + .chain([maven_mirrors(&[("corp", of.as_str())])]) + .collect(); + let r = rewrite_registry_redirect(&files, &[granted_maven_override(), second]); + let wired = &r.files["pom.xml"]; + assert!( + wired.contains("1.7.36-socket.88888888") + && wired.contains(&format!("socket-patch-{second_uuid}")), + "{wired}" + ); + assert!( + !wired.contains(MAVEN_SUFFIXED) + && !wired.contains(&format!("socket-patch-{MAVEN_UUID}")), + "{wired}" + ); + assert_eq!( + warning_codes(&r), + ["redirect_maven_mirror_captures_repository"] + ); + assert!(r.warnings[0].detail.starts_with("org.slf4j:slf4j-api: ")); + assert!(r.maven_reactor_uuids.contains(MAVEN_UUID)); + assert!(!r.maven_reactor_uuids.contains(second_uuid)); + } + /// [`maven_override`] as the patch service grants it: the suffix is the /// first eight hex digits of the patch uuid, which is what ties a pin /// to its repository and what the reactor planner writes. diff --git a/docs/ecosystems.md b/docs/ecosystems.md index f934ed803..236ad6665 100644 --- a/docs/ecosystems.md +++ b/docs/ecosystems.md @@ -1224,14 +1224,50 @@ Honest limits of the Maven and NuGet flows — documented behavior, not bugs: applied. To clear them, add a Maven Wrapper pinned to Maven 3.9.9 or later, or make sure your `settings.xml` mirrors exclude `socket-patch-vendor` (for example `external:*` or `*,!socket-patch-vendor`). -* **`mirrorOf` mirrors (hosted Maven).** A `settings.xml` `` with - `*` (common in corporate environments) reroutes *all* repositories - — including the injected `socket-patch-` repository — through the mirror. Because - the patch resolves only at the suffixed version, the mirror (which does not carry it) - can't serve it and the **build fails loudly** rather than silently going unpatched. - Scope the mirror to exclude the Socket repos (e.g. - `*,!socket-patch-*`) so the redirect resolves; the - `originAware=false` Trusted Checksums act as a backstop when present. +* **`mirrorOf` mirrors (hosted Maven).** A `settings.xml` `` whose + `` is `*` or `external:*` (common in corporate environments) sends *every* + repository to the mirror, the `socket-patch-` repository hosted mode adds + included. The patch resolves only at its suffixed version, which the mirror does not + hold, so a project wired behind such a mirror **fails to build**. `scan --mode hosted` + therefore reads the Maven settings of the machine it runs on before it writes a Maven + pin, and wires nothing for a patch whose repository a mirror would take over: the + poms and `.mvn/` stay as they are, the scan exits 0, and + `redirect_maven_mirror_captures_repository` names the mirror, the settings file that + declares it, and the two ways forward: + - **Leave the repository out of the mirror.** Add `!socket-patch-` to its + `` (`*,!socket-patch-`), with no space around + it, on every machine that builds, then scan again. Maven compares whole repository + ids: there is no pattern for "every Socket repository" (`!socket-patch-*` excludes + nothing), and each patch has its own id, so each new patch needs its own exclusion. + - **Use vendored mode, on Maven 3.9.2 or later.** `scan --mode vendored` commits the + patched artifact and reads it through `maven.repo.local.tail`, which no mirror + redirects. Maven reads that setting from 3.9.2 on. An older Maven reads a vendored + patch through the `socket-patch-vendor` file repository, which a mirror of everything + takes as well, so there vendored mode needs the mirror to leave `socket-patch-vendor` + out (one id for every vendored patch). The warning says which applies: when the + project's Maven Wrapper pins a Maven older than 3.9.2 it does not offer vendored mode + as the project stands. + + What is read: the user settings (`-s` / `--settings` in `MAVEN_ARGS`, then in + `.mvn/maven.config`, else `~/.m2/settings.xml`) merged over the global settings (`-gs` + / `--global-settings` likewise, else `conf/settings.xml` of the Maven Wrapper's + unpacked distribution, of the `mvn` on `PATH`, or, with none there, of `$MAVEN_HOME` + / `$M2_HOME`), and a `.mvn/settings.xml` the project keeps. `.mvn/maven.config` is + read as the project's Maven reads it: one argument per line from Maven 3.9 on (so a + settings path may hold spaces), split on whitespace before; the Maven Wrapper's + release decides, and without a wrapper both readings are weighed. The matching is + Maven's own: a mirror whose `` names the repository's id, alone or in a list + (`central,socket-patch-`), was written for that repository and is not a reason + to skip; a mirror with no `` counts under Maven's default id; `external:http:*` (the blocker Maven ships) never matches the + HTTPS Socket repository; `` is honoured. **Only the scanning + machine's settings are known.** A build machine with another `settings.xml` (a CI + image, a colleague's laptop) is not seen: a project wired here still fails there + behind a mirror that takes every repository, and a project skipped here may have built + there. The in-memory engine (a Socket-opened pull request) reads no settings at all. + A project an earlier scan wired is left as it is and reported the same way, and is no + longer counted as redirected or attested by that scan's `--vex`. The skip is only for + a patch that would get the repository: one the scan would not wire anyway (the build + selects another version) is reported under its own reason. * **Gradle (hosted Maven).** Gradle builds get automated wiring, not a pasted snippet: an owned settings script pins the suffixed version, every lock file is rewritten, and a tripwire fails the build if the base version still resolves. See