Skip to content

Commit 34c1792

Browse files
committed
fix(ast): retain dynamic getattr provenance
Signed-off-by: Deepak Jain <[email protected]>
1 parent f1917b5 commit 34c1792

2 files changed

Lines changed: 16 additions & 3 deletions

File tree

‎src/skillspector/nodes/analyzers/behavioral_ast.py‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -562,10 +562,15 @@ def _emit(
562562
elif call_name == "getattr" and len(ast_node.args) >= 2:
563563
second_arg = ast_node.args[1]
564564
resolved_name = _constant_string(second_arg)
565-
if resolved_name is None:
566-
_emit("AST7", ast_node)
567-
elif resolved_name in _DANGEROUS_GETATTR_NAMES:
565+
# A direct non-string literal cannot name an attribute. Do not
566+
# conflate it with a dynamic or constructed expression, which
567+
# remains an AST7 signal unless it resolves to an AST9 sink.
568+
if isinstance(second_arg, ast.Constant) and not isinstance(second_arg.value, str):
569+
continue
570+
if resolved_name in _DANGEROUS_GETATTR_NAMES:
568571
_emit("AST9", ast_node)
572+
elif resolved_name is None or not isinstance(second_arg, ast.Constant):
573+
_emit("AST7", ast_node)
569574

570575
return findings if budget is None else list(budget.current_findings)
571576

‎tests/nodes/analyzers/test_behavioral_ast.py‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,14 @@ def test_getattr_with_literal_no_finding(self):
202202
findings = _run(code)
203203
assert not any(f.rule_id == "AST7" for f in findings)
204204

205+
def test_getattr_with_direct_non_string_literal_is_silent(self):
206+
findings = _run("getattr(obj, 42)")
207+
assert not any(f.rule_id in ("AST7", "AST9") for f in findings)
208+
209+
def test_getattr_with_constructed_benign_name_remains_dynamic(self):
210+
findings = _run("getattr(subprocess, ''.join(['P', 'o', 'p', 'e', 'n']))(cmd)")
211+
assert any(f.rule_id == "AST7" for f in findings)
212+
205213

206214
class TestReflectiveGetattrExec:
207215
"""getattr(obj, "<sink>")(...) is a reflective handle on an exec/os sink.

0 commit comments

Comments
 (0)