Skip to content

Commit e98fa25

Browse files
committed
Merge origin/main into fix/maven-discovery-false-attestation
Adopt #2006's shared Maven variant rule (is_variant / variant_label / is_main_jar / is_executable_variant) in VEX discovery: live_gas and main_jar_declarations exclude every variant (a classifier or a code-carrying type such as test-jar), classifier_declarations reports executable variants by their label, and variant management is keyed by classifier and type. The PR's behavior stays on top: profile declarations (MavenProfileUnpatched, now gated on is_main_jar), .mvn/maven.config overrides (MavenConfigOverride) and pre-v5 vendored classifier coverage. A test-jar typed profile declaration is therefore reported as a classifier copy, not a profile override. Main's unpatched_executable_classifier / group_by_ga are superseded by the PR's helpers; the redirect rewriter takes main's version. Keep both sides' VEX notes and enum variants (Maven profile / config overrides and #2007's vex_nuget_lock_other_version), and in CLI_CONTRACT.md count eight unattested cases besides Gradle's and NuGet's, with both tables' rows. Co-Authored-By: Claude <noreply@anthropic.com>
2 parents a6b3ab0 + f217f54 commit e98fa25

24 files changed

Lines changed: 2839 additions & 299 deletions

File tree

‎crates/socket-patch-cli/CLI_CONTRACT.md‎

Lines changed: 12 additions & 3 deletions
Large diffs are not rendered by default.

‎crates/socket-patch-cli/src/commands/composer_hints.rs‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,8 +46,10 @@ const VENDOR_PREFIX: &str = ".socket/vendor/composer/";
4646

4747
/// The `<vendor>/<name>` of every composer.lock package (`packages` and
4848
/// `packages-dev`) whose dist is a vendored `path` copy, sorted and
49-
/// de-duplicated. An unparseable lock yields nothing.
49+
/// de-duplicated. An unparseable lock yields nothing; one leading BOM is
50+
/// read past, as the vendored backend reads the lock.
5051
pub(crate) fn vendored_composer_packages(lock_text: &str) -> Vec<String> {
52+
let lock_text = socket_patch_core::formats::text::strip_bom(lock_text);
5153
let Ok(lock) = serde_json::from_str::<Value>(lock_text) else {
5254
return Vec::new();
5355
};
@@ -182,6 +184,13 @@ mod tests {
182184
);
183185
assert!(vendored_composer_packages("not json").is_empty());
184186
assert!(vendored_composer_packages("{}").is_empty());
187+
// One leading BOM is encoding (the backend reads past it); a second
188+
// is content.
189+
assert_eq!(
190+
vendored_composer_packages(&format!("\u{feff}{}", lock())),
191+
vendored_composer_packages(&lock())
192+
);
193+
assert!(vendored_composer_packages(&format!("\u{feff}\u{feff}{}", lock())).is_empty());
185194
}
186195

187196
#[test]

‎crates/socket-patch-cli/src/commands/scan/mod.rs‎

Lines changed: 121 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1070,15 +1070,18 @@ pub(super) async fn classify_overlap_takeover_with(
10701070
Some(uuid) => liveness.redirect_record(&purl, uuid).await,
10711071
None => discovery.wires_package(&purl, WiringMode::Hosted),
10721072
};
1073+
// `None`: undecided (a JVM pom that cannot be read, or a tree still
1074+
// referenced without attestable wiring) — neither live nor dead.
10731075
let vendored_live = match vendor_by_purl.get(&PurlKey::new(&purl)) {
1074-
Some(entry) => liveness.vendor_entry(entry).await,
1075-
None => false,
1076+
Some(entry) => liveness.vendor_entry_state(entry).await,
1077+
None => Some(false),
10761078
};
10771079
match (hosted_live, vendored_live) {
1078-
(true, false) => out.redirect.push(purl),
1079-
(false, true) => out.vendored.push(purl),
1080-
// Both (a half-migrated lock naming both) or neither (no rewire /
1081-
// unreadable) does not prove a single direction — stay silent.
1080+
(true, Some(false)) => out.redirect.push(purl),
1081+
(false, Some(true)) => out.vendored.push(purl),
1082+
// Both (a half-migrated lock naming both), neither (no rewire)
1083+
// or an undecided vendored side (unreadable) does not prove a
1084+
// single direction — stay silent.
10821085
_ => {}
10831086
}
10841087
}
@@ -4671,6 +4674,118 @@ mod tests {
46714674
);
46724675
}
46734676

4677+
// ---- maven: an undecided vendored claim is not a dead one -------------
4678+
4679+
const MAVEN_PURL: &str = "pkg:maven/org.slf4j/slf4j-api@1.7.36";
4680+
/// The vendored patch: another uuid than the hosted pin's, so its
4681+
/// suffixed version tells the two wirings apart.
4682+
const MAVEN_VENDORED_UUID: &str = "5c0ffee0-1d3a-4f6b-8c2d-7e5a9b1c3d5f";
4683+
4684+
fn maven_dep(version: &str) -> String {
4685+
format!(
4686+
"<dependency><groupId>org.slf4j</groupId><artifactId>slf4j-api</artifactId>\
4687+
<version>{version}</version></dependency>"
4688+
)
4689+
}
4690+
4691+
/// A root pom pinning slf4j-api to the hosted [`TAKEOVER_UUID`] patch,
4692+
/// with `extra` (a `<build>` section) inside the project.
4693+
async fn write_maven_hosted_pom(root: &Path, extra: &str) {
4694+
let pom = format!(
4695+
"<?xml version=\"1.0\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\">\n \
4696+
<modelVersion>4.0.0</modelVersion>\n <groupId>com.example</groupId>\n \
4697+
<artifactId>app</artifactId>\n <version>1.0.0</version>\n \
4698+
<dependencies>\n {}\n </dependencies>\n <repositories>\n <repository>\n \
4699+
<id>socket-patch-{TAKEOVER_UUID}</id>\n \
4700+
<url>https://patch.socket.dev/patch-registry/maven/11111111-2222-4333-8444-555555555555/{TAKEOVER_UUID}/maven2</url>\n \
4701+
<releases>\n <enabled>true</enabled>\n \
4702+
<checksumPolicy>fail</checksumPolicy>\n </releases>\n </repository>\n \
4703+
</repositories>\n {extra}\n</project>\n",
4704+
maven_dep(&format!("1.7.36-socket.{}", &TAKEOVER_UUID[..8])),
4705+
);
4706+
tokio::fs::write(root.join("pom.xml"), pom).await.unwrap();
4707+
}
4708+
4709+
/// A vendored ledger whose one entry is a Maven reactor vendoring of
4710+
/// slf4j-api at [`MAVEN_VENDORED_UUID`].
4711+
async fn write_maven_vendor_ledger(root: &Path) {
4712+
let sv = format!("1.7.36-socket.{}", &MAVEN_VENDORED_UUID[..8]);
4713+
let state = serde_json::json!({
4714+
"version": 1,
4715+
"entries": {
4716+
MAVEN_PURL: {
4717+
"ecosystem": "maven",
4718+
"basePurl": MAVEN_PURL,
4719+
"uuid": MAVEN_VENDORED_UUID,
4720+
"artifact": {
4721+
"path": format!(
4722+
".socket/vendor/maven2/org/slf4j/slf4j-api/{sv}/slf4j-api-{sv}.jar"
4723+
),
4724+
},
4725+
"wiring": [{
4726+
"file": "pom.xml",
4727+
"kind": "maven_pom_fragment",
4728+
"action": "added",
4729+
}],
4730+
},
4731+
},
4732+
});
4733+
let dir = root.join(".socket/vendor");
4734+
tokio::fs::create_dir_all(&dir).await.unwrap();
4735+
tokio::fs::write(
4736+
dir.join("state.json"),
4737+
serde_json::to_string_pretty(&state).unwrap(),
4738+
)
4739+
.await
4740+
.unwrap();
4741+
}
4742+
4743+
/// A vendored Maven claim the reader cannot decide — a project file it
4744+
/// cannot read, or the vendored version left only where the build may
4745+
/// still resolve it from the tree (a build plugin's dependencies) —
4746+
/// is neither live nor dead: the `scan --prune` GC keeps it, so the
4747+
/// takeover classifier must not report it superseded (and tell the
4748+
/// user to remove it). Only a claim nothing references any more is.
4749+
#[tokio::test]
4750+
async fn maven_takeover_stays_silent_on_an_undecided_vendored_claim() {
4751+
let vendored = format!("1.7.36-socket.{}", &MAVEN_VENDORED_UUID[..8]);
4752+
let plugin = format!(
4753+
"<build><plugins><plugin><groupId>p</groupId><artifactId>p</artifactId>\
4754+
<dependencies>{}</dependencies></plugin></plugins></build>",
4755+
maven_dep(&vendored)
4756+
);
4757+
// Control: nothing references the vendored version — superseded.
4758+
let tmp = tempfile::tempdir().unwrap();
4759+
let root = tmp.path();
4760+
write_maven_vendor_ledger(root).await;
4761+
write_maven_hosted_pom(root, "").await;
4762+
let takeover = classify_overlap_takeover(&common_at(root), root).await;
4763+
assert_eq!(
4764+
takeover.redirect,
4765+
vec![MAVEN_PURL.to_string()],
4766+
"{takeover:?}"
4767+
);
4768+
4769+
// Left only in a build plugin's dependencies.
4770+
let tmp = tempfile::tempdir().unwrap();
4771+
let root = tmp.path();
4772+
write_maven_vendor_ledger(root).await;
4773+
write_maven_hosted_pom(root, &plugin).await;
4774+
let takeover = classify_overlap_takeover(&common_at(root), root).await;
4775+
assert_eq!(takeover, OverlapTakeover::default());
4776+
4777+
// A Maven config the reader cannot read (a directory).
4778+
let tmp = tempfile::tempdir().unwrap();
4779+
let root = tmp.path();
4780+
write_maven_vendor_ledger(root).await;
4781+
write_maven_hosted_pom(root, "").await;
4782+
tokio::fs::create_dir_all(root.join(".mvn/maven.config"))
4783+
.await
4784+
.unwrap();
4785+
let takeover = classify_overlap_takeover(&common_at(root), root).await;
4786+
assert_eq!(takeover, OverlapTakeover::default());
4787+
}
4788+
46744789
// ---- takeover DIRECTION follows the live lock, not the command ---------
46754790

46764791
/// Like [`write_vendor_ledger`] but each entry records wiring the

‎crates/socket-patch-cli/src/commands/vendor.rs‎

Lines changed: 65 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -174,10 +174,14 @@ async fn keep_older_vendored_patch(
174174
};
175175
if let Some(kept) = lookup_entry(&state.entries, purl).filter(|e| e.uuid != uuid) {
176176
let root = common.project_root();
177+
// Still in force, not attestable: a JVM tree that is still wired
178+
// or referenced (an executable classifier copy beside it, say) is
179+
// kept; only a provably dead one gives way.
177180
if crate::commands::discover_wiring(common, &root)
178181
.await
179-
.vendor_entry_live(&root, kept)
182+
.vendor_entry_liveness(&root, kept)
180183
.await
184+
!= Some(false)
181185
{
182186
return Some(VendorOutcome::Refused {
183187
code,
@@ -1334,7 +1338,18 @@ async fn run_check(args: &VendorArgs) -> i32 {
13341338
None => Some("patch record missing; restore the manifest or vendor ledger".to_string()),
13351339
};
13361340
if failure.is_none() && vendor::jvm::apply::is_jvm_entry(entry) {
1337-
failure = vendor::jvm::apply::check_entry(root, entry, local_repo.as_deref()).err();
1341+
match vendor::jvm::apply::check_entry(root, entry, local_repo.as_deref()) {
1342+
Ok(None) => {}
1343+
// Intact and wired, but `vex` will not attest it: a
1344+
// declaration may still build the base. Re-vendoring cannot
1345+
// clear that, so it warns rather than fails (the unattested
1346+
// references rule).
1347+
Ok(Some(why)) => env.warnings.push(RunWarning {
1348+
code: "vendor_jvm_unattested".into(),
1349+
detail: format!("{key}: {why}; vex does not attest it"),
1350+
}),
1351+
Err(e) => failure = Some(e),
1352+
}
13381353
}
13391354
// The npm check names the exact unwired lock entry, so it runs
13401355
// before the generic liveness rule below.
@@ -8153,3 +8168,51 @@ mod unused_vendored_manifest_keys_tests {
81538168
);
81548169
}
81558170
}
8171+
8172+
/// The CLI side of core's `lock_pinned_locations_never_drive_a_download`
8173+
/// (see its docs for what the check does and does not catch). Core's
8174+
/// registry downloads (`registry_fetch::download`,
8175+
/// `maven_repo::fetch_registry_bytes`) are `pub(crate)`, so the compiler
8176+
/// already keeps the CLI from calling them (a by-name scan here would
8177+
/// only meet the CLI's own `download` locals). What is pinned is the
8178+
/// public `recover_lock_entry`: the CLI has no reference to it (its one
8179+
/// production caller is core's `vendor::refusals::pristine_fetch_is_verifiable`
8180+
/// yes/no gate), so any new CLI reference fails here.
8181+
#[cfg(test)]
8182+
mod lock_download_guard_tests {
8183+
use socket_patch_core::vendor::test_support::production_sources::{
8184+
production_sources, references,
8185+
};
8186+
8187+
const PINNED_REFERENCES: &[(&str, &str, &str)] = &[];
8188+
8189+
#[test]
8190+
fn lock_pinned_locations_never_drive_a_download() {
8191+
let src = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
8192+
let mut found: Vec<(String, &str, String)> = Vec::new();
8193+
for file in production_sources(&src) {
8194+
let code = file.code();
8195+
let lines: Vec<&str> = file.text.lines().collect();
8196+
for (line, _) in references(&code, "recover_lock_entry") {
8197+
found.push((
8198+
file.rel.clone(),
8199+
"recover_lock_entry",
8200+
lines[line - 1].trim().to_string(),
8201+
));
8202+
}
8203+
}
8204+
found.sort();
8205+
let mut expected: Vec<(String, &str, String)> = PINNED_REFERENCES
8206+
.iter()
8207+
.map(|(rel, name, line)| (rel.to_string(), *name, line.to_string()))
8208+
.collect();
8209+
expected.sort();
8210+
assert_eq!(
8211+
found, expected,
8212+
"a production reference to `recover_lock_entry` was added, removed or changed. \
8213+
Its recovered `resolved`/`integrity` may be a Socket-hosted (patched) artifact's: \
8214+
never download them as a pristine source; re-check the site, then update \
8215+
PINNED_REFERENCES"
8216+
);
8217+
}
8218+
}

‎crates/socket-patch-cli/src/commands/vex_sources.rs‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -240,6 +240,10 @@ const NOTE_MAVEN_PROFILE_UNPATCHED: &str = "vex_maven_profile_unpatched";
240240
/// through a `${property}` that `.mvn/maven.config` redefines, so the build resolves
241241
/// another version (`vex::Unattested`).
242242
const NOTE_MAVEN_CONFIG_OVERRIDE: &str = "vex_maven_config_override";
243+
/// Omission tag and note: a NuGet Socket source's id is also locked at a
244+
/// version other than the patched one, which that source cannot serve
245+
/// (`vex::Unattested`).
246+
const NOTE_NUGET_LOCK_OTHER_VERSION: &str = "vex_nuget_lock_other_version";
243247
/// Omission tag and note: a hosted sbt pin whose bytes the build provably
244248
/// does not use (a `dependencyOverrides` reassignment, an `onLoad` one
245249
/// dropping the load-time verifier, or current evidence
@@ -300,6 +304,11 @@ fn unattested_note(kind: UnattestedKind) -> (&'static str, &'static str) {
300304
through; the wiring itself is intact, so re-running `scan` does not change this \
301305
(drop that -D from .mvn/maven.config, or write the pinned version literally)",
302306
),
307+
UnattestedKind::NugetLockOtherVersion => (
308+
NOTE_NUGET_LOCK_OTHER_VERSION,
309+
"not attested until every target framework locks only the patched version (align \
310+
them on it, restore, and re-run `scan` / `vendor`)",
311+
),
303312
UnattestedKind::SbtPinBypassed => (
304313
NOTE_SBT_PIN_BYPASSED,
305314
"not attested while the build bypasses the pin, even from the copy under \

‎crates/socket-patch-core/src/crawlers/composer_crawler.rs‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,7 @@ impl InstallerLayout {
102102
let root = crate::utils::fs::read_regular_to_string(&project_root.join("composer.json"))
103103
.await
104104
.ok()
105-
.and_then(|content| serde_json::from_str::<serde_json::Value>(&content).ok());
105+
.and_then(|content| crate::vendor::common::parse_json_text(&content).ok());
106106
let extra = root.as_ref().and_then(|r| r.get("extra"));
107107
Self {
108108
active: true,
@@ -630,7 +630,7 @@ const PROJECT_ROOT_SEARCH_DEPTH: usize = 3;
630630
/// value counts as unset. Placeholder expansion is the caller's call, see
631631
/// [`resolve_vendor_dir`].
632632
fn parse_config_vendor_dir(composer_json: &str) -> Option<String> {
633-
let doc: serde_json::Value = serde_json::from_str(composer_json).ok()?;
633+
let doc: serde_json::Value = crate::vendor::common::parse_json_text(composer_json).ok()?;
634634
let raw = doc.get("config")?.get("vendor-dir")?.as_str()?;
635635
let trimmed = raw.trim_end_matches(['/', '\\']);
636636
(!trimmed.is_empty()).then(|| trimmed.to_string())
@@ -1964,6 +1964,14 @@ mod tests {
19641964
None
19651965
);
19661966
assert_eq!(parse_config_vendor_dir("{ not json"), None);
1967+
// One leading BOM is encoding; a second is content.
1968+
let bom = crate::formats::text::BOM;
1969+
let json = r#"{"config":{"vendor-dir":"lib/deps"}}"#;
1970+
assert_eq!(
1971+
parse_config_vendor_dir(&format!("{bom}{json}")).as_deref(),
1972+
Some("lib/deps")
1973+
);
1974+
assert_eq!(parse_config_vendor_dir(&format!("{bom}{bom}{json}")), None);
19671975
}
19681976

19691977
/// Composer's `Platform::expandPath`: only a LEADING `~/`, `$VAR` or

‎crates/socket-patch-core/src/formats/maven/mod.rs‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -605,6 +605,56 @@ fn is_model_reference(name: &str) -> bool {
605605
name.starts_with("project.") || name.starts_with("pom.")
606606
}
607607

608+
/// Whether a declaration of a GA is a sibling copy of its main jar that
609+
/// Maven resolves apart from it (and that the main-jar pin does not
610+
/// reach): a classifier, or a type other than `jar` / `pom`. The `<type>`
611+
/// a `${...}` leaves unknown counts. The hosted rewriter, VEX discovery and
612+
/// the vendored reactor share this rule with [`is_executable_variant`].
613+
pub(crate) fn is_variant(type_text: Option<&str>, classifier: Option<&str>) -> bool {
614+
classifier.is_some_and(|c| !c.is_empty())
615+
|| type_text.is_some_and(|t| !t.is_empty() && t != "jar" && t != "pom")
616+
}
617+
618+
/// The label a variant ([`is_variant`]) is reported by: its classifier,
619+
/// else its type.
620+
pub(crate) fn variant_label<'a>(
621+
type_text: Option<&'a str>,
622+
classifier: Option<&'a str>,
623+
) -> &'a str {
624+
classifier
625+
.filter(|c| !c.is_empty())
626+
.or(type_text)
627+
.unwrap_or_default()
628+
}
629+
630+
/// Whether a declaration of a GA's main jar: untyped or `jar`-typed, with
631+
/// no classifier.
632+
pub(crate) fn is_main_jar(type_text: Option<&str>, classifier: Option<&str>) -> bool {
633+
type_text.is_none_or(|t| t.is_empty() || t == "jar") && classifier.is_none_or(str::is_empty)
634+
}
635+
636+
/// Whether a declaration of a GA that is not its main jar
637+
/// ([`is_main_jar`]) is a copy that carries code onto a classpath. Maven
638+
/// derives a classifier from some types (`test-jar` is the `tests` jar,
639+
/// `ejb-client` the `client` one, `java-source` / `javadoc` the
640+
/// non-executable ones), so a type counts like the classifier it implies.
641+
/// Of the rest only `pom` holds no code; every other type (`ejb`,
642+
/// `maven-plugin`, `bundle`, an unknown or `${...}` one) is executable.
643+
pub(crate) fn is_executable_variant(type_text: Option<&str>, classifier: Option<&str>) -> bool {
644+
let type_text = type_text.filter(|t| !t.is_empty()).unwrap_or("jar");
645+
let implied = match type_text {
646+
"test-jar" => Some("tests"),
647+
"ejb-client" => Some("client"),
648+
"java-source" => Some("sources"),
649+
"javadoc" => Some("javadoc"),
650+
_ => None,
651+
};
652+
match classifier.filter(|c| !c.is_empty()).or(implied) {
653+
Some(c) => is_executable_classifier(c),
654+
None => type_text != "pom",
655+
}
656+
}
657+
608658
fn is_property_name(name: &str) -> bool {
609659
!name.is_empty()
610660
&& name

0 commit comments

Comments
 (0)