diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index d1e97dfe2..46e56bd25 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -547,7 +547,7 @@ Recognition rules that hold for every ecosystem: * **Patch hosts.** A hosted reference counts only on `https://patch.socket.dev` or the `--patch-server-url` / `SOCKET_PATCH_SERVER_URL` origin, with no userinfo. The uuid is the URL's LAST canonical-uuid path segment, because grant tokens may themselves be uuid-shaped. The Go module prefix is fixed. `socket-patch-` registry / repository / source names count only through a pin. For a URL on any other host, see **Patch hosts** above. * **Pins, not definitions.** A registry, index or source *definition* alone (cargo `[registries]`, nuget ``, pom ``, uv index tables, `.npmrc`) never makes a reference, because it survives a reverted pin. Sections the package manager ignores are not read: npm's v2 `dependencies` mirror, a `.cargo/config.toml` shadowed by `.cargo/config`. A Socket pin inside a maven `` is diagnosed, never a reference. * **Contested locks.** When one lock wires a package to a patch and another lock resolves the same `name@version` from a non-Socket source, the build's bytes depend on which package manager runs. The reference is then dropped with a `patched_ref_unattributable` diagnostic naming both files. This applies across npm / pnpm / yarn / bun and across uv / pylock / poetry / pdm / Pipfile.lock / requirements. PEP 723 script locks neither contest nor are contested. The root `requirements.txt` and its in-root `-r` includes count as one lock here: pip reads them as one requirement set, where a direct reference wins over a compatible `==` pin of the same version in another file of the set (#1086). A PyPI version matches under PEP 440 equality, so a requirements line pinned in any spelling that can only install the wired release (`==1.2.3.0`, `==v1.2.3`, `===1.2.3`) contests it like `==1.2.3` does; a range or wildcard (`~=1.2.3`, `==1.2.*`) does not (#1602). A **bundled** npm copy (`inBundle: true`, or v1 `bundled: true`, beneath a dependency that bundles it; the root project's own bundles install from the lock, #1618) of the same `name@version` contests the reference too, in the same lock, in the other npm lock of a shrinkwrap/package-lock pair, or in any other lock. npm unpacks it from the parent package's tarball, so no rewire reaches it and it stays unpatched. Bun and vlt unpack bundled copies the same way (#469, #471). pnpm unpacks bundled copies too, but its lock cannot tie one to a reference (see **Unattested references** below). For Bun, that is a `bun.lock` entry whose meta is `{ "bundled": true }`, or a `bun.lockb` record that a dependency edge with the `bundled` behavior bit reaches, including one Bun shares with a regular install. Such an entry is never a reference, and it contests the reference the same way. For vlt, the lock records no node for a bundled copy, so the copy is found in the installed store: a real package directory inside a store package's own `node_modules`. yarn classic's `yarn.lock` records nothing about bundled copies either (#758), so for a lock with a Socket wiring they are found in the installed `node_modules`: each package a parent's `bundleDependencies` / `bundledDependencies` names inside the parent's own `node_modules`, the dependencies of those beside them, and everything nested under them. Such a copy contests the reference in `yarn.lock` (the diagnostic names the parent's lock entry and the copy's directory); a lock-only `vex` with no `node_modules` can't see it. Hosted and vendored scans skip these copies with `redirect_bun_bundled_instance_skipped` / `redirect_vlt_bundled_instance_skipped` / `vendor_bundled_instance_skipped`, and a yarn classic hosted scan names one with `redirect_copy_unpatched`. When a bundled copy is the only instance, vendoring refuses with `vendor_lock_entry_not_rewritable`. A reference withheld only because such an unreachable copy installs beside it (a bundled npm / Bun / vlt copy, an npm copy beneath a `hasShrinkwrap` package (#753) or one npm installs from a git / url / `file:` spec, or a yarn classic git or `file:` directory block of the same `name@version`) is still the rewriter's own wiring of exactly one package version: it is never attested, but `rollback`, `remove`, `list` and the hosted → vendored takeover treat it as an ordinary hosted pin and restore its upstream registry entry (#828), rather than refusing it with `hosted_wiring_contested`. Another entry of the **same** npm, Bun or yarn lock that resolves the wired `name@version` from a non-Socket source (for example a workspace member added after the rewire, then `npm install` / `bun install` / `yarn install`; for yarn berry, a registry locator such as `left-pad@npm:1.3.0` beside the hosted `…::__archiveUrl=` one) contests the reference too (#588). The package manager installs both entries, and that copy stays unpatched. Re-running `scan` / `vendor` rewires every copy. -* **Unattested references.** Some evidence shows a build may run a copy no wiring reaches, but cannot be tied to the reference's exact `name@version` or cannot say the build runs it. The reference then stays a reference: `list`, `rollback` and `remove` find it, and the ledgers' liveness gates (`vendor --check`, `scan`) keep treating the wiring as live, because re-running `scan` / `vendor` could never clear the evidence. Only `vex` omits it, as a run warning and as the `failed[].reason`. Six cases besides Gradle's (`vex_gradle_lock_above_base`): **pnpm bundled copies** (`vex_pnpm_bundled_copy`): a `packages:` entry's `bundledDependencies:` names the copies pnpm unpacks from that package's own tarball, but pnpm never locks them, so the bundled version is not in the lock. A pnpm reference whose package name a `bundledDependencies` list in the same lock names is omitted whatever its version (a missed attestation when the bundled copy is another version, never a false one), and `bundledDependencies: true` (or a value that cannot be read) omits every reference of that lock. It reaches no other lock. **deno.lock** (`vex_deno_lock_copy`): `deno install` installs a `package.json` project's npm dependencies from `deno.lock` and never reads `package-lock.json` / `pnpm-lock.yaml` / `yarn.lock`, so an npm-family reference whose `name@version` the `deno.lock` npm section also locks is omitted (#406). Whether Deno or another package manager populates `node_modules` (`nodeModulesDir: "manual"` allows either) is not in the files, so this holds whatever `nodeModulesDir` says. **Maven reactor roots** (`vex_maven_reactor_root`): a hosted pin in a root `pom.xml` that declares `` / ``, or whose subprojects Maven 4 discovers (see the hosted Maven rewriter), is omitted, because a module's own literal `` overrides a root pin and module poms are not read (#261); hosted scan refuses such roots (`redirect_maven_multimodule_unsupported`), so this only covers pins an older release wrote. **Maven classifier copies** (`vex_maven_classifier_unpatched`): a `` dependency of a hosted-pinned GA is its own coordinate; the classifier-less pin does not retarget it and the grant serves only the main jar, so Maven fetches it from the next repository. When a classifier copy other than `sources` / `javadoc` (`tests`, a native or JDK-specific build), live or inside ``, resolves any version other than the suffixed pin — its own literal ``, a `` entry with the same classifier (a profile's overriding the live one), or no version in the root pom — the pin is omitted. A pre-v5 single-pom vendored repository holds only the main jar, so any such copy omits its reference. `sources` / `javadoc` copies never run on a classpath and do not withhold the statement; hosted scan only warns about them (`redirect_maven_classifier_unsupported`) and skips the dep when an executable copy names the patched release. **Maven profile declarations** (`vex_maven_profile_unpatched`): a `` declaration of a pinned GA's main jar in the root `pom.xml` at any version other than the pin (the base release, another release, a `${property}` the pom does not resolve) overrides the pin whenever that profile is active, so the reference is omitted. A profile `` entry always counts; a profile `` entry counts only when management governs the pin (no direct `` outside ``), since a direct literal version beats management. A declaration without a `` takes the live pin, and a `pom` (or `java-source` / `javadoc`) typed one carries no code; neither withholds the statement. Activation is not evaluated: every profile counts, as in vendored mode, which rewrites profile declarations too; hosted scan leaves them as written (`redirect_maven_profile_dependency_unpatched`). A pin spelled through a property counts the same way: a `${property}` `` is interpolated through every property it names (at most 16 levels deep; a cycle or an undefined name never resolves to a pin), and when any profile's `` — or several profiles' together — redefine one of those properties so that it resolves anything other than the pin (or nothing), the reference is omitted too; a `.mvn/maven.config` user property wins over every profile's. A profile declaration reads its own profile's `` first. The same holds for a pre-v5 single-pom vendored repository, which serves only the original version. **Maven user properties** (`vex_maven_config_override`): Maven resolves a `${property}` `` from `.mvn/maven.config`'s `-D` user properties before the pom's `` (`${project.*}` / `${pom.*}` always come from the model). A pin the pom spells through a property that `.mvn/maven.config` redefines resolves that other version, so the reference is omitted. A Socket version that only a `-D` user property supplies is not `pom.xml` wiring (hosted scan never writes one, and `rollback` / `remove` never edit `.mvn/maven.config`): it is no reference at all, only a diagnostic. +* **Unattested references.** Some evidence shows a build may run a copy no wiring reaches, but cannot be tied to the reference's exact `name@version` or cannot say the build runs it. The reference then stays a reference: `list`, `rollback` and `remove` find it, and the ledgers' liveness gates (`vendor --check`, `scan`) keep treating the wiring as live, because re-running `scan` / `vendor` could never clear the evidence. Only `vex` omits it, as a run warning and as the `failed[].reason`. Six cases besides Gradle's (`vex_gradle_lock_above_base`): **pnpm bundled copies** (`vex_pnpm_bundled_copy`): a `packages:` entry's `bundledDependencies:` names the copies pnpm unpacks from that package's own tarball, but pnpm never locks them, so the bundled version is not in the lock. A pnpm reference whose package name a `bundledDependencies` list in the same lock names is omitted whatever its version (a missed attestation when the bundled copy is another version, never a false one), and `bundledDependencies: true` (or a value that cannot be read) omits every reference of that lock. It reaches no other lock. **deno.lock** (`vex_deno_lock_copy`): `deno install` installs a `package.json` project's npm dependencies from `deno.lock` and never reads `package-lock.json` / `pnpm-lock.yaml` / `yarn.lock`, so an npm-family reference whose `name@version` the `deno.lock` npm section also locks is omitted (#406). Whether Deno or another package manager populates `node_modules` (`nodeModulesDir: "manual"` allows either) is not in the files, so this holds whatever `nodeModulesDir` says. **Maven reactor roots** (`vex_maven_reactor_root`): a hosted pin in a root `pom.xml` that declares `` / ``, or whose subprojects Maven 4 discovers (see the hosted Maven rewriter), is omitted, because a module's own literal `` overrides a root pin and module poms are not read (#261); hosted scan refuses such roots (`redirect_maven_multimodule_unsupported`), so this only covers pins an older release wrote. **Maven classifier copies** (`vex_maven_classifier_unpatched`): a `` dependency of a hosted-pinned GA is its own coordinate; the classifier-less pin does not retarget it and the grant serves only the main jar, so Maven fetches it from the next repository. When a classifier copy other than `sources` / `javadoc` (`tests`, a native or JDK-specific build), live or inside ``, resolves any version other than the suffixed pin — its own literal ``, a `` entry with the same classifier (a profile's overriding the live one), or no version in the root pom — the pin is omitted. A pre-v5 single-pom vendored repository holds only the main jar, so any such copy omits its reference. `sources` / `javadoc` copies never run on a classpath and do not withhold the statement; hosted scan only warns about them (`redirect_maven_classifier_unsupported`) and skips the dep when an executable copy names the patched release. **Maven profile declarations** (`vex_maven_profile_unpatched`): a `` declaration of a pinned GA's main jar in the root `pom.xml` at any version other than the pin (the base release, another release, a `${property}` the pom does not resolve) overrides the pin whenever that profile is active, so the reference is omitted. A profile `` entry always counts; a profile `` entry counts only when management governs the pin (no direct `` outside ``), since a direct literal version beats management. A declaration without a `` takes the live pin, and a `pom` (or `java-source` / `javadoc`) typed one carries no code; neither withholds the statement. Activation is not evaluated: every profile counts, as in vendored mode, which rewrites profile declarations too; hosted scan leaves them as written (`redirect_maven_profile_dependency_unpatched`). A pin spelled through a property counts the same way: a `${property}` `` is interpolated through every property it names (at most 16 levels deep; a cycle or an undefined name never resolves to a pin), and when any profile's `` — or several profiles' together — redefine one of those properties so that it resolves anything other than the pin (or nothing), the reference is omitted too; a `.mvn/maven.config` user property wins over every profile's. A profile declaration reads its own profile's `` first. Coordinates count the same way: when a profile's `` (or several profiles' together, or the profile holding the declaration) redefine a property a `${property}` `` / `` names, so that the declaration carrying the pin names another package (the pin then no longer applies to the patched GA) or another declaration names the patched GA (its main jar, or an executable classifier copy) at a version other than the pin, or as a classifier copy with no version of its own, the reference is omitted; a profile value the pom cannot resolve may name any package, and a user property wins over every profile's. The same holds for a pre-v5 single-pom vendored repository, which serves only the original version. **Maven user properties** (`vex_maven_config_override`): Maven resolves a `${property}` `` from `.mvn/maven.config`'s `-D` user properties before the pom's `` (`${project.*}` / `${pom.*}` always come from the model). A pin the pom spells through a property that `.mvn/maven.config` redefines resolves that other version, so the reference is omitted. A Socket version that only a `-D` user property supplies is not `pom.xml` wiring (hosted scan never writes one, and `rollback` / `remove` never edit `.mvn/maven.config`): it is no reference at all, only a diagnostic. * **Shrinkwrap without a twin (#899).** npm >= 12 never reads `npm-shrinkwrap.json`: on a project whose only npm lock is the shrinkwrap it resolves the tree from the registry and writes a fresh `package-lock.json`, so a Socket reference there reaches npm <= 11 only. The reference is still discovered, so `list`, `rollback` and `remove` manage it, but `vex` omits the patch (`vex_npm_shrinkwrap_only`, as a run warning and as the `failed[].reason`). A `package-lock.json` beside it (wired the same way) makes it attestable again. Hosted and vendored runs still rewire the shrinkwrap and warn `redirect_npm_shrinkwrap_only` / `vendor_npm_shrinkwrap_only`. * **Lockless pins.** With no lock to name a version, a `Cargo.toml` pin (every declaration on `socket-patch-`, that registry defined on the patch host for the same uuid) or an exclusive nuget exact-id mapping is never a reference on its own, so v5.0 does not attest it (nor does `list` show it, or `rollback` / `remove` restore it — restore those files from version control). Only a pre-v5 redirect-ledger record naming a version the pin admits keeps it live. The same holds for a gem wired only in the `Gemfile` (the pre-bundler-2.6 mixed state, lock not converged). @@ -2678,7 +2678,7 @@ match it, withholds the statement: | `vex_deno_lock_copy` | run warning and `failed[].reason` | An npm pin is wired, but `deno.lock` locks the same `name@version`, which `deno install` installs without the wiring; no statement while it does. `vendor --check` and `scan` still treat the wiring as live. | | `vex_maven_reactor_root` | run warning and `failed[].reason` | A hosted Maven pin sits in a root `pom.xml` that declares `` / `` (a profile's included), where a module's own literal `` overrides it; only the root pom is read, so no statement (#261). `list`, `rollback` and `remove` still find the pin. | | `vex_maven_classifier_unpatched` | run warning and `failed[].reason` | A hosted Maven pin's GA also has an executable `` copy (not `sources` / `javadoc`; live or inside ``) at a version other than the pin, which the classifier-less pin does not retarget and the grant does not serve; no statement while it does. `list`, `rollback` and `remove` still find the pin. | -| `vex_maven_profile_unpatched` | run warning and `failed[].reason` | A Maven pin's GA main jar is also declared inside `` in the root `pom.xml` at a version other than the pin (a profile `` entry only where management governs the pin), or a profile's `` redefine a property the pin's `${property}` version names so it resolves another version, which overrides the pin whenever that profile is active; no statement while it does. `list`, `rollback` and `remove` still find the pin. | +| `vex_maven_profile_unpatched` | run warning and `failed[].reason` | A Maven pin's GA main jar is also declared inside `` in the root `pom.xml` at a version other than the pin (a profile `` entry only where management governs the pin), or a profile's `` redefine a property the pin's `${property}` version names so it resolves another version, or a property a `${property}` groupId / artifactId names so the pin names another package or another declaration becomes the pinned GA off the pin, which overrides the pin whenever that profile is active; no statement while it does. `list`, `rollback` and `remove` still find the pin. | | `vex_maven_config_override` | run warning and `failed[].reason` | A hosted Maven pin is spelled through a `${property}` that a `-D` user property in `.mvn/maven.config` redefines, so Maven resolves another version; no statement while it does. `list`, `rollback` and `remove` still find the pin. | | `vex_gradle_derived_cache_unchecked` | run warning | The derived-cache walk was cut short (a very large transforms cache); the statement is still emitted, the copies the walk did reach were checked. | diff --git a/crates/socket-patch-cli/src/commands/vex_sources.rs b/crates/socket-patch-cli/src/commands/vex_sources.rs index 51c98e35b..6dc982a2d 100644 --- a/crates/socket-patch-cli/src/commands/vex_sources.rs +++ b/crates/socket-patch-cli/src/commands/vex_sources.rs @@ -280,9 +280,11 @@ fn unattested_note(kind: UnattestedKind) -> (&'static str, &'static str) { UnattestedKind::MavenProfileUnpatched => ( NOTE_MAVEN_PROFILE_UNPATCHED, "not attested while a profile declares it at, or its move it to, \ - another version; the wiring itself is intact, so re-running `scan` does not change \ - this (drop that profile or property or set it to the pin, or re-patch \ - with `scan --mode vendored`)", + another version, or its redefine a groupId / artifactId property so \ + the pin names another package or another declaration names this one; the wiring \ + itself is intact, so re-running `scan` does not change this (drop that profile \ + or property or set it to the pin, or re-patch with \ + `scan --mode vendored`)", ), UnattestedKind::MavenConfigOverride => ( NOTE_MAVEN_CONFIG_OVERRIDE, diff --git a/crates/socket-patch-core/src/formats/maven/mod.rs b/crates/socket-patch-core/src/formats/maven/mod.rs index 6c8f99209..9cc7d622c 100644 --- a/crates/socket-patch-core/src/formats/maven/mod.rs +++ b/crates/socket-patch-core/src/formats/maven/mod.rs @@ -39,8 +39,22 @@ pub(crate) struct PomRepo { #[derive(Debug)] pub(crate) struct PomDep { + /// `` / `` as [`ScopedDep::group`] reads them: + /// while no profile is active, an undefined `${…}` kept as written. pub(crate) group: String, pub(crate) artifact: String, + /// The trimmed `` / `` text as written. + pub(crate) group_text: String, + pub(crate) artifact_text: String, + /// The other `(groupId, artifactId)` pairs the declaration names when + /// some set of profiles is active whose `` redefine a + /// property its coordinates name (transitively), or, for a declaration + /// inside a profile, while its own profile is: a superset + /// ([`interpolate_each_keeping`], each coordinate's values paired with + /// each of the other's), in which a reference some set leaves + /// unresolved stays as written ([`may_name`] reads it as any text). + /// Empty when no profile can move it. + pub(crate) coordinate_alternatives: Vec<(String, String)>, /// Trimmed version, every `${prop}` interpolated /// ([`interpolate_strict`]) from the project model (`project.*` / /// `pom.*`), the `` of the profile holding the declaration @@ -254,6 +268,55 @@ impl PomScope { (spelled, build, alternatives) } + /// [`PomDep::coordinate_alternatives`] of the declaration at `pos` + /// whose coordinates read `base` ([`ScopedDep::group`] / + /// [`ScopedDep::artifact`]) and are written `text`. + fn coordinate_alternatives( + &self, + text: (&str, &str), + base: (&str, &str), + pos: usize, + ) -> Vec<(String, String)> { + if !text.0.contains("${") && !text.1.contains("${") { + return Vec::new(); + } + let own = self.own_profile(pos); + // Every value a coordinate may read, `base` included. What it reads + // with no profile active is `base`, whatever the two interpolators' + // bounds make of an odd property (a chain deeper than the lenient + // one follows, a cycle), so that reading is no alternative. + let values = |text: &str, base: &str| -> BTreeSet { + let mut all = BTreeSet::from([base.to_string()]); + if !text.contains("${") { + return all; + } + match interpolate_each_keeping(text, &|name| self.lookup_any(name, &own)) { + Some(each) => all.extend(each), + None => { + all.insert(text.to_string()); + } + } + let plain = |name: &str| self.lookup(name, &[], true).into_iter().collect(); + for v in interpolate_each_keeping(text, &plain).unwrap_or_default() { + if v != base { + all.remove(&v); + } + } + all + }; + let groups = values(text.0, base.0); + let artifacts = values(text.1, base.1); + let mut out = Vec::new(); + for g in &groups { + for a in &artifacts { + if (g.as_str(), a.as_str()) != base { + out.push((g.clone(), a.clone())); + } + } + } + out + } + /// Inside a plugin / deploy section (never project resolution). pub(crate) fn is_ignored(&self, pos: usize) -> bool { inside(pos, &self.ignored) @@ -301,8 +364,13 @@ pub(crate) struct ScopedDep { /// `` or the project's own coordinates define /// interpolated (see [`interpolate`]); an /// undefined one stays as written, so [`may_name`] can tell it apart. + /// No profile's `` are read, not even those of the profile + /// holding the declaration ([`PomDep::coordinate_alternatives`] does). pub(crate) group: Option, pub(crate) artifact: Option, + /// The trimmed `` / `` text as written. + pub(crate) group_text: Option, + pub(crate) artifact_text: Option, /// Inner-text byte range of the literal ``, when present. pub(crate) version_inner: Option<(usize, usize)>, /// Trimmed `` text as written (no property resolution). @@ -321,12 +389,18 @@ impl PomScope { for dep in self.elements("dependency")? { let body = blank_elements(dep.inner(&self.masked), "exclusions")?; let version = elements(&body, "version")?.into_iter().next(); + let group_text = child_text(&body, "groupId")?; + let artifact_text = child_text(&body, "artifactId")?; out.push(ScopedDep { element: dep, - group: child_text(&body, "groupId")? - .map(|g| interpolate(&g, &self.coordinate_refs)), - artifact: child_text(&body, "artifactId")? - .map(|a| interpolate(&a, &self.coordinate_refs)), + group: group_text + .as_deref() + .map(|g| interpolate(g, &self.coordinate_refs)), + artifact: artifact_text + .as_deref() + .map(|a| interpolate(a, &self.coordinate_refs)), + group_text, + artifact_text, version_inner: version.map(|v| { ( dep.inner_start + v.inner_start, @@ -370,9 +444,16 @@ pub(crate) fn parse_pom_with(raw: &str, user: &BTreeMap) -> Resu } for dep in scope.dependencies()? { - let (Some(group), Some(artifact)) = (dep.group, dep.artifact) else { + let (Some(group), Some(artifact), Some(group_text), Some(artifact_text)) = + (dep.group, dep.artifact, dep.group_text, dep.artifact_text) + else { continue; }; + let coordinate_alternatives = scope.coordinate_alternatives( + (&group_text, &artifact_text), + (&group, &artifact), + dep.element.start, + ); let (version, build_version, version_alternatives) = match &dep.version_text { Some(text) => { let (spelled, build, alternatives) = scope.resolve_version(text, dep.element.start); @@ -383,6 +464,9 @@ pub(crate) fn parse_pom_with(raw: &str, user: &BTreeMap) -> Resu pom.deps.push(PomDep { group, artifact, + group_text, + artifact_text, + coordinate_alternatives, version, build_version, version_text: dep.version_text, @@ -523,18 +607,31 @@ pub(crate) fn interpolate_each( lookup: &dyn Fn(&str) -> Vec, ) -> Option> { let lookups = std::cell::Cell::new(MAX_LOOKUPS); - expand(value, lookup, &mut Vec::new(), &lookups) + expand(value, lookup, &mut Vec::new(), &lookups, false) +} + +/// [`interpolate_each`], except that a reference it cannot resolve (an +/// undefined name, a cycle, a chain deeper than +/// [`MAX_INTERPOLATION_DEPTH`], an unterminated `${`) is kept as written +/// instead of failing the whole text, the way coordinates are read +/// ([`ScopedDep::group`]): each kept `${name}` then stands for any text +/// ([`may_name`]). `None` only past the work or result bounds. +pub(crate) fn interpolate_each_keeping( + value: &str, + lookup: &dyn Fn(&str) -> Vec, +) -> Option> { + let lookups = std::cell::Cell::new(MAX_LOOKUPS); + expand(value, lookup, &mut Vec::new(), &lookups, true) } +/// [`interpolate_each`] (`keep` false) or [`interpolate_each_keeping`]. fn expand( value: &str, lookup: &dyn Fn(&str) -> Vec, stack: &mut Vec, lookups: &std::cell::Cell, + keep: bool, ) -> Option> { - if stack.len() > MAX_INTERPOLATION_DEPTH { - return None; - } let mut texts = BTreeSet::from([String::new()]); let mut rest = value; loop { @@ -545,22 +642,37 @@ fn expand( let Some(after) = reference else { return concat(&texts, &BTreeSet::from([literal.to_string()])); }; - let close = after.find('}')?; + let Some(close) = after.find('}') else { + return match keep { + true => concat(&texts, &BTreeSet::from([rest.to_string()])), + false => None, + }; + }; let name = &after[..close]; - if stack.iter().any(|n| n == name) { - return None; - } - lookups.set(lookups.get().checked_sub(1)?); - let raws = lookup(name); - if raws.is_empty() { - return None; - } - stack.push(name.to_string()); - let mut values = BTreeSet::new(); - for raw in &raws { - values.extend(expand(raw, lookup, stack, lookups)?); - } - stack.pop(); + let written = || BTreeSet::from([format!("${{{name}}}")]); + let values = if stack.iter().any(|n| n == name) || stack.len() >= MAX_INTERPOLATION_DEPTH { + if !keep { + return None; + } + written() + } else { + lookups.set(lookups.get().checked_sub(1)?); + let raws = lookup(name); + if raws.is_empty() { + if !keep { + return None; + } + written() + } else { + stack.push(name.to_string()); + let mut values = BTreeSet::new(); + for raw in &raws { + values.extend(expand(raw, lookup, stack, lookups, keep)?); + } + stack.pop(); + values + } + }; let prefixed = concat(&texts, &BTreeSet::from([literal.to_string()]))?; texts = concat(&prefixed, &values)?; rest = &after[close + 1..]; @@ -1283,6 +1395,180 @@ mod tests { ); } + /// The keeping interpolator leaves what it cannot resolve as written + /// (an undefined name, a cycle, too deep, an unterminated `${`) and + /// fails only past its work bounds. + #[test] + fn keeping_interpolation_leaves_unresolved_references() { + let props: std::collections::BTreeMap<&str, &str> = [ + ("a", "org"), + ("b", "${a}.${nope}"), + ("c", "x${c}"), + ("d", "${a}"), + ] + .into(); + let lookup = |name: &str| props.get(name).map(|v| v.to_string()).into_iter().collect(); + let each = |text: &str| { + super::interpolate_each_keeping(text, &lookup) + .map(|set| set.into_iter().collect::>()) + }; + let one = |v: &str| Some(vec![v.to_string()]); + assert_eq!(each("${b}-x"), one("org.${nope}-x")); + assert_eq!(each("${c}"), one("x${c}")); + assert_eq!(each("${d}.${a"), one("org.${a")); + assert_eq!(each("plain"), one("plain")); + let many = |name: &str| match name { + "v" => vec!["1".to_string(), "2".to_string()], + _ => Vec::new(), + }; + assert_eq!( + super::interpolate_each_keeping("${v}.${w}", &many) + .map(|set| set.into_iter().collect::>()), + Some(vec!["1.${w}".to_string(), "2.${w}".to_string()]) + ); + let deep: std::collections::BTreeMap = (0..20) + .map(|i| (format!("p{i}"), format!("${{p{}}}", i + 1))) + .collect(); + let deep_lookup = |name: &str| deep.get(name).cloned().into_iter().collect(); + assert_eq!( + super::interpolate_each_keeping("${p0}", &deep_lookup), + Some(std::collections::BTreeSet::from(["${p16}".to_string()])) + ); + } + + /// The `(groupId, artifactId)` pairs a profile's `` may move + /// a `${property}` coordinate to: every profile (and set of them) + /// counts, a declaration inside a profile reads its own first, a value + /// left unresolved stays as written, and user properties and model + /// references no profile can redefine. + #[test] + fn profile_properties_give_coordinate_alternatives() { + let alternatives = |props: &str, profiles: &[&str], user: &[(&str, &str)], deps: &str| { + let profiles: String = profiles + .iter() + .map(|p| format!("{p}")) + .collect(); + let pom = format!( + "org.self{props}\ + {deps}{profiles}" + ); + let user = user + .iter() + .map(|(k, v)| (k.to_string(), v.to_string())) + .collect(); + super::parse_pom_with(&pom, &user) + .unwrap() + .deps + .into_iter() + .map(|d| ((d.group, d.artifact), d.coordinate_alternatives)) + .collect::>() + }; + let dep = |g: &str, a: &str| { + format!( + "{g}{a}\ + 1" + ) + }; + let pair = |g: &str, a: &str| (g.to_string(), a.to_string()); + let one = |props, profiles: &[&str], user: &[(&str, &str)], g: &str, a: &str| { + alternatives(props, profiles, user, &dep(g, a)).remove(0) + }; + assert_eq!( + one("org.a", &["org.b"], &[], "${g}", "x"), + (pair("org.a", "x"), vec![pair("org.b", "x")]) + ); + assert_eq!( + one("org.a", &["org.a"], &[], "${g}", "x"), + (pair("org.a", "x"), vec![]) + ); + assert_eq!( + one("org.a", &["org.b"], &[], "${g}", "x"), + (pair("org.a", "x"), vec![]) + ); + // Both coordinates, each value paired with each of the other's. + assert_eq!( + one("a", &["b"], &[], "org.${v}", "${v}-api").1, + [ + pair("org.a", "b-api"), + pair("org.b", "a-api"), + pair("org.b", "b-api") + ] + ); + // Nested, and two profiles together. + assert_eq!( + one( + "${w}org.a", + &["org.b", "${w}.c"], + &[], + "${g}", + "x" + ) + .1, + [ + pair("org.a.c", "x"), + pair("org.b", "x"), + pair("org.b.c", "x") + ] + ); + // Unresolved under a profile, or a cycle: kept as written. + assert_eq!( + one("org.a", &["${nope}"], &[], "${g}", "x").1, + [pair("${nope}", "x")] + ); + assert_eq!( + one("org.a", &["${g}"], &[], "${g}", "x").1, + [pair("${g}", "x")] + ); + // Undefined with no profile involved: no alternative. + assert_eq!( + one("org.a", &[], &[], "${g}.${nope}", "x"), + (pair("org.a.${nope}", "x"), vec![]) + ); + // User properties and model references win over every profile's. + assert_eq!( + one( + "org.a", + &["org.b"], + &[("g", "org.c")], + "${g}", + "x" + ), + (pair("org.c", "x"), vec![]) + ); + assert_eq!( + one( + "", + &["org.b"], + &[], + "${project.groupId}", + "x" + ), + (pair("org.self", "x"), vec![]) + ); + + // A profile's own declaration reads its own properties first. + let pom = format!( + "org.a{}\ + porg.b\ + {}", + dep("${g}", "x"), + dep("${g}", "x") + ); + let deps: Vec<_> = super::parse_pom(&pom) + .unwrap() + .deps + .into_iter() + .map(|d| (d.in_profile, d.group, d.coordinate_alternatives)) + .collect(); + assert_eq!( + deps, + [ + (false, "org.a".to_string(), vec![pair("org.b", "x")]), + (true, "org.a".to_string(), vec![pair("org.b", "x")]), + ] + ); + } + #[test] fn suffix_grammar_is_exact() { assert_eq!( diff --git a/crates/socket-patch-core/src/vendor/jvm/maven_reactor.rs b/crates/socket-patch-core/src/vendor/jvm/maven_reactor.rs index 8b8e9b6cc..acf585cfb 100644 --- a/crates/socket-patch-core/src/vendor/jvm/maven_reactor.rs +++ b/crates/socket-patch-core/src/vendor/jvm/maven_reactor.rs @@ -1803,6 +1803,44 @@ impl Reactor { }) } + /// Where `dep` of `rel`, a declaration named through `${...}` + /// coordinates, reads a groupId and artifactId (each `None` when + /// undefined there) that `hit` accepts, other than `rel` with no + /// profile active: an inheritor of `rel`, or `rel` or an inheritor with + /// a profile on its chain active (which covers the profile holding + /// `dep`). Maven interpolates after inheritance and with the active + /// profiles' `` merged in, then matches management and + /// pins. Profile activation is not evaluated, so every profile counts + /// (one at a time). + fn coordinates_elsewhere( + &self, + rel: &str, + dep: usize, + hit: &dyn Fn(Option, Option) -> bool, + ) -> Option { + let doc = &self.poms[rel].doc; + let read = |resolve: &dyn Fn(&str) -> Option| { + hit( + doc.coordinate(dep, "groupId", resolve), + doc.coordinate(dep, "artifactId", resolve), + ) + }; + std::iter::once(rel) + .chain(self.inheritors(rel)) + .find_map(|reader| { + let plain = (reader != rel && read(&|v| self.interpolate(reader, v))) + .then(|| reader.to_string()); + plain.or_else(|| { + self.chain(reader).find_map(|at| { + self.poms[at].profile_props.iter().find_map(|(id, props)| { + read(&|v| self.interpolate_with(reader, v, Some((at, props)))) + .then(|| format!("{reader} under profile {id} of {at}")) + }) + }) + }) + }) + } + /// Every pom in scope that inherits from `rel` (has it on its chain). fn inheritors<'s>(&'s self, rel: &'s str) -> impl Iterator + 's { self.scope @@ -1830,6 +1868,7 @@ impl Reactor { let doc = &self.poms[rel].doc; let ga = format!("{}:{}", patch.group_id, patch.artifact_id); self.warn_unresolved_coordinates(rel, patch, warnings, unpinned, uncertain); + self.warn_moved_coordinates(rel, patch, warnings, unpinned, uncertain); for (dep, key) in self.keyed_declarations(rel, patch.group_id, patch.artifact_id) { if doc .child_text(dep, "type") @@ -1849,15 +1888,13 @@ impl Reactor { continue; } let root = self.local_root(rel); - // Maven interpolates after inheritance: a pom that inherits this - // declaration may name another artifact through it, which the - // literal SV must not reach. + // Maven interpolates after inheritance and with the active + // profiles: a pom that inherits this declaration, or a profile + // redefining a property it names, may make it another artifact, + // which the literal SV must not reach. if doc.has_property_coordinate(dep) { - let other = self.inheritors(rel).find(|p| { - let resolve = |v: &str| self.interpolate(p, v); - doc.coordinate(dep, "groupId", &resolve).as_deref() != Some(patch.group_id) - || doc.coordinate(dep, "artifactId", &resolve).as_deref() - != Some(patch.artifact_id) + let other = self.coordinates_elsewhere(rel, dep, &|g, a| { + g.as_deref() != Some(patch.group_id) || a.as_deref() != Some(patch.artifact_id) }); if let Some(p) = other { warnings.push(degraded( @@ -2027,6 +2064,86 @@ impl Reactor { } } +impl Reactor { + /// Warn for each declaration of `rel` whose `${...}` groupId or + /// artifactId reads another artifact in `rel` itself but may read + /// `patch`'s g:a in an inheritor or with a profile active + /// ([`Self::coordinates_elsewhere`]): it is left as is, and there it + /// declares the g:a at its own version. One with a version beats any + /// pin, so its local root is not pinned. + fn warn_moved_coordinates( + &self, + rel: &str, + patch: &JvmPatch<'_>, + warnings: &mut Vec, + unpinned: &mut BTreeSet, + uncertain: &mut BTreeSet, + ) { + let doc = &self.poms[rel].doc; + let resolve = |v: &str| self.interpolate(rel, v); + for dep in doc.declarations() { + let (Some(g), Some(a)) = ( + doc.child_text(dep, "groupId"), + doc.child_text(dep, "artifactId"), + ) else { + continue; + }; + let other_variant = doc + .child_text(dep, "type") + .is_some_and(|t| !t.is_empty() && t != "jar") + || doc + .child_text(dep, "classifier") + .is_some_and(|c| !c.is_empty()); + // Undefined in `rel`: `warn_unresolved_coordinates` weighs it; + // `patch`'s g:a in `rel`: `rewrite_declarations` does. + let (Some(here_g), Some(here_a)) = ( + doc.coordinate(dep, "groupId", &resolve), + doc.coordinate(dep, "artifactId", &resolve), + ) else { + continue; + }; + if other_variant + || !doc.has_property_coordinate(dep) + || doc.pin_at(dep).is_some() + || (here_g == patch.group_id && here_a == patch.artifact_id) + { + continue; + } + let could_be = |raw: &str, read: Option, want: &str| match read { + Some(v) => v == want, + None => may_interpolate_to(raw, want), + }; + let Some(there) = self.coordinates_elsewhere(rel, dep, &|rg, ra| { + could_be(&g, rg, patch.group_id) && could_be(&a, ra, patch.artifact_id) + }) else { + continue; + }; + let at = format!("{rel}:{}", doc.line_of(doc.nodes[dep].start)); + let versioned = doc + .child_text(dep, "version") + .is_some_and(|v| !v.is_empty()); + let root = self.local_root(rel); + let unpin = if versioned { + format!(", and {root} is not pinned") + } else { + String::new() + }; + warnings.push(degraded( + "coordinates_overridden", + format!( + "{at}: {g}:{a} is {here_g}:{here_a} here but may be {}:{} in {there}; \ + left as is, probably unpatched there{unpin}", + patch.group_id, patch.artifact_id, + ), + )); + if versioned { + unpinned.insert(root); + uncertain.insert(at); + } + } + } +} + /// Whether `raw`, with each `${...}` standing for any text, can read /// `want`. fn may_interpolate_to(raw: &str, want: &str) -> bool { @@ -5815,6 +5932,185 @@ mod tests { assert!(unwired(&applied(&files, &plan))); } + /// `root` with `{props}` and a profile `corp` + /// whose `` are `profile` (none when empty), before its + /// ``. + fn root_with(props: &str, profile: &str) -> String { + let root = ROOT.replace( + " ", + &format!(" {props}\n "), + ); + match profile { + "" => root, + p => root.replace( + " ", + &format!( + " corp{p}\ + \n " + ), + ), + } + } + + /// A declaration whose `${...}` groupId a profile redefines names + /// another artifact whenever that profile is active, which the literal + /// SV must not reach: it is left as is and its root unpinned, as for + /// an inheritor that resolves it differently. A `.mvn/maven.config` + /// user property wins over the profile's. + #[test] + fn a_profile_moving_the_declared_coordinates_is_left_alone() { + let decl = "${ct.group}\ + commons-text1.10.0"; + let a = module("a", decl); + let props = "org.apache.commons"; + for profile in [ + "org.other", + "${nope}", + ] { + let files = fs(&[ + ("pom.xml", &root_with(props, profile)), + ("a/pom.xml", &a), + ("b/pom.xml", &module("b", "")), + ]); + let plan = run(&files).unwrap(); + assert_eq!(reasons(&plan), ["coordinates_overridden"], "{profile}"); + assert!( + plan.warnings[0].detail.contains("profile corp"), + "{:?}", + plan.warnings + ); + let after = applied(&files, &plan); + assert_eq!(text(&after, "a/pom.xml"), a); + assert!(!root_pinned(&plan, &files)); + assert!(unwired(&after), "{profile}"); + } + + // A vendored reactor a profile is added to later is not attestable. + let files = fs(&[ + ("pom.xml", &root_with(props, "")), + ("a/pom.xml", &a), + ("b/pom.xml", &module("b", "")), + ]); + let (_, mut after) = vendor(&files); + assert_eq!(attestable(&after), (true, true)); + let root = text(&after, "pom.xml").replace( + " ", + " corporg.other\ + \n ", + ); + after.insert("pom.xml".to_string(), root.into_bytes()); + assert_eq!(attestable(&after), (true, false)); + + // The same profile, beaten by a user property, or agreeing. + for (profile, config) in [ + ( + "org.other", + "-Dct.group=org.apache.commons\n", + ), + ("org.apache.commons", ""), + ] { + let files = fs(&[ + ("pom.xml", &root_with(props, profile)), + ("a/pom.xml", &a), + ("b/pom.xml", &module("b", "")), + (".mvn/maven.config", config), + ]); + let (plan, after) = vendor(&files); + assert!(plan.warnings.is_empty(), "{:?}", plan.warnings); + assert_eq!(text(&after, "a/pom.xml"), a.replace("1.10.0", SV)); + assert_eq!(attestable(&after), (true, true), "{profile}"); + } + } + + /// A declaration whose `${...}` groupId names another artifact with no + /// profile active, but the patched one under a profile, declares the + /// patched artifact at its own version there, beating the root pin: + /// it is left as is, warned about, and its root unpinned, so a reactor + /// vendored before that profile was added is not attestable. Unrelated + /// coordinate properties change nothing. + #[test] + fn a_profile_turning_a_declaration_into_the_patched_artifact_is_weighed() { + let other = |v: &str| { + format!( + "${{lib.group}}\ + commons-text{v}" + ) + }; + let props = "org.other"; + let a = module( + "a", + &format!("{}{}", dep("1.10.0"), other("1.9")), + ); + for (profile, warned) in [ + ("org.apache.commons", true), + ("${nope}", true), + ("org.third", false), + ("org.apache.commons", false), + ] { + let files = fs(&[ + ("pom.xml", &root_with(props, profile)), + ("a/pom.xml", &a), + ("b/pom.xml", &module("b", "")), + ]); + let plan = run(&files).unwrap(); + if warned { + assert_eq!(reasons(&plan), ["coordinates_overridden"], "{profile}"); + assert!( + plan.warnings[0].detail.contains("profile corp") + && plan.warnings[0] + .detail + .contains("org.apache.commons:commons-text"), + "{:?}", + plan.warnings + ); + assert!(!root_pinned(&plan, &files), "{profile}"); + } else { + assert!(plan.warnings.is_empty(), "{profile}: {:?}", plan.warnings); + assert!(root_pinned(&plan, &files), "{profile}"); + } + } + + // No version of its own: the pin applies, so the root stays pinned. + let files = fs(&[ + ( + "pom.xml", + &root_with(props, "org.apache.commons"), + ), + ( + "a/pom.xml", + &module("a", &format!("{}{}", dep("1.10.0"), other(""))), + ), + ("b/pom.xml", &module("b", "")), + ]); + let plan = run(&files).unwrap(); + assert_eq!(reasons(&plan), ["coordinates_overridden"]); + assert!(root_pinned(&plan, &files)); + + // Vendored first, the profile added later: not attestable; a user + // property fixing the group keeps it attestable. + let files = fs(&[ + ("pom.xml", &root_with(props, "")), + ("a/pom.xml", &a), + ("b/pom.xml", &module("b", "")), + ]); + let (_, after) = vendor(&files); + assert_eq!(attestable(&after), (true, true)); + let profiled = text(&after, "pom.xml").replace( + " ", + " corp\ + org.apache.commons\n \ + ", + ); + let mut later = after.clone(); + later.insert("pom.xml".to_string(), profiled.into_bytes()); + assert_eq!(attestable(&later), (true, false)); + later.insert( + ".mvn/maven.config".to_string(), + b"-Dlib.group=org.other\n".to_vec(), + ); + assert_eq!(attestable(&later), (true, true)); + } + fn attestable(files: &Fs) -> (bool, bool) { let read = |p: &str| files.get(p).cloned(); let c = Coords { diff --git a/crates/socket-patch-core/src/vex/discover/maven.rs b/crates/socket-patch-core/src/vex/discover/maven.rs index 2c4e7f2a2..c920f31e4 100644 --- a/crates/socket-patch-core/src/vex/discover/maven.rs +++ b/crates/socket-patch-core/src/vex/discover/maven.rs @@ -66,6 +66,12 @@ //! `.mvn/maven.config`). A pin the build resolves but that any profile's //! (or set of profiles') `` make resolve anything else keeps //! the ref unattested too, as a profile declaration does. +//! So do `${property}` coordinates a profile's `` redefine +//! (Maven merges them in before it interpolates a groupId / artifactId, +//! then matches pins): the declaration carrying the pin then names +//! another package, or another declaration becomes the pinned GA at a +//! version off the pin. Coordinates keep an undefined reference as +//! written, so a profile value this pom cannot resolve may name anything. //! //! Integrity: when the pom sha256 was known the rewriter also writes Maven //! Trusted Checksums — `.mvn/checksums/checksums.sha256` lines @@ -123,7 +129,7 @@ use super::{ }; use crate::formats::maven::{ is_executable_classifier, is_maven_coordinate, is_maven_version_text, maven_config_properties, - may_shadow, parse_pom_with, split_socket_version, Pom, PomDep, PomRepo, + may_name, may_shadow, parse_pom_with, split_socket_version, Pom, PomDep, PomRepo, }; use crate::patch::redirect::{MVN_CHECKSUMS, MVN_CONFIG, TRUSTED_CHECKSUMS_ON}; use crate::utils::digest::sha256_hex; @@ -830,12 +836,93 @@ fn bypasses( if let Some(detail) = unpatched_classifier_copy(deps, group, artifact, pinned, wiring) { found.push((UnattestedKind::MavenClassifierUnpatched, detail)); } - if let Some(detail) = profile_override(deps, group, artifact, pinned, built.direct.is_empty()) { + if let Some(detail) = profile_override(deps, group, artifact, pinned, built.direct.is_empty()) + .or_else(|| { + deps.iter() + .find_map(|d| coordinate_override(d, group, artifact, pinned)) + }) + { found.push((UnattestedKind::MavenProfileUnpatched, detail)); } found } +/// Why a profile moves `group:artifact` off `pinned` through a declaration +/// whose `${…}` groupId or artifactId some set of active profiles' +/// `` (or the profile holding it) redefine ([`PomDep::coordinate_alternatives`]); Maven merges +/// them over the pom's own before it interpolates the coordinates, and +/// matches management and pins after: +/// +/// * the live declaration carrying the pin (a main jar at `pinned`) then +/// names another package, so the pin no longer applies to +/// `group:artifact`, which resolves from wherever its other declarations +/// (or a transitive path) say; +/// * any other declaration then becomes `group:artifact` (its main jar, or +/// literally an executable classifier copy of it) at a version other +/// than `pinned`, or, for a classifier copy, with no version of its own. +/// A main jar without a version takes the live pin and moves nothing. +fn coordinate_override(d: &PomDep, group: &str, artifact: &str, pinned: &str) -> Option { + if d.coordinate_alternatives.is_empty() { + return None; + } + let section = if d.managed { + " " + } else { + "" + }; + let place = if d.in_profile { "a " } else { "a " }; + let written = format!("{}:{}", d.group_text, d.artifact_text); + let redefined = "a redefinition of a property its coordinates name"; + if d.group == group && d.artifact == artifact { + if d.in_profile || d.classifier.is_some() || build_version(d) != Some(pinned) { + return None; + } + let (g, a) = &d.coordinate_alternatives[0]; + return Some(format!( + "{POM}: {place}{section}declaration of {written} names {group}:{artifact} at the \ + patched {pinned} from the root , but {redefined} makes it {g}:{a}; \ + whenever that profile is active the pin no longer applies to {group}:{artifact}, \ + which Maven resolves from its other declarations instead" + )); + } + let main_type = d + .type_text + .as_deref() + .is_none_or(|t| t == "jar" || t.contains("${")); + let (g, a) = d + .coordinate_alternatives + .iter() + .find(|(g, a)| match d.classifier.as_deref() { + None => main_type && may_name(g, group) && may_name(a, artifact), + Some(c) => is_executable_classifier(c) && g == group && a == artifact, + })?; + let mut versions = build_version(d) + .into_iter() + .chain(d.version_alternatives.iter().map(String::as_str)); + let what = match (d.classifier.as_deref(), build_version(d)) { + (None, None) => return None, + (Some(c), None) => format!("classifier {c} with no of its own"), + (classifier, Some(_)) => { + let v = versions.find(|v| *v != pinned)?; + match classifier { + None => format!("{v}"), + Some(c) => format!("classifier {c} at {v}"), + } + } + }; + let which = if g == group && a == artifact { + String::new() + } else { + format!(", which may be {group}:{artifact},") + }; + Some(format!( + "{POM}: {place}{section}declaration of {written} names {}:{} with no profile active, \ + but {redefined} makes it {g}:{a}{which} carrying {what}, not the patched {pinned}; \ + whenever that profile is active Maven resolves it instead of the pin", + d.group, d.artifact + )) +} + /// Why the first executable classifier copy of `group:artifact` — live or /// inside `` — runs code the wiring does not serve, if one does. /// A classifier copy is its own coordinate: the classifier-less pin does @@ -2106,6 +2193,323 @@ mod tests { } } + /// One `property_project` case: root ``, the declarations, + /// each profile's body, `.mvn/maven.config`. + type CoordinateCase = (String, String, Vec, Option); + + /// Runs `case` and checks the slf4j-api ref is found, and attested + /// exactly when `attested` (else withheld as a profile override naming + /// the GA and the profile ``). + async fn assert_coordinate_case(case: &CoordinateCase, attested: bool) { + let (props, decl, profiles, config) = case; + let profiles: Vec<&str> = profiles.iter().map(String::as_str).collect(); + let p = property_project(props, decl, &profiles); + if let Some(config) = config { + p.write(".mvn/maven.config", config); + } + let out = run(&p).await; + assert_refs(&out, &[(FX_PURL, UUID_A, WiringMode::Hosted)]); + if attested { + assert!( + attests(&out, FX_PURL), + "{props} {decl} {profiles:?}: {:?}", + out.unattested + ); + return; + } + assert_eq!( + out.unattested.len(), + 1, + "{props} {decl} {profiles:?}: {:?}", + out.unattested + ); + let u = &out.unattested[0]; + assert_eq!(u.kind, UnattestedKind::MavenProfileUnpatched, "{decl}"); + assert_eq!((u.purl.as_str(), u.uuid.as_str()), (FX_PURL, UUID_A)); + assert!( + u.detail.contains("org.slf4j:slf4j-api") + && u.detail.contains("") + && u.detail.contains("coordinates"), + "{}", + u.detail + ); + } + + fn in_props(body: &str) -> String { + format!("{body}\n") + } + + /// A pin declared through a `${property}` groupId or artifactId is the + /// pin of that GA only while no active profile's `` + /// redefine the property (or one it names): Maven merges them over the + /// pom's own before it interpolates the coordinates, so with such a + /// profile active the pin names another package and slf4j-api resolves + /// from wherever else it is declared (here: transitively, unpinned). + #[tokio::test] + async fn profile_properties_moving_the_pinned_coordinates_are_not_attested() { + let pin = suffixed(UUID_A); + let direct = |g: &str, a: &str| { + format!("\n{}\n", dep(g, a, Some(&pin))) + }; + let managed = format!( + "\n{}\n", + dep("${g}", "slf4j-api", Some(&pin)) + ); + let case = |props: &str, decl: &str, profiles: &[&str], config: Option<&str>| { + ( + props.to_string(), + decl.to_string(), + profiles.iter().map(|p| in_props(p)).collect::>(), + config.map(str::to_string), + ) + }; + let g = "org.slf4j"; + let by_group = direct("${g}", "slf4j-api"); + let withheld = [ + // The groupId, the artifactId, or a managed pin. + case(g, &by_group, &["org.other"], None), + case( + "slf4j-api", + &direct("org.slf4j", "${a}"), + &["slf4j-simple"], + None, + ), + case(g, &managed, &["org.other"], None), + // Through a property the coordinate's names, or partly literal. + case( + "${vendor}org.slf4j", + &by_group, + &["org.other"], + None, + ), + case( + "slf4j", + &direct("org.${v}", "${v}-api"), + &["log4j"], + None, + ), + // A value this pom cannot resolve, or a cycle. + case(g, &by_group, &["${undefined}"], None), + case(g, &by_group, &["${g}"], None), + // Two profiles that move it only together. + case( + "org.slf4jorg.slf4j", + &by_group, + &["${w}", "org.other"], + None, + ), + // A user property in the chain does not fix a name above it. + case( + "${vendor}", + &by_group, + &["org.other"], + Some("-Dvendor=org.slf4j\n"), + ), + ]; + for c in &withheld { + assert_coordinate_case(c, false).await; + } + let attested = [ + // The same GA, or an unrelated property. + case(g, &by_group, &["org.slf4j"], None), + case(g, &by_group, &["org.other"], None), + // A user property wins over every profile's. + case(g, &by_group, &["org.other"], Some("-Dg=org.slf4j\n")), + case( + "${vendor}org.other", + &by_group, + &["org.another"], + Some("-Dvendor=org.slf4j\n"), + ), + ]; + for c in &attested { + assert_coordinate_case(c, true).await; + } + } + + /// Another declaration whose `${property}` coordinates name another + /// package while no profile is active but slf4j-api once a profile's + /// `` redefine them overrides the pin with its own version + /// whenever that profile is active. So does one inside a profile whose + /// own `` make it slf4j-api. + #[tokio::test] + async fn profile_properties_turning_a_declaration_into_the_pinned_ga_are_not_attested() { + let pin = suffixed(UUID_A); + let pinned = dep("org.slf4j", "slf4j-api", Some(&pin)); + let with = |other: &str| format!("\n{pinned}{other}\n"); + let other = |v: Option<&str>| dep("${h}", "slf4j-api", v); + let classified = |c: &str, v: Option<&str>| { + let v = v.map_or(String::new(), |v| format!("{v}")); + format!( + "${{h}}slf4j-api{v}\ + {c}\n" + ) + }; + let h = "org.other"; + let to_slf4j = in_props("org.slf4j"); + let case = |props: &str, decl: String, profiles: Vec, config: Option<&str>| { + ( + props.to_string(), + decl, + profiles, + config.map(str::to_string), + ) + }; + let withheld = [ + // The base release, or another one. + case( + h, + with(&other(Some("1.7.36"))), + vec![to_slf4j.clone()], + None, + ), + case( + h, + with(&other(Some("1.7.30"))), + vec![to_slf4j.clone()], + None, + ), + // Managed. + case( + h, + format!( + "\n{pinned}\n\ + \n{}\n", + other(Some("1.7.36")) + ), + vec![to_slf4j.clone()], + None, + ), + // A version the same profile moves too. + case( + &format!("{h}2.0.0"), + with(&other(Some("${v}"))), + vec![in_props("org.slf4j1.7.36")], + None, + ), + // A value the pom cannot resolve may be slf4j-api. + case( + h, + with(&other(Some("1.7.36"))), + vec![in_props("${undefined}")], + None, + ), + // An executable classifier copy, with or without a version. + case( + h, + with(&classified("tests", Some("1.7.36"))), + vec![to_slf4j.clone()], + None, + ), + case( + h, + with(&classified("tests", None)), + vec![to_slf4j.clone()], + None, + ), + // A profile declaration its own profile's properties retarget. + case( + h, + with(""), + vec![format!( + "{to_slf4j}\n{}\n", + other(Some("1.7.36")) + )], + None, + ), + // Through a user property lower in the chain. + case( + "${corp}", + with(&other(Some("1.7.36"))), + vec![to_slf4j.clone()], + Some("-Dcorp=org.other\n"), + ), + ]; + for c in &withheld { + assert_coordinate_case(c, false).await; + } + let attested = [ + // No version of its own: the live pin applies. + case(h, with(&other(None)), vec![to_slf4j.clone()], None), + // A non-executable classifier copy, or another type. + case( + h, + with(&classified("sources", Some("1.7.36"))), + vec![to_slf4j.clone()], + None, + ), + case( + h, + with( + "${h}slf4j-api\ + 1.7.36pom\n", + ), + vec![to_slf4j.clone()], + None, + ), + // A user property wins over every profile's. + case( + h, + with(&other(Some("1.7.36"))), + vec![to_slf4j.clone()], + Some("-Dh=org.other\n"), + ), + ]; + for c in &attested { + assert_coordinate_case(c, true).await; + } + } + + /// Coordinate properties that cannot make any declaration the pinned + /// GA, or move the pin off it, withhold nothing: a profile moving an + /// unrelated package to another unrelated one, a partly undefined + /// coordinate no profile touches, and a profile property no coordinate + /// names. + #[tokio::test] + async fn unrelated_coordinate_properties_do_not_withhold() { + let pin = suffixed(UUID_A); + let pinned = dep("org.slf4j", "slf4j-api", Some(&pin)); + let with = |other: &str| format!("\n{pinned}{other}\n"); + let none: Option = None; + for case in [ + ( + "org.other".to_string(), + with(&dep("${h}", "slf4j-api", Some("1.7.36"))), + vec![in_props("org.third")], + none.clone(), + ), + ( + "org.other".to_string(), + with(&dep("org.slf4j", "${h}", Some("1.7.36"))), + vec![in_props("slf4j-simple")], + none.clone(), + ), + ( + "com.corp".to_string(), + with(&dep("${h}.${undefined}", "slf4j-api", Some("1.7.36"))), + vec![in_props("1")], + none.clone(), + ), + ( + "org.other1".to_string(), + with(&dep("${h}", "slf4j-api", Some("1.7.36"))), + vec![in_props("2")], + none.clone(), + ), + ( + "org.slf4j".to_string(), + format!( + "\n{}\n", + dep("${g}", "slf4j-api", Some(&pin)) + ), + vec![in_props("org.other")], + none.clone(), + ), + ] { + assert_coordinate_case(&case, true).await; + } + } + /// A `${property}` version resolves through every property it names, /// with user properties first at each level, as Maven interpolates; a /// cycle, or a chain deeper than the vendored reactor follows, is