Skip to content

Commit 22544e7

Browse files
committed
Bound test-only list items in the source scan; gate composer refusal
Second review round. - The production-source scan's `item_end` only stopped at a depth-0 `;` or the end of the first depth-0 block, so a `#[cfg(test)]` struct field, enum variant, match arm or parameter blanked code far past itself (a whole following `impl`), hiding production references from the no-lock-download and BOM guards. An item now ends at its `,` (with generic `<...>` counted so `Result<(), ()>` does not end it) or at the bracket enclosing it. - `code_only` failed open (an empty file) on a UTF-8 slip; it panics now, like `strip_test_items`. - The module docs no longer claim the file an out-of-line test module points at is dropped. - `vendor --revert` of a composer entry refused over any unparseable composer.lock. It still refuses when the lock names the entry's uuid, but a broken lock that never mentions it cannot route composer at the uuid dir and no longer blocks the revert. - The BOM memo test re-seeds with two BOMs before asserting nothing was stored; the CLI guard sorts its expected list. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 75b6ca3 commit 22544e7

3 files changed

Lines changed: 103 additions & 15 deletions

File tree

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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8197,10 +8197,11 @@ mod lock_download_guard_tests {
81978197
}
81988198
}
81998199
found.sort();
8200-
let expected: Vec<(String, &str, String)> = PINNED_REFERENCES
8200+
let mut expected: Vec<(String, &str, String)> = PINNED_REFERENCES
82018201
.iter()
82028202
.map(|(rel, name, line)| (rel.to_string(), *name, line.to_string()))
82038203
.collect();
8204+
expected.sort();
82048205
assert_eq!(
82058206
found, expected,
82068207
"a production reference to `recover_lock_entry` was added, removed or changed. \

‎crates/socket-patch-core/src/vendor/composer_lock.rs‎

Lines changed: 49 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -890,9 +890,20 @@ async fn stranded_wired_packages(
890890
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
891891
Err(e) => return Err(format!("composer.lock is unreadable ({e})")),
892892
};
893-
let lock = LOCK_MEMO
894-
.parse(text.as_bytes(), || parse_json_text(&text))
895-
.map_err(|e| format!("composer.lock is not valid JSON ({e})"))?;
893+
let lock = match LOCK_MEMO.parse(text.as_bytes(), || parse_json_text(&text)) {
894+
Ok(lock) => lock,
895+
// A lock that never names the uuid (in any spelling: the uuid has
896+
// no `/` to escape) cannot point composer at its directory, so a
897+
// broken lock elsewhere does not block this revert.
898+
Err(_)
899+
if !text
900+
.to_ascii_lowercase()
901+
.contains(&uuid.to_ascii_lowercase()) =>
902+
{
903+
return Ok(Vec::new())
904+
}
905+
Err(e) => return Err(format!("composer.lock is not valid JSON ({e})")),
906+
};
896907
Ok(stranded_in(&lock, uuid, restorable))
897908
}
898909

@@ -1912,7 +1923,12 @@ mod tests {
19121923
let bom = with_bom(&render);
19131924
reseed_memo(&memo, bom.clone(), lock.clone());
19141925
assert_eq!(memo.get(&bom).as_deref(), Some(&lock));
1915-
assert!(memo.get(&with_bom(&bom)).is_none());
1926+
// Only one BOM is stripped: two are not the render, so re-seeding
1927+
// with them stores nothing (and drops the stale slot).
1928+
let double = with_bom(&bom);
1929+
reseed_memo(&memo, double.clone(), lock.clone());
1930+
assert!(memo.get(&double).is_none());
1931+
assert!(memo.get(&bom).is_none());
19161932
}
19171933

19181934
/// Vendor then `--revert` on `lock_bytes`, asserting the revert
@@ -3295,12 +3311,20 @@ mod tests {
32953311
.await
32963312
.unwrap()
32973313
.is_empty());
3298-
// Unparseable lock: fail closed (what it wires cannot be read).
3299-
tokio::fs::write(&lock_path, b"not json").await.unwrap();
3314+
// Unparseable lock naming the uuid: fail closed (what it wires
3315+
// cannot be read). One that never names it wires nothing of it.
3316+
tokio::fs::write(&lock_path, format!("not json {UUID}"))
3317+
.await
3318+
.unwrap();
33003319
let err = stranded_wired_packages(&lock_path, UUID, &none)
33013320
.await
33023321
.unwrap_err();
33033322
assert!(err.contains("not valid JSON"), "{err}");
3323+
tokio::fs::write(&lock_path, b"not json").await.unwrap();
3324+
assert!(stranded_wired_packages(&lock_path, UUID, &none)
3325+
.await
3326+
.unwrap()
3327+
.is_empty());
33043328
// No package sections at all.
33053329
tokio::fs::write(
33063330
&lock_path,
@@ -4526,5 +4550,24 @@ mod tests {
45264550
conflicted,
45274551
"lock untouched"
45284552
);
4553+
4554+
// A broken lock that never names the uuid cannot point composer at
4555+
// its directory: it does not block the revert.
4556+
let unrelated = format!(
4557+
"<<<<<<< HEAD\n{text}=======\n{}>>>>>>> theirs\n",
4558+
text.replace('/', "\\/")
4559+
);
4560+
tokio::fs::write(root.join(COMPOSER_LOCK), &unrelated)
4561+
.await
4562+
.unwrap();
4563+
let outcome = revert_composer(&entry, root, true).await;
4564+
assert!(
4565+
!outcome
4566+
.error
4567+
.as_deref()
4568+
.is_some_and(|e| e.contains("not valid JSON")),
4569+
"{:?}",
4570+
outcome.error
4571+
);
45294572
}
45304573
}

‎crates/socket-patch-core/src/vendor/test_support/production_sources.rs‎

Lines changed: 52 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,13 @@
44
//!
55
//! "Production" is every `.rs` file under `src/` except the test-only
66
//! files (`*tests.rs`, `test_support`), with every test-only item removed:
7-
//! an item behind `#[cfg(test)]` or `#[cfg(all(test, …))]` (a test module,
8-
//! inline or `mod x;`, a test helper, a test `use`), and the whole file
9-
//! when it opens with `#![cfg(test)]`. Items are removed in place, never by
7+
//! an item behind `#[cfg(test)]` or `#[cfg(all(test, …))]` (an inline test
8+
//! module or a `mod x;` declaration, a test helper, a test `use`, a field,
9+
//! variant, arm or parameter), and the whole file when it opens with
10+
//! `#![cfg(test)]`. The FILE an out-of-line test module (`#[cfg(test)] mod
11+
//! x;`) points at is still read unless its name ends in `tests.rs`, so a
12+
//! test-only file (the crawlers' `oracle.rs`) must not hold what a guard
13+
//! forbids, or must open with `#![cfg(test)]`. Items are removed in place, never by
1014
//! truncating at the first `#[cfg(test)]`, so production code after a test
1115
//! item is still scanned. Line endings are normalized to LF, and removed
1216
//! bytes become spaces (newlines kept), so line numbers stay the file's.
@@ -208,22 +212,40 @@ fn matching_close(b: &[u8], kind: &[Kind], open: usize) -> usize {
208212

209213
/// End (exclusive) of the item starting at `start`: its first `;` outside
210214
/// brackets, or its first top-level `{…}` block (plus a `;` right after).
215+
/// An item never reaches past the bracket that encloses it, and one in a
216+
/// comma list (a struct field, an enum variant, a match arm, a parameter)
217+
/// ends at its `,`. Generic `<…>` count as brackets for that comma (a
218+
/// `<` or `>` hugged by code on both sides, `->` and `=>` excepted), so
219+
/// `Result<(), ()>` or `HashMap<K, V>` do not end it.
211220
fn item_end(b: &[u8], kind: &[Kind], start: usize) -> usize {
212221
let mut depth = 0usize;
222+
let mut angle = 0usize;
213223
let mut j = start;
224+
let code = |i: usize| kind.get(i) == Some(&Kind::Code);
214225
while j < b.len() {
215-
if kind[j] == Kind::Code {
226+
if code(j) {
216227
match b[j] {
217228
b'(' | b'[' => depth += 1,
218-
b')' | b']' => depth = depth.saturating_sub(1),
229+
b')' | b']' | b'}' if depth == 0 => return j,
230+
b')' | b']' => depth -= 1,
231+
b'<' if j > 0
232+
&& code(j - 1)
233+
&& !b[j - 1].is_ascii_whitespace()
234+
&& b.get(j + 1)
235+
.is_some_and(|c| !c.is_ascii_whitespace() && *c != b'=') =>
236+
{
237+
angle += 1
238+
}
239+
b'>' if angle > 0 && j > 0 && !matches!(b[j - 1], b'-' | b'=') => angle -= 1,
240+
b',' if depth == 0 && angle == 0 => return j + 1,
219241
b';' if depth == 0 => return j + 1,
220242
b'{' if depth == 0 => {
221243
let close = matching_close(b, kind, j);
222244
let mut k = close + 1;
223245
while k < b.len() && b[k].is_ascii_whitespace() {
224246
k += 1;
225247
}
226-
return if b.get(k) == Some(&b';') {
248+
return if b.get(k) == Some(&b';') || b.get(k) == Some(&b',') {
227249
k + 1
228250
} else {
229251
close + 1
@@ -313,8 +335,9 @@ pub fn code_only(src: &str) -> String {
313335
_ => b' ',
314336
})
315337
.collect();
316-
// Non-code bytes became ASCII; code bytes are whole chars.
317-
String::from_utf8(out).unwrap_or_default()
338+
// Non-code bytes became ASCII; code bytes are whole chars. A slip must
339+
// fail the guard loudly, never hand it an empty (reference-free) file.
340+
String::from_utf8(out).expect("blanking keeps UTF-8")
318341
}
319342

320343
/// Every reference to the identifier `name` in `code` (from
@@ -372,6 +395,27 @@ mod tests {
372395
);
373396
}
374397

398+
/// A test-only field, variant, arm or parameter ends at its `,` or at
399+
/// the bracket that encloses it, never at the next item's block.
400+
#[test]
401+
fn list_items_end_at_their_comma_or_closer() {
402+
let src = "struct S {\n #[cfg(test)]\n probe: u32,\n}\nimpl S { fn get(&self) { kept_a(); } }\n\
403+
struct T {\n #[cfg(test)]\n m: HashMap<K, V>,\n keep: u8,\n}\n\
404+
enum E {\n #[cfg(test)]\n Probe(u8),\n Real,\n}\n\
405+
fn f(#[cfg(test)] x: u8, y: u8) { kept_b(); }\n\
406+
#[cfg(test)]\nfn r() -> Result<(), ()> { gone(); }\nfn after() { kept_c(); }\n\
407+
fn m(v: u8) { match v {\n #[cfg(test)]\n 0 => gone2(),\n _ => kept_d(),\n } }\n";
408+
let out = strip_test_items(src);
409+
for kept in [
410+
"kept_a", "keep: u8", "Real", "y: u8", "kept_b", "kept_c", "kept_d",
411+
] {
412+
assert!(out.contains(kept), "{kept}: {out}");
413+
}
414+
for dropped in ["probe", "HashMap", "Probe", "x: u8", "gone()", "gone2"] {
415+
assert!(!out.contains(dropped), "{dropped}: {out}");
416+
}
417+
}
418+
375419
#[test]
376420
fn literals_and_comments_do_not_confuse_the_scan() {
377421
let src = "#[cfg(test)]\nfn t() { let r = r#\"{ \"#; let c = '{'; /* { */ // {\n }\nfn p<'a>(x: &'a str) {}\n";

0 commit comments

Comments
 (0)