Repository navigation
fix(macro-names): close four macro-defined owner shadow gaps (#8467) - #8516
Conversation
…se imports and nested macro groups (#8467) Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01JPWmsSED95rEHERuRACDEp
|
Warning You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again! |
|
Warning Review limit reachedEnable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
Reviews can continue after your included limit without a manual trigger. An admin must approve usage-based billing. Next included review available in 39 minutes. View limit details
Comment |
There was a problem hiding this comment.
Verification questions
- Confirm new test a_passthrough_local_macro_defines_the_item_its_caller_spells asserts against a $i:item macro that captures 'fn name' via declares_item_named path, mixing the two new detection routes; architecture risk only if reviewer assumes each test covers one route.
- Confirm crates/ripr/src/analysis/classify/macro_item_names.rs:141 — In
passes_name_as_bare_argument,top_level.trim_end().ends_with('!')only catches macros whose name ends exactly at top_level; an outer callouter!(a, inner!(name))was the new positive control, butouter!(inner!{name})(braces) relies on the ! adjacency afterinner, which trims whitespace but not an immediately-preceding identifier char. Re-verifyouter!(inner!{name})returns true. - Confirm sibling callers of macro_may_define_item_named in other classify modules are not in this diff's blast radius but were not enumerated here; the lane cannot claim no other route depends on the prior 'depth-0 characters' behavior.
- Confirm negative control breadth is thin for
fn namein external-macro args (only call/method/other-name/x:: controls); missing macro-path and tuple-group cases.
Refuted
- duplicate detection logic for 'use name;' / 'use other::name;' could live alongside existing keyword+name pair scan, creating two ways to detect the same case; refuted because: declares_item_named delegates to imports_name(name) which only matches the specific 'use ...;' patterns absent from the existing keyword-then-name pair loop; uses differ in form (statement-bound) vs. fn/struct pairs, no overlap.
- Could the new transparent-group tracking read OOB in
top_levelafter popping a non-transparent group?; refuted because: Push/pop parity preserved;top_level.push('(')only fires when collecting==true, so non-transparent inner groups never append. Subsequentif collecting => top_level.push(c)cannot observe a stale length from a closed group. - imports_name would false-positive on
use_other::name;or on a path likeuse crate::...; refuted because: word_edge guard on chars before/afteruserejectsuse_other, and the only path that would still match is the unlikelyusewhere surrounding char isn't alphanumeric/underscore; existing negative controlsuse other::thing;anduse name::leaf;pass. - A carefully crafted
usestatement with the target name appearing inside a string literal, attribute, or doc-comment could be misread by imports_name as a binding, causing a non-owning macro to falsely claim ownership.; refuted because: imports_name matchesnameonly with word-edges (non-identifier on both sides) and requires the next non-whitespace char after the name to be,,}, or end-of-statement; identifiers inside string literals/attributes would either break word-edges or be followed by an unexpected character, so they do not satisfy both constraints. - A transparent inner-macro group in
passes_name_as_bare_argumentcould leak parsed depth state across worker calls (UB via aliasing).; refuted because:top_levelandopen_groupsare localString/Vec<bool>constructed fresh each call; no static, thread-local, or shared storage; lexical scan is pure. - No ArrayBuffer/TypedArray/resizable buffer surface exists in Rust source; macro_item_names.rs only slices &str. UB category is inapplicable.
Evidence gaps
- Model proof intent was rejected by deterministic validation.
Parked follow-ups
- Weak test credit (PR finding 6) is parked; sibling paths scanned found no related helper that should be co-patched in this PR.
…ture check-allow-attributes counts allow(..) text inside fixture strings. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01JPWmsSED95rEHERuRACDEp
…ro groups Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01JPWmsSED95rEHERuRACDEp
There was a problem hiding this comment.
Confirmed findings
- forwards_arguments_verbatim treats any occurrence of
:ttor:itemin a macro_rules definition as sufficient evidence that caller-spelled items will be defined; this is an over-approximation that may produce false positives for macros that capture the fragment only to re-emit it in non-item positions (e.g. insideletbinders or proc-macro-shim calls). The route is fail-closed for the four partial-fix items in #8467 but is broader than the doc comment'sforwarded asclaim. A future tightening (require both:tt/:itemAND a top-level passthrough like$($t)*/$iin the LHS->RHS) would close the gap with negligible test churn. transparent = collecting && top_level.trim_end().ends_with('!')only catches a macro-bang if it is the immediately preceding non-whitespace character in top_level. A comment betweeninner!and a brace group (outer!(inner!/*x*/{name})) leaves top_level ending with the literal(, so the group is recorded opaque andnameis no longer visible as a top-level argument. The new positive controlouter!(inner!{ name });does not cover this; add a test or relax the rule to also accept(/[after!ignored by whitespace/comments. (crates/ripr/src/analysis/classify/macro_item_names.rs:147).- crates/ripr/src/analysis/classify/macro_item_names.rs:244 — Add
emit!(inner::name)andemit!((name, x))as negative controls for thefn namecase so theITEM_KEYWORDS.contains(trailing_identifier(before)) \|\| !after.starts_with('(')rule is regression-tested against macro-path and tuple-group variants. - Test
a_passthrough_local_macro_defines_the_item_its_caller_spellsmixes both detection routes (passes_name_as_bare_argument now seesfn namevia the ITEM_KEYWORDS escape, and the new declares_in_arguments/forwards_arguments_verbatim route). One targeted test per route would localize future regressions; the new routes are additive and individually exercised byan_item_spelled_in_external_macro_arguments_defines_the_nameanda_passthrough_local_macro_defines_the_item_its_caller_spellsrespectively, so this is a brittleness note, not a bug. - forwards_arguments_verbatim collapses whitespace before checking
:tt/:item, sor# : ttor comment-padded$ ($ t : t t) *would silently misclassify; cosmetic, not in scope of this PR. - Macro detection is heuristic string classification over masked source; if a future change adopts token-stream parsing it would introduce lifetime concerns at parser boundary, but current diff does not.
Verification questions
- Confirm no cargo-test receipt yet at gate time; PR body admits local lib tests were still running at push. Hosted CI is the proof-of-record per the PR's own REVIEW_INCOMPLETE admission; new test additions are syntactically valid Rust and structure matches prior class but platform evidence is not in the packet.
- Confirm a_passthrough_local_macro_defines_the_item_its_caller_spells mixes the declares_item_named (spelling path) and forwards_arguments_verbatim (passthrough path) routes in one assertion, so a regression in either branch would still pass; split per route or assert each branch's negative control independently.
- Confirm forwards_arguments_verbatim uses ':tt'/':item' substring match after whitespace squeeze; identifier-false-positive risk (e.g. a fragment binder named 'settle') is mitigated by the ':' requirement but never negatively tested.
- Confirm negative-control breadth for external-macro fn-name args is thin (only call/method/other-name/x::); a path-segment call
emit!(a::name(1))is covered by x::name() and mid-path renamed controluse name::leaf;lives in a different test, so a macro that emitspub fn nameafter a doc-comment or attribute list is the only newly-covered positive (#[inline] fn name,pub const fn name); both are exercised. - Confirm sibling callers of macro_may_define_item_named in other classify modules are not enumerated in the diff blast radius. Within
crates/ripr/src/analysis/classify, a grep would be needed to prove no other callee depends on the prior contract that nested (depth-0) groups are collapsed to a single(marker. The lane cannot claim that confidently without a search.
Parked follow-ups
- a_plain_import_inside_an_invoked_macro covers use other::name;, use other::{a, name};, use name;, but the change to declares_item_named also affects top-level imports outside any macro body — a parked follow-up to add a top-level use other::name; positive test, not a blocker.
…cros; split route tests Address review findings: forwards_arguments_verbatim now needs a :tt/:item matcher and a transcriber that emits a fragment; add inner::name and (name, x) negative controls; one test per detection route. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01JPWmsSED95rEHERuRACDEp
EffortlessSteven
left a comment
There was a problem hiding this comment.
REVIEW_READY for head 9e4ac21c.
Inspected: the full diff (one file, macro_item_names.rs), the semantic owner and its two consumers (ProbeContext::test_file_imports_foreign_callee_name and reveal::file_imports_foreign_callee_name, both through macro_may_define_item_named), test stimulus and oracle grip, and exact-head evidence.
- Direction: every change only adds shadow detection, so a macro-defined owner name earns less credit, never more. The actionability flip stays fail-closed, and no output, schema or public surface changes.
- Each new route has a positive case and a discriminating negative control:
fn namein arguments (call, method, path, other item, tuple group), passthrough macros (:tt/:itemwith a forwarding transcriber, versus other item, call only, dropped tokens, non-forwarding macro),useimports (rename, mid-path, other name) and nested macro groups (parenthesis, bracket, brace and path-qualified forms; call and braced-body negatives). - Bot findings addressed in this head:
forwards_arguments_verbatimnow requires a transcriber that emits a fragment;inner::nameand(name, x)controls added; tests split per route. Not changed: a comment betweeninner!and its group (source is masked before this runs), and non-ASCII or padded fragment spellings (cosmetic, conservative). - Proof:
cargo xtask precommitexit 0 on this head;cargo test -p ripr --lib macro_item_names10 passed;analysis::classifylib tests 1179 passed on the preceding head. Hosted checks on this head are green or skipped; the Rust test, Clippy and coverage lanes are skipped by the repo's gating, so hosted CI does not exercise this change. - Out of scope, still open on #8467: findings 3, 6 and 7.
CodeRabbit and Gemini were rate limited and did not review, so that review is missing, not clean.
Generated by Claude Code
|
Warning You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again! |
|
CI note for head The drift was three I merged Generated by Claude Code |
# Conflicts: # crates/ripr/src/analysis/classify/macro_item_names.rs
There was a problem hiding this comment.
Confirmed findings
- Sibling callers of macro_may_define_item_named outside this diff were not enumerated; the lane cannot guarantee no other route depends on the prior 'depth-0 characters' behavior of passes_name_as_bare_argument, only that the two known consumers are unaffected.
- No memory-safety seam exists in this PR. The changed code is pure string scanning that allocates only
String,Vec<bool>, andVec<&str>from already-borrowed&strinputs and returnsbool; there are no raw pointers, nounsafeblocks, noBox/Vec::from_raw_parts, no aliasing of&mut, and no lifetime extension beyond the inputsource: &str. The lane has no memory-lifetime objection. - passes_name_as_bare_argument accepts only
!adjacency for transparency; a comment (outer!(inner!/*x*/{name})) or trailing whitespace-then-comment defeats the rule. Missed detection only (fail-closed). Add positive control or relax to also accept after!followed by/*…*/.
Verification questions
- Confirm bot flagged that forwards_arguments_verbatim over-approximates any :tt/:item as sufficient. The dropped-tokens and :expr-only controls prove the matcher side, but no test exercises a :tt matcher whose transcriber forwards only a non-item fragment (e.g. $($t:tt)* => { stringify!($($t)*) }), leaving a residual gap for that exact shape.
Refuted
- passes_name_as_bare_argument transparent-group rule (
top_level.trim_end().ends_with('!')) could be bypassed by a comment betweeninner!and{, leaving top_level ending with '(' and silently dropping the inner argument from view, enabling a shadow to slip through and re-open an exploit primitive.; refuted because: A comment betweeninner!and{is plausible but the failure mode is missing detection (owner keeps credit), not a new security primitive; ripr's owner attribution feeds downstream scoring, not memory safety. The PR's direction is fail-closed with additive detection; relaxing this rule to also accept '(' after '!' is a correctness follow-up, not a security blocker. - imports_name would false-positive on substring matches like 'use_name::x' or 'use other::nameful'; refuted because: word_edge guards on both sides of 'use' keyword and on 'name' substring; plus the post-name check requires next non-ws char to be ','/'}'/end, so 'nameful' (next char 'f', alphanumeric, not comma/brace) returns false; 'use_name' is rejected because the char before 'use' is '_' (word_edge returns false).
- Open groups stack in passes_name_as_bare_argument could be reused as a resizable backing-store snapshot of masked_arguments, causing stale reads after a later tokenization pass.; refuted because: top_level is rebuilt per call from inner only; no length/suffix is shared across invocations or stored in a cell; the change is text re-derivation, not a cached active view over shared storage.
- forwards_arguments_verbatim accepts
:tt/:itemwith any$-bearing transcriber; e.g.$($t)* => { $t }captures but does not forward verbatim — still treated as defining. Direction stays fail-closed (extra credits are denied), so no overclaim.
Evidence gaps
- Model proof intent was rejected by deterministic validation.
Parked follow-ups
- Prior review flagged comment between inner! and brace group (outer!(inner!/x/{name})) as a gap; top_level.trim_end().ends_with('!') will be false because trim_end does not strip comments — sibling-paths notes this as parked sibling follow-up rather than fresh finding.
- forwards_arguments_verbatim is a deliberately loose heuristic (any :tt/:item matcher with a transcriber containing '$'); for the four partial-fix items in #8467 this is fail-closed (no owner credit flips direction), and a future tightening to require verbatim passthrough shape like
$($t)*=>$($t)*would reduce over-approximation with negligible test churn. Not in scope for this PR but worth a parked follow-up. - Two consumers of macro_may_define_item_named: ProbeContext::test_file_imports_foreign_callee_name and reveal::file_imports_foreign_callee_name; neither is in the diff but both inherit the new detection. Parked as sibling follow-up.
Summary
Partial fix for #8467, on top of #8515 (which already landed finding 1,
fn namein arguments, and whose implementation this branch now carries after the merge withmain). Inmacro_item_names.rs, a macro-defined owner name is also detected (so it earns no credit) for:$($t:tt)*/$i:itemmatcher with a transcriber that emits a fragment) whose caller spellsfn namein the arguments.use other::name;/use other::{a, name};inside an invoked macro body (renames and mid-path segments bind nothing).outer!(inner!(name))— groups opened by a macro call are read as top-level (paren, bracket, brace and path-qualified forms).Also adds extra negative controls around finding 1 (
inner::name,(name, x),other.name(),x::name()).Every shape has a discriminating negative control. All changes only add detection, so the direction stays fail-closed; no output, schema or public surface changes.
Not in this PR (remain open on #8467): finding 3 (statement-position non-local macros, deliberate false-positive trade-off), 6 (weak test credit), 7 (std macro list).
Proof
cargo test -p ripr --lib macro_item_names: 10 passed on the current head, after the merge that combined this branch with fix(macro-names): a macro argument declaring the owner with an item keyword may rebind it (#8467) #8515.cargo xtask goldens check: zero drift on the earlier merged tree;cargo xtask precommitexit 0 on9e4ac21c, re-run on the current head in progress.Rust gatesfailure on9e4ac21cwas golden drift inherited frommain(fixed by test(fixtures): bless 3 match_arm_tuple_terminal human goldens #8524), not this change.🤖 Generated with Claude Code
https://claude.ai/code/session_01JPWmsSED95rEHERuRACDEp